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

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

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