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

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

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