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

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

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