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

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

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