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

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

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