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

model_manager.cc 79 kB

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

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