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

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