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

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