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

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