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 69 kB

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

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