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

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