You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

model_manager.cc 79 kB

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

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