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

model_manager.cc 84 kB

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

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