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

model_manager.cc 79 kB

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

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