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

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