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

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