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

model_manager.cc 59 kB

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

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