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

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

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