You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

model_manager.cc 61 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "graph/load/new_model_manager/model_manager.h"
  17. #include <string>
  18. #include "common/dump/dump_manager.h"
  19. #include "common/l2_cache_optimize.h"
  20. #include "common/profiling/profiling_manager.h"
  21. #include "common/properties_manager.h"
  22. #include "framework/common/debug/ge_log.h"
  23. #include "framework/common/util.h"
  24. #include "graph/common/ge_call_wrapper.h"
  25. #include "graph/debug/ge_attr_define.h"
  26. #include "graph/load/new_model_manager/davinci_model.h"
  27. #include "graph/load/new_model_manager/davinci_model_parser.h"
  28. #include "model/ge_root_model.h"
  29. #include "graph/common/local_context.h"
  30. #include "common/formats/utils/formats_trans_utils.h"
  31. #include "hybrid/hybrid_davinci_model.h"
  32. namespace ge {
  33. thread_local uint32_t device_count = 0;
  34. namespace {
  35. const int kCmdParSize = 2;
  36. const int kDumpCmdPairSize = 2;
  37. const std::size_t kProfCmdParaMaxSize = 1000;
  38. const std::size_t kProfStartCmdParaSize = 2;
  39. const std::string kCmdTypeProfile = "profile";
  40. const std::string kCmdTypeDump = "dump";
  41. const std::string kCmdTypeProfiling = "profiling";
  42. const std::string kCmdTypeProfInit = "prof_init";
  43. const std::string kCmdTypeProfFinalize = "prof_finalize";
  44. const std::string kCmdTypeProfStart = "prof_start";
  45. const std::string kCmdTypeProfStop = "prof_stop";
  46. const std::string kCmdTypeProfModelSubscribe = "prof_model_subscribe";
  47. const std::string kCmdTypeProfModelUnsubscribe = "prof_model_cancel_subscribe";
  48. const char *const kBatchLoadBuf = "batchLoadsoFrombuf";
  49. const char *const kDeleteCustOp = "deleteCustOp";
  50. struct CustAicpuSoBuf {
  51. uint64_t kernelSoBuf;
  52. uint32_t kernelSoBufLen;
  53. uint64_t kernelSoName;
  54. uint32_t kernelSoNameLen;
  55. } __attribute__((packed));
  56. struct BatchLoadOpFromBufArgs {
  57. uint32_t soNum;
  58. uint64_t args;
  59. } __attribute__((packed));
  60. } // namespace
  61. DumpProperties ModelManager::dump_properties_;
  62. std::mutex ModelManager::exeception_infos_mutex_;
  63. std::shared_ptr<ModelManager> ModelManager::GetInstance() {
  64. static const std::shared_ptr<ModelManager> instance_ptr =
  65. shared_ptr<ModelManager>(new (std::nothrow) ModelManager(), ModelManager::FinalizeForPtr);
  66. return instance_ptr;
  67. }
  68. ModelManager::ModelManager() {
  69. max_model_id_ = 0;
  70. session_id_bias_ = 0;
  71. }
  72. Status ModelManager::KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType op_type, uint64_t session_id, uint32_t model_id) {
  73. STR_FWK_OP_KERNEL param_base = {};
  74. void *devicebase = nullptr;
  75. void *aicpu_kernel_addr = nullptr;
  76. const uint32_t kKernelType = 0;
  77. param_base.fwkKernelType = kKernelType;
  78. param_base.fwkKernelBase.fwk_kernel.opType = op_type;
  79. param_base.fwkKernelBase.fwk_kernel.sessionID = session_id;
  80. if (op_type == aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY) {
  81. std::vector<uint64_t> v_aicpu_kernel;
  82. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  83. auto iter = model_aicpu_kernel_.find(model_key);
  84. if (iter != model_aicpu_kernel_.end()) {
  85. GELOGD("kernel destroy session_id %lu, model_id %u.", session_id, model_id);
  86. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  87. // Insert size of aicpu kernel vector in the first element
  88. v_aicpu_kernel.insert(v_aicpu_kernel.begin(), v_aicpu_kernel.size());
  89. auto kernel_size = sizeof(uint64_t) * (v_aicpu_kernel.size());
  90. rtError_t rt_ret = rtMalloc(&aicpu_kernel_addr, kernel_size, RT_MEMORY_HBM);
  91. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret);
  92. return RT_ERROR_TO_GE_STATUS(rt_ret);)
  93. rt_ret = rtMemcpy(aicpu_kernel_addr, kernel_size, v_aicpu_kernel.data(), kernel_size, RT_MEMCPY_HOST_TO_DEVICE);
  94. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(RT_FAILED, "rtMemcpy to input_output_addr_ error: 0x%X", rt_ret);
  95. GE_CHK_RT(rtFree(aicpu_kernel_addr)); return RT_ERROR_TO_GE_STATUS(rt_ret);)
  96. uint64_t kernel_id_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(aicpu_kernel_addr));
  97. param_base.fwkKernelBase.fwk_kernel.kernelID = kernel_id_addr;
  98. // In the scene of loading once and running many times, the kernel needs to be destroyed many times,
  99. // and connot be removed from kernel map.
  100. }
  101. }
  102. rtError_t rt_ret = rtMalloc(&(devicebase), sizeof(STR_FWK_OP_KERNEL), RT_MEMORY_HBM);
  103. if (rt_ret != RT_ERROR_NONE) {
  104. GELOGE(RT_FAILED, "malloc device memory failed. ret: 0x%X", rt_ret);
  105. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  106. return RT_ERROR_TO_GE_STATUS(rt_ret);
  107. }
  108. rt_ret =
  109. rtMemcpy(devicebase, sizeof(STR_FWK_OP_KERNEL), &param_base, sizeof(STR_FWK_OP_KERNEL), RT_MEMCPY_HOST_TO_DEVICE);
  110. if (rt_ret != RT_ERROR_NONE) {
  111. GELOGE(RT_FAILED, "memory copy to device failed. ret: 0x%X", rt_ret);
  112. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  113. GE_CHK_RT(rtFree(devicebase));
  114. return RT_ERROR_TO_GE_STATUS(rt_ret);
  115. }
  116. rtStream_t stream = nullptr;
  117. rt_ret = rtStreamCreate(&stream, 0);
  118. if (rt_ret != RT_ERROR_NONE) {
  119. GELOGE(RT_FAILED, "create stream failed. ret: 0x%X", rt_ret);
  120. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  121. GE_CHK_RT(rtFree(devicebase));
  122. return RT_ERROR_TO_GE_STATUS(rt_ret);
  123. }
  124. rt_ret = rtKernelLaunchEx(devicebase, sizeof(STR_FWK_OP_KERNEL), 0, stream);
  125. if (rt_ret != RT_ERROR_NONE) {
  126. GELOGE(RT_FAILED, "rtKernelLaunchEx failed. ret: 0x%X", rt_ret);
  127. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  128. GE_CHK_RT(rtFree(devicebase));
  129. GE_CHK_RT(rtStreamDestroy(stream));
  130. return RT_ERROR_TO_GE_STATUS(rt_ret);
  131. }
  132. rt_ret = rtStreamSynchronize(stream);
  133. if (rt_ret != RT_ERROR_NONE) {
  134. GELOGE(RT_FAILED, "rtStreamSynchronize failed. ret: 0x%X", rt_ret);
  135. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  136. GE_CHK_RT(rtFree(devicebase));
  137. GE_CHK_RT(rtStreamDestroy(stream));
  138. return RT_ERROR_TO_GE_STATUS(rt_ret);
  139. }
  140. if (aicpu_kernel_addr != nullptr) {
  141. rt_ret = rtFree(aicpu_kernel_addr);
  142. if (rt_ret != RT_ERROR_NONE) {
  143. GELOGE(RT_FAILED, "free memory failed. ret: 0x%X", rt_ret);
  144. GE_CHK_RT(rtFree(devicebase));
  145. GE_CHK_RT(rtStreamDestroy(stream));
  146. return RT_ERROR_TO_GE_STATUS(rt_ret);
  147. }
  148. }
  149. rt_ret = rtFree(devicebase);
  150. if (rt_ret != RT_ERROR_NONE) {
  151. GELOGE(RT_FAILED, "free memory failed. ret: 0x%X", rt_ret);
  152. GE_CHK_RT(rtStreamDestroy(stream));
  153. return RT_ERROR_TO_GE_STATUS(rt_ret);
  154. }
  155. rt_ret = rtStreamDestroy(stream);
  156. if (rt_ret != RT_ERROR_NONE) {
  157. GELOGE(RT_FAILED, "rtStreamDestroy failed. ret: 0x%X", rt_ret);
  158. return RT_ERROR_TO_GE_STATUS(rt_ret);
  159. }
  160. return SUCCESS;
  161. }
  162. void ModelManager::DestroyAicpuSession(uint64_t session_id) {
  163. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  164. auto it = sess_ids_.find(session_id);
  165. if (it == sess_ids_.end()) {
  166. GELOGI("The session: %lu not created.", session_id);
  167. return;
  168. } else {
  169. rtContext_t ctx = nullptr;
  170. bool has_ctx = (rtCtxGetCurrent(&ctx) == RT_ERROR_NONE);
  171. if (!has_ctx) {
  172. GELOGI("Set device %u.", GetContext().DeviceId());
  173. GE_CHK_RT(rtSetDevice(static_cast<int32_t>(GetContext().DeviceId())));
  174. }
  175. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_DESTROY, session_id, 0);
  176. if (ret != SUCCESS) {
  177. GELOGW("The session: %lu destroy failed.", session_id);
  178. } else {
  179. (void)sess_ids_.erase(session_id);
  180. GELOGI("The session: %lu destroyed.", session_id);
  181. }
  182. if (!has_ctx) {
  183. GELOGI("Reset device %u.", GetContext().DeviceId());
  184. GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId())));
  185. }
  186. }
  187. }
  188. ge::Status ModelManager::DestroyAicpuSessionForInfer(uint32_t model_id) {
  189. std::lock_guard<std::mutex> lock(map_mutex_);
  190. auto hybrid_davinci_model = hybrid_model_map_.find(model_id);
  191. if (hybrid_davinci_model != hybrid_model_map_.end()) {
  192. uint64_t session_id = hybrid_davinci_model->second->GetSessionId();
  193. DestroyAicpuSession(session_id);
  194. return SUCCESS;
  195. }
  196. auto it = model_map_.find(model_id);
  197. if (it == model_map_.end()) {
  198. GELOGE(GE_EXEC_MODEL_ID_INVALID, "model id %u does not exists.", model_id);
  199. return GE_EXEC_MODEL_ID_INVALID;
  200. }
  201. uint64_t session_id = it->second->GetSessionId();
  202. DestroyAicpuSession(session_id);
  203. return SUCCESS;
  204. }
  205. ge::Status ModelManager::DestroyAicpuKernel(uint64_t session_id, uint32_t model_id) {
  206. GELOGD("destroy aicpu kernel in session_id %lu, model_id %u.", session_id, model_id);
  207. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  208. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  209. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  210. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY, session_id, model_id);
  211. if (ret != SUCCESS) {
  212. GELOGE(FAILED, "Destroy aicpu kernel failed.");
  213. return FAILED;
  214. }
  215. }
  216. return SUCCESS;
  217. }
  218. ge::Status ModelManager::CreateAicpuKernel(uint64_t session_id, uint32_t model_id, uint64_t kernel_id) {
  219. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  220. std::vector<uint64_t> v_aicpu_kernel;
  221. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  222. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  223. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  224. }
  225. v_aicpu_kernel.push_back(kernel_id);
  226. model_aicpu_kernel_[model_key] = v_aicpu_kernel;
  227. return SUCCESS;
  228. }
  229. ModelManager::~ModelManager() {
  230. std::lock_guard<std::mutex> lock(map_mutex_);
  231. model_map_.clear();
  232. model_aicpu_kernel_.clear();
  233. cust_aicpu_so_.clear();
  234. GE_IF_BOOL_EXEC(device_count > 0, GE_CHK_RT(rtDeviceReset(0)));
  235. }
  236. ///
  237. /// @ingroup domi_ome
  238. /// @brief set Device. If no device available, return failure
  239. /// @return Status run result
  240. /// @author
  241. ///
  242. Status ModelManager::SetDevice(int32_t deviceId) const {
  243. GE_CHK_RT_RET(rtSetDevice(deviceId));
  244. return SUCCESS;
  245. }
  246. ge::Status ModelManager::SetDynamicSize(uint32_t model_id, const std::vector<uint64_t> &batch_num,
  247. int32_t dynamic_type) {
  248. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  249. GE_CHECK_NOTNULL(davinci_model);
  250. davinci_model->SetDynamicSize(batch_num, dynamic_type);
  251. return SUCCESS;
  252. }
  253. ge::Status ModelManager::DoLoadHybridModelOnline(uint32_t model_id, const shared_ptr<ge::GeRootModel> &ge_root_model,
  254. const shared_ptr<ModelListener> &listener) {
  255. auto hybrid_model = hybrid::HybridDavinciModel::Create(ge_root_model);
  256. GE_CHECK_NOTNULL(hybrid_model);
  257. hybrid_model->SetListener(listener);
  258. hybrid_model->SetModelId(model_id);
  259. hybrid_model->SetDeviceId(GetContext().DeviceId());
  260. GE_CHK_STATUS_RET(hybrid_model->Init(), "Failed to init hybrid model. model_id = %u", model_id);
  261. auto shared_model = std::shared_ptr<hybrid::HybridDavinciModel>(hybrid_model.release());
  262. InsertModel(model_id, shared_model);
  263. return SUCCESS;
  264. }
  265. ///
  266. /// @ingroup domi_ome
  267. /// @brief load model online
  268. /// @return Status run result
  269. ///
  270. Status ModelManager::LoadModelOnline(uint32_t &model_id, const shared_ptr<ge::GeRootModel> &ge_root_model,
  271. std::shared_ptr<ModelListener> listener) {
  272. GE_CHK_BOOL_RET_STATUS(listener.get() != nullptr, PARAM_INVALID, "Param incorrect, listener is null");
  273. if (model_id == INVALID_MODEL_ID) {
  274. GenModelId(&model_id);
  275. }
  276. bool is_shape_unknown = false;
  277. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_shape_unknown), "CheckIsUnknownShape failed, model id:%u",
  278. model_id);
  279. if (is_shape_unknown || GetContext().GetHostExecFlag()) {
  280. return DoLoadHybridModelOnline(model_id, ge_root_model, listener);
  281. }
  282. GE_CHK_STATUS_RET(SetDevice(static_cast<int32_t>(GetContext().DeviceId())), "Set device failed, model id:%u.",
  283. model_id);
  284. mmTimespec timespec = mmGetTickCount();
  285. std::shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(0, listener);
  286. if (davinci_model == nullptr) {
  287. GELOGE(FAILED, "davinci_model is nullptr");
  288. return FAILED;
  289. }
  290. davinci_model->SetId(model_id);
  291. davinci_model->SetDeviceId(GetContext().DeviceId());
  292. const DumpProperties &dump_properties = PropertiesManager::Instance().GetDumpProperties(GetContext().SessionId());
  293. davinci_model->SetDumpProperties(dump_properties);
  294. dump_properties_ = dump_properties;
  295. auto root_graph = ge_root_model->GetRootGraph();
  296. GE_CHECK_NOTNULL(root_graph);
  297. string root_model_name = root_graph->GetName();
  298. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  299. GeModelPtr ge_model = name_to_model[root_model_name];
  300. Status ret = SUCCESS;
  301. do {
  302. GE_TIMESTAMP_START(Assign);
  303. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Assign(ge_model)), GELOGW("assign model to modeldef failed.");
  304. break;);
  305. GE_TIMESTAMP_END(Assign, "GraphLoader::ModelAssign");
  306. GE_TIMESTAMP_START(Init);
  307. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Init()), GELOGW("DavinciInit failed."); break;);
  308. GE_TIMESTAMP_END(Init, "GraphLoader::ModelInit");
  309. InsertModel(model_id, davinci_model);
  310. GELOGI("Parse model %u success.", model_id);
  311. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * 1000 * 1000 * 1000 +
  312. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  313. davinci_model->SetProfileTime(MODEL_LOAD_END);
  314. } while (0);
  315. GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId())));
  316. return ret;
  317. }
  318. void ModelManager::InsertModel(uint32_t id, std::shared_ptr<DavinciModel> &davinci_model) {
  319. GE_CHK_BOOL_EXEC(davinci_model != nullptr, return, "davinci_model ptr is null, id: %u", id);
  320. std::lock_guard<std::mutex> lock(map_mutex_);
  321. model_map_[id] = davinci_model;
  322. }
  323. void ModelManager::InsertModel(uint32_t id, shared_ptr<hybrid::HybridDavinciModel> &hybrid_model) {
  324. GE_CHK_BOOL_EXEC(hybrid_model != nullptr, return, "hybrid_model ptr is null, id: %u", id);
  325. std::lock_guard<std::mutex> lock(map_mutex_);
  326. hybrid_model_map_[id] = hybrid_model;
  327. }
  328. Status ModelManager::DeleteModel(uint32_t id) {
  329. std::lock_guard<std::mutex> lock(map_mutex_);
  330. auto it = model_map_.find(id);
  331. auto hybrid_model_it = hybrid_model_map_.find(id);
  332. if (it != model_map_.end()) {
  333. uint64_t session_id = it->second->GetSessionId();
  334. std::string model_key = std::to_string(session_id) + "_" + std::to_string(id);
  335. auto iter_aicpu_kernel = model_aicpu_kernel_.find(model_key);
  336. if (iter_aicpu_kernel != model_aicpu_kernel_.end()) {
  337. (void)model_aicpu_kernel_.erase(iter_aicpu_kernel);
  338. }
  339. (void)model_map_.erase(it);
  340. } else if (hybrid_model_it != hybrid_model_map_.end()) {
  341. (void)hybrid_model_map_.erase(hybrid_model_it);
  342. } else {
  343. GELOGE(GE_EXEC_MODEL_ID_INVALID, "model id %u does not exists.", id);
  344. return GE_EXEC_MODEL_ID_INVALID;
  345. }
  346. return SUCCESS;
  347. }
  348. std::shared_ptr<DavinciModel> ModelManager::GetModel(uint32_t id) {
  349. std::lock_guard<std::mutex> lock(map_mutex_);
  350. auto it = model_map_.find(id);
  351. return (it == model_map_.end()) ? nullptr : it->second;
  352. }
  353. std::shared_ptr<hybrid::HybridDavinciModel> ModelManager::GetHybridModel(uint32_t id) {
  354. std::lock_guard<std::mutex> lock(map_mutex_);
  355. auto it = hybrid_model_map_.find(id);
  356. return (it == hybrid_model_map_.end()) ? nullptr : it->second;
  357. }
  358. Status ModelManager::Unload(uint32_t model_id) {
  359. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload model id: %u", model_id);
  360. if (device_count > 0) {
  361. device_count--;
  362. GELOGI("Unload model %u success.", model_id);
  363. } else {
  364. GELOGI("Unload model %u success.no need reset device,device_count: %u", model_id, device_count);
  365. }
  366. std::lock_guard<std::mutex> lock(exeception_infos_mutex_);
  367. exception_infos_.clear();
  368. return SUCCESS;
  369. }
  370. Status ModelManager::UnloadModeldef(uint32_t model_id) {
  371. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload modeldef id: %u", model_id);
  372. return SUCCESS;
  373. }
  374. Status ModelManager::DataInput(const InputData &input_data, OutputData &output_data) {
  375. GELOGI("calling the DataInput");
  376. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  377. GE_CHECK_NOTNULL(data_wrap);
  378. Status status = data_wrap->Init(input_data, output_data);
  379. if (status != SUCCESS) {
  380. GELOGE(domi::PUSH_DATA_FAILED, "Init InputDataWrapper failed, input data index: %u.", input_data.index);
  381. return domi::PUSH_DATA_FAILED;
  382. }
  383. uint32_t model_id = input_data.model_id;
  384. output_data.model_id = model_id;
  385. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  386. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid model id %u in InputData! ", model_id);
  387. GE_IF_BOOL_EXEC(model->GetDataInputTid() == 0, model->SetDataInputTid(mmGetTid()));
  388. DataInputer *inputer = model->GetDataInputer();
  389. GE_CHECK_NOTNULL(inputer);
  390. if (inputer->Push(data_wrap) != SUCCESS) {
  391. GELOGE(domi::DATA_QUEUE_ISFULL, "Data queue is full, please call again later, model_id %u ", model_id);
  392. return domi::DATA_QUEUE_ISFULL;
  393. }
  394. GELOGD("Data input success, model id:%u", model_id);
  395. return SUCCESS;
  396. }
  397. Status ModelManager::GetCurDynamicDims(const vector<vector<int64_t>> &user_real_input_dims,
  398. const vector<pair<string, vector<int64_t>>> &user_input_dims,
  399. vector<int64_t> &cur_dynamic_dims) {
  400. GELOGD(" Start get cur dynamic dims.");
  401. if (user_real_input_dims.size() != user_input_dims.size()) {
  402. GELOGE(INTERNAL_ERROR,
  403. "The input count of user: %zu should be equal to the data count of graph: %zu",
  404. user_real_input_dims.size(), user_input_dims.size());
  405. return INTERNAL_ERROR;
  406. }
  407. for (size_t i = 0; i < user_input_dims.size(); ++i) {
  408. if (user_real_input_dims[i].size() != user_input_dims[i].second.size()) {
  409. GELOGE(INTERNAL_ERROR,
  410. "The shape size: %zu of dynamic input: %s should be equal to the shape size of input shape: %zu.",
  411. user_real_input_dims[i].size(), user_input_dims[i].first.c_str(), user_input_dims[i].second.size());
  412. return INTERNAL_ERROR;
  413. }
  414. for (size_t j = 0; j < user_input_dims.at(i).second.size(); ++j) {
  415. if (user_input_dims.at(i).second.at(j) < 0) {
  416. cur_dynamic_dims.emplace_back(user_real_input_dims[i][j]);
  417. }
  418. }
  419. }
  420. GELOGD("Cur dynamic dims is %s.", formats::JoinToString(cur_dynamic_dims).c_str());
  421. bool cur_dynamic_dims_valid = false;
  422. std::vector<std::string> shape_strs = ge::StringUtils::Split(GetLocalOmgContext().dynamic_dims, ';');
  423. for (auto dynamic_dim : shape_strs) {
  424. if (dynamic_dim == formats::JoinToString(cur_dynamic_dims)) {
  425. cur_dynamic_dims_valid = true;
  426. break;
  427. }
  428. }
  429. if (!cur_dynamic_dims_valid) {
  430. GELOGE(INTERNAL_ERROR, "Cur dynamic dims is %s, not exist in options.",
  431. formats::JoinToString(cur_dynamic_dims).c_str());
  432. return INTERNAL_ERROR;
  433. }
  434. return SUCCESS;
  435. }
  436. ///
  437. /// @ingroup domi_ome
  438. /// @brief load Input and output TensorInfo for Model
  439. /// @return Status run result
  440. ///
  441. Status ModelManager::DataInputTensor(uint32_t model_id, const std::vector<InputTensorInfo> &inputs) {
  442. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  443. auto hybrid_model = GetHybridModel(model_id);
  444. if (hybrid_model == nullptr) {
  445. GE_CHECK_NOTNULL(model);
  446. }
  447. InputData input_data;
  448. input_data.model_id = model_id;
  449. input_data.timeout = 0;
  450. input_data.timestamp = 0;
  451. input_data.index = 0;
  452. for (size_t i = 0; i < inputs.size(); ++i) {
  453. DataBuffer data;
  454. data.data = inputs[i].data;
  455. data.length = inputs[i].length;
  456. input_data.blobs.push_back(data);
  457. }
  458. if (!GetLocalOmgContext().user_input_dims.empty() && GetLocalOmgContext().need_multi_batch) {
  459. std::vector<int64_t> cur_dynamic_dims;
  460. if (!GetLocalOmgContext().user_real_input_dims.empty()) {
  461. if (GetCurDynamicDims(GetLocalOmgContext().user_real_input_dims, GetLocalOmgContext().user_input_dims,
  462. cur_dynamic_dims) != SUCCESS) {
  463. GELOGE(INTERNAL_ERROR, "[Train_Dynamic] Failed to Parse real_dynamic_dims.");
  464. return INTERNAL_ERROR;
  465. }
  466. DataBuffer data;
  467. data.data = new(std::nothrow) int64_t[cur_dynamic_dims.size()];
  468. GE_CHECK_NOTNULL(data.data);
  469. uint64_t length = static_cast<uint64_t>(cur_dynamic_dims.size() * sizeof(int64_t));
  470. GE_CHK_BOOL_EXEC(memcpy_s(data.data, length, cur_dynamic_dims.data(), length) == EOK, return INTERNAL_ERROR,
  471. "Failed to memcpy data.");
  472. data.length = length;
  473. input_data.blobs.push_back(data);
  474. }
  475. }
  476. OutputData output_data;
  477. output_data.model_id = model_id;
  478. output_data.index = 0;
  479. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  480. GE_CHECK_NOTNULL(data_wrap);
  481. GE_CHK_STATUS_EXEC(data_wrap->Init(input_data, output_data), return domi::PUSH_DATA_FAILED,
  482. "Init InputDataWrapper failed,input data model_id is : %u.", model_id);
  483. if (hybrid_model != nullptr) {
  484. GE_CHK_STATUS_RET(hybrid_model->EnqueueData(data_wrap), "Data queue is full, please call again later, model_id %u ",
  485. model_id);
  486. return SUCCESS;
  487. }
  488. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid model id %u in InputData! ", model_id);
  489. DataInputer *inputer = model->GetDataInputer();
  490. GE_CHECK_NOTNULL(inputer);
  491. GE_CHK_STATUS_EXEC(inputer->Push(data_wrap), return domi::DATA_QUEUE_ISFULL,
  492. "Data queue is full, please call again later, model_id %u ", model_id);
  493. GELOGD("Data input success, model id:%u", model_id);
  494. return SUCCESS;
  495. }
  496. ///
  497. /// @ingroup domi_ome
  498. /// @brief create model thread, start to execute model
  499. /// @param [in] model_id Model ID to be started
  500. /// @return Status model run result
  501. /// @author
  502. ///
  503. Status ModelManager::Start(uint32_t model_id) {
  504. auto hybrid_model = GetHybridModel(model_id);
  505. if (hybrid_model != nullptr) {
  506. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStart());
  507. GELOGI("Start hybrid model %u success.", model_id);
  508. return SUCCESS;
  509. }
  510. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  511. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid model id %u to start! ", model_id);
  512. Status status = davinci_model->ModelRunStart();
  513. if (status == SUCCESS) {
  514. GELOGI("Start model %u success.", model_id);
  515. }
  516. return status;
  517. }
  518. ///
  519. /// @ingroup domi_ome
  520. /// @brief Model ID stop
  521. /// @only when unloaded
  522. /// @param [in] model_id Model ID to be stopped
  523. /// @return Status model stop result
  524. /// @author
  525. ///
  526. Status ModelManager::Stop(uint32_t model_id) {
  527. auto hybrid_model = GetHybridModel(model_id);
  528. if (hybrid_model != nullptr) {
  529. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStop());
  530. GELOGI("Stop hybrid model %u success.", model_id);
  531. return SUCCESS;
  532. }
  533. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  534. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid model id %u to stop!", model_id);
  535. Status status = davinci_model->ModelRunStop();
  536. if (status == SUCCESS) {
  537. GELOGI("Stop model %u success.", model_id);
  538. }
  539. return status;
  540. }
  541. ///
  542. /// @ingroup domi_ome
  543. /// @brief Command handle
  544. /// @iterator 1 only Ieference, Debug 2 modes
  545. /// @param [in] command command to handle
  546. /// @return Status command handle result
  547. /// @author
  548. ///
  549. Status ModelManager::HandleCommand(const Command &command) {
  550. static const std::map<std::string, std::function<uint32_t(const Command &)>> cmds = {
  551. {kCmdTypeProfile, HandleProfileCommand}, {kCmdTypeDump, HandleDumpCommand},
  552. {kCmdTypeProfiling, HandleAclProfilingCommand}, {kCmdTypeProfInit, HandleProfInitCommand},
  553. {kCmdTypeProfFinalize, HandleProfFinalizeCommand}, {kCmdTypeProfStart, HandleProfStartCommand},
  554. {kCmdTypeProfStop, HandleProfStopCommand},
  555. {kCmdTypeProfModelSubscribe, HandleProfModelSubscribeCommand},
  556. {kCmdTypeProfModelUnsubscribe, HandleProfModelUnsubscribeCommand}};
  557. auto iter = cmds.find(command.cmd_type);
  558. if (iter == cmds.end()) {
  559. GELOGE(PARAM_INVALID, "Unsupported command: %s", command.cmd_type.c_str());
  560. return PARAM_INVALID;
  561. } else {
  562. return iter->second(command);
  563. }
  564. }
  565. Status ModelManager::HandleAclProfilingCommand(const Command &command) {
  566. if (command.cmd_params.size() < kCmdParSize) {
  567. GELOGE(PARAM_INVALID, "When the cmd_type is 'profiling', the size of cmd_params must larger than 2.");
  568. return PARAM_INVALID;
  569. }
  570. std::string map_key = command.cmd_params[0];
  571. std::string value = command.cmd_params[1];
  572. if (map_key == PROFILE_CONFIG) {
  573. ProfilingManager::Instance().SetProfilingConfig(value);
  574. }
  575. return SUCCESS;
  576. }
  577. Status ModelManager::GetModelByCmd(const Command &command,
  578. std::shared_ptr<DavinciModel> &davinci_model) {
  579. if (command.cmd_params.size() < kCmdParSize) {
  580. GELOGE(PARAM_INVALID, "When the cmd_type is '%s', the size of cmd_params must larger than 2.",
  581. command.cmd_type.c_str());
  582. return PARAM_INVALID;
  583. }
  584. std::string map_key = command.cmd_params[0];
  585. std::string value = command.cmd_params[1];
  586. if (map_key == PROFILE_MODEL_ID) {
  587. int32_t model_id = 0;
  588. try {
  589. model_id = std::stoi(value);
  590. } catch (std::invalid_argument &) {
  591. GELOGE(PARAM_INVALID, "Model id: %s is invalid.", value.c_str());
  592. return PARAM_INVALID;
  593. } catch (std::out_of_range &) {
  594. GELOGE(PARAM_INVALID, "Model id: %s is out of range.", value.c_str());
  595. return PARAM_INVALID;
  596. } catch (...) {
  597. GELOGE(FAILED, "Model id: %s cannot change to int.", value.c_str());
  598. return FAILED;
  599. }
  600. auto model_manager = ModelManager::GetInstance();
  601. GE_CHECK_NOTNULL(model_manager);
  602. davinci_model = model_manager->GetModel(static_cast<uint32_t>(model_id));
  603. if (davinci_model == nullptr) {
  604. GELOGE(FAILED, "Model id: %d is invaild or model is not loaded.", model_id);
  605. return FAILED;
  606. }
  607. } else {
  608. GELOGE(FAILED, "The model_id parameter is not found in the command.");
  609. return FAILED;
  610. }
  611. return SUCCESS;
  612. }
  613. Status ModelManager::HandleProfModelSubscribeCommand(const Command &command) {
  614. std::shared_ptr<DavinciModel> davinci_model = nullptr;
  615. Status ret = GetModelByCmd(command, davinci_model);
  616. if (ret != SUCCESS) {
  617. return ret;
  618. }
  619. if (ProfilingManager::Instance().ProfModelSubscribe(command.module_index,
  620. static_cast<void *>(davinci_model.get())) != SUCCESS) {
  621. GELOGE(FAILED, "Handle prof model subscribe failed.");
  622. return FAILED;
  623. }
  624. return SUCCESS;
  625. }
  626. Status ModelManager::HandleProfModelUnsubscribeCommand(const Command &command) {
  627. std::shared_ptr<DavinciModel> davinci_model = nullptr;
  628. Status ret = GetModelByCmd(command, davinci_model);
  629. if (ret != SUCCESS) {
  630. return ret;
  631. }
  632. if (ProfilingManager::Instance().ProfModelUnsubscribe(static_cast<void *>(davinci_model.get())) != SUCCESS) {
  633. GELOGE(FAILED, "Handle prof model unsubscribe failed.");
  634. return FAILED;
  635. }
  636. return SUCCESS;
  637. }
  638. Status ModelManager::HandleProfInitCommand(const Command &command) {
  639. uint64_t module_index = command.module_index;
  640. if (ProfilingManager::Instance().ProfInit(module_index) != SUCCESS) {
  641. GELOGE(FAILED, "Handle prof init failed.");
  642. return FAILED;
  643. }
  644. return SUCCESS;
  645. }
  646. Status ModelManager::HandleProfFinalizeCommand(const Command &command) {
  647. if (ProfilingManager::Instance().ProfFinalize() != SUCCESS) {
  648. GELOGE(FAILED, "Handle prof finalize failed.");
  649. return FAILED;
  650. }
  651. return SUCCESS;
  652. }
  653. /*
  654. * cmd para when prof start
  655. * "devNums:2"
  656. * "devIdList:1,2"
  657. * "profilingOption:PROF_OP_TRACE"
  658. * "aicoreMetrics:AICORE_ARITHMATIC_THROUGHPUT"
  659. */
  660. Status ModelManager::HandleProfStartCommand(const Command &command) {
  661. if (command.cmd_params.size() < kProfStartCmdParaSize) {
  662. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile start', the size of cmd_params must larger than 2.");
  663. return PARAM_INVALID;
  664. }
  665. if (command.cmd_params.size() > kProfCmdParaMaxSize) {
  666. GELOGE(PARAM_INVALID, "Command para size[%zu] larger than max[1000].", command.cmd_params.size());
  667. return PARAM_INVALID;
  668. }
  669. std::map<std::string, std::string> cmd_params_map;
  670. uint32_t step = 2;
  671. for (uint32_t i = 0; i < command.cmd_params.size(); i += step) {
  672. if (i + 1 >= command.cmd_params.size()) {
  673. continue;
  674. }
  675. cmd_params_map[command.cmd_params[i]] = command.cmd_params[i + 1];
  676. }
  677. uint64_t module_index = command.module_index;
  678. if (ProfilingManager::Instance().ProfStartProfiling(module_index, cmd_params_map) != SUCCESS) {
  679. GELOGE(FAILED, "Handle prof start failed.");
  680. return FAILED;
  681. }
  682. return SUCCESS;
  683. }
  684. Status ModelManager::HandleProfStopCommand(const Command &command) {
  685. if (command.cmd_params.size() < kProfStartCmdParaSize) {
  686. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile stop', the size of cmd_params must larger than 2.");
  687. return PARAM_INVALID;
  688. }
  689. if (command.cmd_params.size() > kProfCmdParaMaxSize) {
  690. GELOGE(PARAM_INVALID, "Command para size[%zu] larger than max[1000].", command.cmd_params.size());
  691. return PARAM_INVALID;
  692. }
  693. std::map<std::string, std::string> cmd_params_map;
  694. uint32_t step = 2;
  695. for (uint32_t i = 0; i < command.cmd_params.size(); i += step) {
  696. if (i + 1 >= command.cmd_params.size()) {
  697. continue;
  698. }
  699. cmd_params_map[command.cmd_params[i]] = command.cmd_params[i + 1];
  700. }
  701. uint64_t module_index = command.module_index;
  702. if (ProfilingManager::Instance().ProfStopProfiling(module_index, cmd_params_map) != SUCCESS) {
  703. GELOGE(FAILED, "Handle prof finalize failed.");
  704. return FAILED;
  705. }
  706. return SUCCESS;
  707. }
  708. Status ModelManager::HandleProfileCommand(const Command &command) {
  709. if (command.cmd_params.size() < kCmdParSize) {
  710. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile', the size of cmd_params must larger than 2.");
  711. return PARAM_INVALID;
  712. }
  713. std::string map_key = command.cmd_params[0];
  714. std::string value = command.cmd_params[1];
  715. GELOGI("Profiling mode, Command key:%s , value:%s ", map_key.c_str(), value.c_str());
  716. auto iter = PROFILE_COMPONENT_MAP.find(map_key);
  717. if (iter != PROFILE_COMPONENT_MAP.end()) {
  718. std::string property_value = (value == "on") ? "1" : "0";
  719. PropertiesManager::Instance().SetPropertyValue(iter->second, property_value);
  720. }
  721. if ((map_key == PROFILER_JOBCTX || map_key == PROFILER_TARGET_PATH || map_key == RTS_PROFILE_PATH)) {
  722. PropertiesManager::Instance().SetPropertyValue(map_key, value);
  723. }
  724. return SUCCESS;
  725. }
  726. static Status ParserPara(const Command &command, const string &dump_key, string &dump_value) {
  727. auto iter = std::find(command.cmd_params.begin(), command.cmd_params.end(), dump_key);
  728. if (iter != command.cmd_params.end()) {
  729. ++iter;
  730. if (iter == command.cmd_params.end()) {
  731. GELOGE(PARAM_INVALID, "Invalid access.");
  732. return PARAM_INVALID;
  733. }
  734. dump_value = *iter;
  735. }
  736. return SUCCESS;
  737. }
  738. Status ModelManager::HandleDumpCommand(const Command &command) {
  739. if (command.cmd_params.size() % kDumpCmdPairSize != 0) {
  740. GELOGE(PARAM_INVALID, "When the cmd_type is 'dump', the size of cmd_params must be a even number.");
  741. return PARAM_INVALID;
  742. }
  743. std::string dump_status("off");
  744. std::string dump_model(DUMP_ALL_MODEL);
  745. std::string dump_path("/");
  746. std::string dump_mode("output");
  747. std::set<std::string> dump_layers;
  748. auto ret = ParserPara(command, DUMP_STATUS, dump_status);
  749. if (ret != SUCCESS) {
  750. GELOGE(PARAM_INVALID, "parser dump status failed");
  751. return FAILED;
  752. }
  753. GELOGI("dump status = %s.", dump_status.c_str());
  754. ret = ParserPara(command, DUMP_MODEL, dump_model);
  755. if (ret != SUCCESS) {
  756. GELOGE(PARAM_INVALID, "parser dump model failed");
  757. return FAILED;
  758. }
  759. GELOGI("dump model = %s.", dump_model.c_str());
  760. if (dump_status == "off" || dump_status == "OFF") {
  761. dump_properties_.DeletePropertyValue(dump_model);
  762. return SUCCESS;
  763. }
  764. for (size_t i = 0; i < command.cmd_params.size() / kDumpCmdPairSize; ++i) {
  765. if (command.cmd_params.at(i * kDumpCmdPairSize).find(DUMP_LAYER) != std::string::npos) {
  766. GELOGI("dump layer: %s.", command.cmd_params.at(i * kDumpCmdPairSize + 1).c_str());
  767. dump_layers.insert(command.cmd_params.at(i * kDumpCmdPairSize + 1));
  768. }
  769. }
  770. ret = ParserPara(command, DUMP_FILE_PATH, dump_path);
  771. if (ret != SUCCESS) {
  772. GELOGE(PARAM_INVALID, "parser dump path failed");
  773. return FAILED;
  774. }
  775. if (!dump_path.empty() && dump_path[dump_path.size() - 1] != '/') {
  776. dump_path = dump_path + "/";
  777. }
  778. dump_path = dump_path + CurrentTimeInStr() + "/";
  779. GELOGI("dump path = %s.", dump_path.c_str());
  780. ret = ParserPara(command, DUMP_MODE, dump_mode);
  781. if (ret != SUCCESS) {
  782. GELOGE(PARAM_INVALID, "parser dump mode failed");
  783. return FAILED;
  784. }
  785. GELOGI("dump mode = %s", dump_mode.c_str());
  786. dump_properties_.AddPropertyValue(dump_model, dump_layers);
  787. dump_properties_.SetDumpPath(dump_path);
  788. dump_properties_.SetDumpMode(dump_mode);
  789. return SUCCESS;
  790. }
  791. Status ModelManager::GetMaxUsedMemory(const uint32_t model_id, uint64_t &max_size) {
  792. auto hybrid_model = GetHybridModel(model_id);
  793. if (hybrid_model != nullptr) {
  794. max_size = 0;
  795. return SUCCESS;
  796. }
  797. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  798. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetMaxUsedMemory Failed, Invalid model id %u!",
  799. model_id);
  800. max_size = davinci_model->TotalMemSize();
  801. return SUCCESS;
  802. }
  803. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  804. vector<InputOutputDescInfo> &output_desc) {
  805. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  806. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid model id %u!",
  807. model_id);
  808. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc);
  809. }
  810. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  811. vector<InputOutputDescInfo> &output_desc,
  812. std::vector<uint32_t> &inputFormats, std::vector<uint32_t> &outputFormats,
  813. bool new_model_desc) {
  814. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  815. if (hybrid_davinci_model != nullptr) {
  816. hybrid_davinci_model->SetModelDescVersion(new_model_desc);
  817. return hybrid_davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats);
  818. }
  819. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  820. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, GE_EXEC_MODEL_ID_INVALID,
  821. "GetInputOutputDescInfo Failed, Invalid model id %u!", model_id);
  822. davinci_model->SetModelDescVersion(new_model_desc);
  823. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats);
  824. }
  825. ///
  826. /// @ingroup ge
  827. /// @brief Get dynamic batch_info
  828. /// @param [in] model_id
  829. /// @param [out] batch_info
  830. /// @return execute result
  831. ///
  832. Status ModelManager::GetDynamicBatchInfo(const uint32_t model_id, std::vector<std::vector<int64_t>> &batch_info,
  833. int32_t &dynamic_type) {
  834. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  835. if (hybrid_davinci_model != nullptr) {
  836. return hybrid_davinci_model->GetDynamicBatchInfo(batch_info, dynamic_type);
  837. }
  838. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  839. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  840. "GetDynamicBatchInfo failed, Invalid model id %u!", model_id);
  841. return davinci_model->GetDynamicBatchInfo(batch_info, dynamic_type);
  842. }
  843. ///
  844. /// @ingroup ge
  845. /// @brief Get combined dynamic dims info
  846. /// @param [in] model_id
  847. /// @param [out] batch_info
  848. /// @return execute result
  849. ///
  850. Status ModelManager::GetCombinedDynamicDims(const uint32_t model_id, vector<vector<int64_t>> &batch_info) {
  851. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  852. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  853. "GetCombinedDynamicDims Failed, Invalid Model ID %u!", model_id);
  854. davinci_model->GetCombinedDynamicDims(batch_info);
  855. return SUCCESS;
  856. }
  857. ///
  858. /// @ingroup ge
  859. /// @brief Get user designate shape order
  860. /// @param [in] model_id
  861. /// @param [out] user_input_shape_order
  862. /// @return execute result
  863. ///
  864. Status ModelManager::GetUserDesignateShapeOrder(const uint32_t model_id,
  865. std::vector<std::string> &user_input_shape_order) {
  866. auto hybrid_davinci_model = GetHybridModel(model_id);
  867. if (hybrid_davinci_model != nullptr) {
  868. hybrid_davinci_model->GetUserDesignateShapeOrder(user_input_shape_order);
  869. return SUCCESS;
  870. }
  871. auto davinci_model = GetModel(model_id);
  872. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  873. "GetUserDesignateShapeOrder Failed, Invalid Model ID %u!", model_id)
  874. davinci_model->GetUserDesignateShapeOrder(user_input_shape_order);
  875. return SUCCESS;
  876. }
  877. Status ModelManager::GetCurShape(const uint32_t model_id, std::vector<int64_t> &batch_info, int32_t &dynamic_type) {
  878. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  879. GE_CHECK_NOTNULL(davinci_model);
  880. davinci_model->GetCurShape(batch_info, dynamic_type);
  881. return SUCCESS;
  882. }
  883. Status ModelManager::GetModelAttr(uint32_t model_id, std::vector<string> &dynamic_output_shape_info) {
  884. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  885. if (hybrid_davinci_model != nullptr) {
  886. hybrid_davinci_model->GetModelAttr(dynamic_output_shape_info);
  887. return SUCCESS;
  888. }
  889. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  890. GE_CHECK_NOTNULL(davinci_model);
  891. davinci_model->GetModelAttr(dynamic_output_shape_info);
  892. return SUCCESS;
  893. }
  894. Status ModelManager::GetInputOutputDescInfoForZeroCopy(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  895. vector<InputOutputDescInfo> &output_desc,
  896. std::vector<uint32_t> &inputFormats,
  897. std::vector<uint32_t> &outputFormats) {
  898. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  899. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid model id %u!",
  900. model_id);
  901. return davinci_model->GetInputOutputDescInfoForZeroCopy(input_desc, output_desc, inputFormats, outputFormats);
  902. }
  903. ///
  904. /// @ingroup ge
  905. /// @brief Get AIPP info
  906. /// @param [in] model_id
  907. /// @param [in] index
  908. /// @param [out] aipp_info
  909. /// @return execute result
  910. ///
  911. Status ModelManager::GetAIPPInfo(const uint32_t model_id, uint32_t index, AippConfigInfo &aipp_info) {
  912. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  913. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  914. "GetAIPPInfo failed, invalid model_id is %u.",
  915. model_id);
  916. return davinci_model->GetAIPPInfo(index, aipp_info);
  917. }
  918. Status ModelManager::GetAippType(uint32_t model_id, uint32_t index, InputAippType &type, size_t &aipp_index) {
  919. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  920. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  921. "GetAIPPInfo failed, invalid model_id is %u.",
  922. model_id);
  923. return davinci_model->GetAippType(index, type, aipp_index);
  924. }
  925. Status ModelManager::GenSessionId(uint64_t &session_id) {
  926. std::lock_guard<std::mutex> lock(session_id_create_mutex_);
  927. mmTimeval tv;
  928. if (mmGetTimeOfDay(&tv, nullptr) != 0) {
  929. GELOGE(INTERNAL_ERROR, "Failed to get current time.");
  930. return INTERNAL_ERROR;
  931. }
  932. session_id = static_cast<uint64_t>(tv.tv_sec * 1000000 + tv.tv_usec); // 1000000us
  933. session_id_bias_++;
  934. // max bais 100.
  935. session_id_bias_ = session_id_bias_ % 100;
  936. session_id = session_id * 100 + session_id_bias_;
  937. GELOGD("Generate new session id: %lu.", session_id);
  938. return SUCCESS;
  939. }
  940. Status ModelManager::LoadModelOffline(uint32_t &model_id, const ModelData &model, shared_ptr<ModelListener> listener,
  941. void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) {
  942. GE_CHK_BOOL_RET_STATUS(model.key.empty() || mmAccess2(model.key.c_str(), M_F_OK) == EN_OK,
  943. ACL_ERROR_GE_PARAM_INVALID,
  944. "input key file path %s is invalid, %s", model.key.c_str(), strerror(errno));
  945. GenModelId(&model_id);
  946. shared_ptr<DavinciModel> davinci_model = nullptr;
  947. mmTimespec timespec = mmGetTickCount();
  948. ModelHelper model_helper;
  949. Status ret = model_helper.LoadModel(model);
  950. if (ret != SUCCESS) {
  951. GELOGE(ret, "load model failed.");
  952. return ret;
  953. }
  954. do {
  955. GeModelPtr ge_model = model_helper.GetGeModel();
  956. try {
  957. davinci_model = std::make_shared<DavinciModel>(model.priority, listener);
  958. } catch (std::bad_alloc &) {
  959. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "Make shared failed");
  960. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  961. } catch (...) {
  962. GELOGE(INTERNAL_ERROR, "Make shared failed since other exception raise");
  963. return INTERNAL_ERROR;
  964. }
  965. ret = davinci_model->Assign(ge_model);
  966. if (ret != SUCCESS) {
  967. GELOGW("assign model failed.");
  968. break;
  969. }
  970. davinci_model->SetId(model_id);
  971. int32_t device_id = 0;
  972. rtError_t rt_ret = rtGetDevice(&device_id);
  973. if (rt_ret != RT_ERROR_NONE || device_id < 0) {
  974. GELOGE(RT_FAILED, "Call rtGetDevice failed, ret = 0x%X, device_id = %d.", rt_ret, device_id);
  975. return RT_ERROR_TO_GE_STATUS(rt_ret);
  976. }
  977. davinci_model->SetDeviceId(device_id);
  978. davinci_model->SetOmName(model.om_name);
  979. if (DumpManager::GetInstance().GetDumpProperties().IsDumpOpen()) {
  980. davinci_model->SetDumpProperties(DumpManager::GetInstance().GetDumpProperties());
  981. } else {
  982. davinci_model->SetDumpProperties(dump_properties_);
  983. }
  984. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  985. /// These session_ids come from the same model, so the values of session_id are the same.
  986. /// Update session_id for infer in load model to avoid the same session_id.
  987. uint64_t new_session_id;
  988. ret = GenSessionId(new_session_id);
  989. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Generate session_id for infer failed.");
  990. ret = davinci_model->UpdateSessionId(new_session_id);
  991. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Update session_id for infer failed.");
  992. ret = davinci_model->Init(dev_ptr, mem_size, weight_ptr, weight_size);
  993. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "DavinciInit failed.");
  994. InsertModel(model_id, davinci_model);
  995. GELOGI("Parse model %u success.", model_id);
  996. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * 1000 * 1000 * 1000 +
  997. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  998. davinci_model->SetProfileTime(MODEL_LOAD_END);
  999. GE_IF_BOOL_EXEC(ret == SUCCESS, device_count++);
  1000. return SUCCESS;
  1001. } while (0);
  1002. return ret;
  1003. }
  1004. ///
  1005. /// @ingroup ge
  1006. /// @brief ACL case, Load task list with queue.
  1007. /// @param [out] model_id: model id for manager.
  1008. /// @param [in] model_data: Model data load from offline model file.
  1009. /// @param [in] input_que_ids: input queue ids from user, num equals Data Op.
  1010. /// @param [in] output_que_ids: input queue ids from user, num equals NetOutput Op.
  1011. /// @return: 0 for success / others for fail
  1012. ///
  1013. Status ModelManager::LoadModelWithQ(uint32_t &model_id, const ModelData &model_data,
  1014. const std::vector<uint32_t> &input_queue_ids,
  1015. const std::vector<uint32_t> &output_queue_ids) {
  1016. GE_CHK_BOOL_RET_STATUS(model_data.key.empty() || mmAccess2(model_data.key.c_str(), M_F_OK) == EN_OK,
  1017. ACL_ERROR_GE_PARAM_INVALID, "input key file path %s is not valid, %s",
  1018. model_data.key.c_str(), strerror(errno));
  1019. ModelHelper model_helper;
  1020. Status ret = model_helper.LoadModel(model_data);
  1021. if (ret != SUCCESS) {
  1022. GELOGE(ret, "load model failed.");
  1023. return ret;
  1024. }
  1025. shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(model_data.priority, nullptr);
  1026. if (davinci_model == nullptr) {
  1027. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "create model failed.");
  1028. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  1029. }
  1030. ret = davinci_model->Assign(model_helper.GetGeModel());
  1031. if (ret != SUCCESS) {
  1032. GELOGE(ret, "assign model failed.");
  1033. return ret;
  1034. }
  1035. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  1036. /// These session_ids come from the same model, so the values of session_id are the same.
  1037. /// Update session_id for infer in load model to avoid the same session_id.
  1038. uint64_t new_session_id;
  1039. ret = GenSessionId(new_session_id);
  1040. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Generate session_id for infer failed.");
  1041. ret = davinci_model->UpdateSessionId(new_session_id);
  1042. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Update session_id for infer failed.");
  1043. GenModelId(&model_id);
  1044. davinci_model->SetId(model_id);
  1045. ret = davinci_model->SetQueIds(input_queue_ids, output_queue_ids);
  1046. if (ret != SUCCESS) {
  1047. GELOGE(ret, "set model queue ids failed.");
  1048. return ret;
  1049. }
  1050. davinci_model->SetDumpProperties(dump_properties_);
  1051. ret = davinci_model->Init();
  1052. if (ret != SUCCESS) {
  1053. GELOGE(ret, "init model failed.");
  1054. return ret;
  1055. }
  1056. InsertModel(model_id, davinci_model);
  1057. GELOGI("Parse model %u success.", model_id);
  1058. return SUCCESS;
  1059. }
  1060. ///
  1061. /// @ingroup domi_ome
  1062. /// @brief ACL case, not start new thread, return result
  1063. /// @param [in] model_id mode id
  1064. /// @param [in] stream model stream
  1065. /// @param [in] async_mode is asynchronize mode.
  1066. /// @param [in] input_data input data
  1067. /// @param [in] input_desc description of input data
  1068. /// @param [out] output_data output data
  1069. /// @param [out] output_desc description of output data
  1070. ///
  1071. Status ModelManager::ExecuteModel(uint32_t model_id, rtStream_t stream, bool async_mode, const InputData &input_data,
  1072. const std::vector<GeTensorDesc> &input_desc, OutputData &output_data,
  1073. std::vector<GeTensorDesc> &output_desc) {
  1074. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  1075. if (hybrid_davinci_model != nullptr) {
  1076. auto inputs = input_data.blobs;
  1077. auto outputs = output_data.blobs;
  1078. Status status = hybrid_davinci_model->Execute(inputs, input_desc, outputs, output_desc, stream);
  1079. if (status == SUCCESS) {
  1080. GELOGI("Execute model %u success.", model_id);
  1081. }
  1082. return status;
  1083. }
  1084. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1085. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid model id %u.", model_id);
  1086. if (davinci_model->NeedDestroyAicpuKernel()) {
  1087. GELOGI("Start to destroy specified aicpu kernel.");
  1088. // Zero copy is enabled by default, no need to judge.
  1089. uint64_t session_id_davinci = davinci_model->GetSessionId();
  1090. uint32_t model_id_davinci = davinci_model->GetModelId();
  1091. Status status = DestroyAicpuKernel(session_id_davinci, model_id_davinci);
  1092. if (status != SUCCESS) {
  1093. GELOGW("Destroy specified aicpu kernel failed, session id is %lu, model id is %u.", session_id_davinci,
  1094. model_id_davinci);
  1095. }
  1096. }
  1097. Status status = davinci_model->NnExecute(stream, async_mode, input_data, output_data);
  1098. if (status == SUCCESS) {
  1099. GELOGD("Execute model %u success.", model_id);
  1100. }
  1101. return status;
  1102. }
  1103. Status ModelManager::CreateAicpuSession(uint64_t session_id) {
  1104. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  1105. auto it = sess_ids_.find(session_id);
  1106. // never been created by any model
  1107. if (it == sess_ids_.end()) {
  1108. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_CREATE, session_id, 0);
  1109. if (ret == SUCCESS) {
  1110. (void)sess_ids_.insert(session_id);
  1111. GELOGI("The session: %lu create success.", session_id);
  1112. }
  1113. return ret;
  1114. }
  1115. return SUCCESS;
  1116. }
  1117. Status ModelManager::LoadCustAicpuSo(const OpDescPtr &op_desc, const string &so_name) {
  1118. GELOGI("LoadCustAicpuSo in, op name %s, so name %s", op_desc->GetName().c_str(), so_name.c_str());
  1119. std::lock_guard<std::mutex> lock(cust_aicpu_mutex_);
  1120. CustAICPUKernelPtr aicpu_kernel = op_desc->TryGetExtAttr(OP_EXTATTR_CUSTAICPU_KERNEL, CustAICPUKernelPtr());
  1121. if (aicpu_kernel == nullptr) {
  1122. GELOGE(INTERNAL_ERROR, "cust aicpu op %s can't find kernel!", op_desc->GetName().c_str());
  1123. return INTERNAL_ERROR;
  1124. }
  1125. // get current context
  1126. rtContext_t rt_cur_ctx = nullptr;
  1127. auto rt_error = rtCtxGetCurrent(&rt_cur_ctx);
  1128. if (rt_error != RT_ERROR_NONE) {
  1129. GELOGE(RT_FAILED, "get current context failed, runtime result is %d", static_cast<int>(rt_error));
  1130. return RT_FAILED;
  1131. }
  1132. // use current context as resource key
  1133. uintptr_t resource_id = reinterpret_cast<uintptr_t>(rt_cur_ctx);
  1134. auto it = cust_aicpu_so_.find(resource_id);
  1135. if (it == cust_aicpu_so_.end()) {
  1136. std::map<string, CustAICPUKernelPtr> new_so_name;
  1137. new_so_name.insert({so_name, aicpu_kernel});
  1138. cust_aicpu_so_[resource_id] = new_so_name;
  1139. GELOGI("LoadCustAicpuSo new aicpu so resource id %lu", resource_id);
  1140. return SUCCESS;
  1141. }
  1142. auto it_so_name = it->second.find(so_name);
  1143. if (it_so_name == it->second.end()) {
  1144. it->second.insert({so_name, aicpu_kernel});
  1145. GELOGI("LoadCustAicpuSo add aicpu so resource id %lu", resource_id);
  1146. }
  1147. return SUCCESS;
  1148. }
  1149. Status ModelManager::LaunchKernelCustAicpuSo(const string &kernel_name) {
  1150. std::lock_guard<std::mutex> lock(cust_aicpu_mutex_);
  1151. if (cust_aicpu_so_.size() == 0) return SUCCESS;
  1152. // get current context
  1153. rtContext_t rt_cur_ctx = nullptr;
  1154. auto rt_error = rtCtxGetCurrent(&rt_cur_ctx);
  1155. if (rt_error != RT_ERROR_NONE) {
  1156. GELOGE(RT_FAILED, "get current context failed, runtime result is %d", static_cast<int>(rt_error));
  1157. return RT_FAILED;
  1158. }
  1159. uintptr_t resource_id = reinterpret_cast<uintptr_t>(rt_cur_ctx);
  1160. auto it = cust_aicpu_so_.find(resource_id);
  1161. if (it == cust_aicpu_so_.end()) {
  1162. GELOGI("Cust aicpu so map is empty, context id %lu", resource_id);
  1163. return SUCCESS;
  1164. }
  1165. vector<void *> allocated_mem;
  1166. rtError_t status;
  1167. rtStream_t stream = nullptr;
  1168. vector<CustAicpuSoBuf> v_cust_so;
  1169. void *args = nullptr;
  1170. for (const auto &it_so : it->second) {
  1171. const void *aicpu_data = it_so.second->GetBinData();
  1172. uint32_t aicpu_data_length = it_so.second->GetBinDataSize();
  1173. string so_name = it_so.first;
  1174. void *d_aicpu_data = nullptr;
  1175. void *d_so_name = nullptr;
  1176. status = rtMalloc(&d_aicpu_data, aicpu_data_length, RT_MEMORY_HBM);
  1177. if (status != RT_ERROR_NONE) {
  1178. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1179. return RT_ERROR_TO_GE_STATUS(status);
  1180. }
  1181. allocated_mem.push_back(d_aicpu_data);
  1182. status = rtMalloc(&d_so_name, so_name.size(), RT_MEMORY_HBM);
  1183. if (status != RT_ERROR_NONE) {
  1184. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1185. return RT_ERROR_TO_GE_STATUS(status);
  1186. }
  1187. allocated_mem.push_back(d_so_name);
  1188. GE_CHK_RT(rtMemcpy(d_aicpu_data, aicpu_data_length, aicpu_data, aicpu_data_length, RT_MEMCPY_HOST_TO_DEVICE));
  1189. GE_CHK_RT(rtMemcpy(d_so_name, so_name.size(), reinterpret_cast<const void *>(so_name.c_str()),
  1190. so_name.size(), RT_MEMCPY_HOST_TO_DEVICE));
  1191. CustAicpuSoBuf cust_aicpu_so_buf;
  1192. cust_aicpu_so_buf.kernelSoBuf = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_aicpu_data));
  1193. cust_aicpu_so_buf.kernelSoBufLen = aicpu_data_length;
  1194. cust_aicpu_so_buf.kernelSoName = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_so_name));
  1195. cust_aicpu_so_buf.kernelSoNameLen = so_name.size();
  1196. v_cust_so.push_back(cust_aicpu_so_buf);
  1197. }
  1198. if (kernel_name == kDeleteCustOp) {
  1199. (void)cust_aicpu_so_.erase(it);
  1200. }
  1201. uint32_t args_size = sizeof(CustAicpuSoBuf) * v_cust_so.size();
  1202. status = rtMalloc(&args, args_size, RT_MEMORY_HBM);
  1203. if (status != RT_ERROR_NONE) {
  1204. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1205. return RT_ERROR_TO_GE_STATUS(status);
  1206. }
  1207. allocated_mem.push_back(args);
  1208. GE_CHK_RT(rtMemcpy(args, args_size, v_cust_so.data(), args_size, RT_MEMCPY_HOST_TO_DEVICE));
  1209. BatchLoadOpFromBufArgs batch_cust_so;
  1210. batch_cust_so.soNum = v_cust_so.size();
  1211. batch_cust_so.args = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(args));
  1212. void *batch_args = nullptr;
  1213. uint32_t batch_args_size = sizeof(BatchLoadOpFromBufArgs);
  1214. status = rtMalloc(&batch_args, batch_args_size, RT_MEMORY_HBM);
  1215. if (status != RT_ERROR_NONE) {
  1216. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1217. return RT_ERROR_TO_GE_STATUS(status);
  1218. }
  1219. allocated_mem.push_back(batch_args);
  1220. GE_CHK_RT(rtMemcpy(batch_args, batch_args_size, static_cast<void *>(&batch_cust_so),
  1221. batch_args_size, RT_MEMCPY_HOST_TO_DEVICE));
  1222. GE_CHK_RT(rtStreamCreate(&stream, 0));
  1223. GE_CHK_RT(rtCpuKernelLaunch(nullptr, kernel_name.c_str(), 1, batch_args, batch_args_size, nullptr, stream));
  1224. status = rtStreamSynchronize(stream);
  1225. if (status != RT_ERROR_NONE) {
  1226. GELOGE(RT_FAILED, "Call rt stream sync failed, status: 0x%x", status);
  1227. return RT_ERROR_TO_GE_STATUS(status);
  1228. }
  1229. std::function<void()> callback = [&]() {
  1230. for (auto mem : allocated_mem) {
  1231. GE_CHK_RT(rtFree(mem));
  1232. }
  1233. GE_CHK_RT(rtStreamDestroy(stream));
  1234. };
  1235. GE_MAKE_GUARD(release, callback);
  1236. GELOGI("Cpu kernel launch task success.");
  1237. return SUCCESS;
  1238. }
  1239. Status ModelManager::ClearAicpuSo() {
  1240. GE_CHK_STATUS_RET(LaunchKernelCustAicpuSo(kDeleteCustOp), "delete cust op so failed.");
  1241. return SUCCESS;
  1242. }
  1243. Status ModelManager::LaunchCustAicpuSo() {
  1244. GE_CHK_STATUS_RET(LaunchKernelCustAicpuSo(kBatchLoadBuf), "launch cust op so failed.");
  1245. return SUCCESS;
  1246. }
  1247. ///
  1248. /// @ingroup ge
  1249. /// @brief get model memory size and weight
  1250. /// @param [in] const ModelData model: model type
  1251. /// @param [out] size_t memSize: model memory usage
  1252. /// size_t weightSize: model weight and memory size
  1253. /// @return SUCCESS success / others failure
  1254. ///
  1255. Status ModelManager::GetModelMemAndWeightSize(const ModelData &model, size_t &mem_size, size_t &weight_size) {
  1256. uint8_t *model_data = nullptr;
  1257. uint32_t model_len = 0;
  1258. Status ret = DavinciModelParser::ParseModelContent(model, model_data, model_len);
  1259. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "parse model content failed!");
  1260. OmFileLoadHelper om_file_helper;
  1261. ret = om_file_helper.Init(model_data, model_len);
  1262. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "om file helperInit failed!");
  1263. auto partition_table = reinterpret_cast<ModelPartitionTable *>(model_data);
  1264. if (partition_table->num == 1) {
  1265. GELOGE(ACL_ERROR_GE_PARAM_INVALID, "om model is error,please use executable om model");
  1266. return ACL_ERROR_GE_PARAM_INVALID;
  1267. }
  1268. ModelPartition task_partition;
  1269. if (om_file_helper.GetModelPartition(ModelPartitionType::TASK_INFO, task_partition) != SUCCESS) {
  1270. GELOGE(ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED, "get task model partition failed.");
  1271. return ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED;
  1272. }
  1273. std::shared_ptr<domi::ModelTaskDef> model_task_def = MakeShared<domi::ModelTaskDef>();
  1274. if (model_task_def == nullptr) {
  1275. return MEMALLOC_FAILED;
  1276. }
  1277. if (task_partition.size != 0) {
  1278. if (!ReadProtoFromArray(task_partition.data, static_cast<int>(task_partition.size), model_task_def.get())) {
  1279. GELOGE(ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED, "ReadProtoFromArray failed.");
  1280. return ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED;
  1281. }
  1282. }
  1283. ModelPartition partition_weight;
  1284. ret = om_file_helper.GetModelPartition(ModelPartitionType::WEIGHTS_DATA, partition_weight);
  1285. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ACL_ERROR_GE_EXEC_LOAD_WEIGHT_PARTITION_FAILED,
  1286. "Get weight partition failed. ret = %u", ret);
  1287. mem_size = model_task_def->memory_size();
  1288. weight_size = partition_weight.size;
  1289. return SUCCESS;
  1290. }
  1291. void ModelManager::GenModelId(uint32_t *id) {
  1292. if (id == nullptr) {
  1293. return;
  1294. }
  1295. std::lock_guard<std::mutex> lock(map_mutex_);
  1296. *id = ++max_model_id_;
  1297. }
  1298. Status ModelManager::GetOrigInputInfo(uint32_t model_id, uint32_t index, OriginInputInfo &orig_input_info) {
  1299. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1300. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1301. "GetOrigInputInfo failed, invalid model_id is %u.",
  1302. model_id);
  1303. return davinci_model->GetOrigInputInfo(index, orig_input_info);
  1304. }
  1305. Status ModelManager::GetAllAippInputOutputDims(uint32_t model_id, uint32_t index,
  1306. std::vector<InputOutputDims> &input_dims,
  1307. std::vector<InputOutputDims> &output_dims) {
  1308. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1309. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1310. "GetAllAippInputOutputDims failed, invalid model_id is %u.", model_id);
  1311. return davinci_model->GetAllAippInputOutputDims(index, input_dims, output_dims);
  1312. }
  1313. bool ModelManager::IsDynamicShape(uint32_t model_id) {
  1314. auto model = GetHybridModel(model_id);
  1315. return model != nullptr;
  1316. }
  1317. ge::Status ModelManager::SyncExecuteModel(uint32_t model_id, const vector<GeTensor> &inputs,
  1318. vector<GeTensor> &outputs) {
  1319. auto model = GetHybridModel(model_id);
  1320. if (model == nullptr) {
  1321. GELOGE(FAILED, "Hybrid model not found. model id = %u.", model_id);
  1322. return FAILED;
  1323. }
  1324. return model->Execute(inputs, outputs);
  1325. }
  1326. Status ModelManager::GetOpDescInfo(uint32_t device_id, uint32_t stream_id, uint32_t task_id, OpDescInfo &op_desc_info) {
  1327. for (const auto &model : model_map_) {
  1328. auto davinci_model = model.second;
  1329. if (davinci_model->GetDeviceId() == device_id) {
  1330. GELOGI("Start to GetOpDescInfo of device_id: %u.", device_id);
  1331. if (davinci_model->GetOpDescInfo(stream_id, task_id, op_desc_info)) {
  1332. GELOGI("Find specific node of stream_id: %u, task_id: %u.", stream_id, task_id);
  1333. return SUCCESS;
  1334. }
  1335. }
  1336. }
  1337. return FAILED;
  1338. }
  1339. Status ModelManager::EnableExceptionDump(const std::map<string, string> &options) {
  1340. auto iter = options.find(OPTION_EXEC_ENABLE_EXCEPTION_DUMP);
  1341. if (iter != options.end()) {
  1342. GELOGI("Find option enable_exeception_dump is %s", iter->second.c_str());
  1343. if (iter->second == "1") {
  1344. rtError_t rt_ret = rtSetTaskFailCallback(reinterpret_cast<rtTaskFailCallback>(ExceptionCallback));
  1345. if (rt_ret != RT_ERROR_NONE) {
  1346. GELOGE(RT_FAILED, "rtSetTaskFailCallback failed");
  1347. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1348. }
  1349. } else {
  1350. GELOGI("Option enable exception dump is %s", iter->second.c_str());
  1351. }
  1352. } else {
  1353. GELOGI("Not find option enable exception dump");
  1354. }
  1355. return SUCCESS;
  1356. }
  1357. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示