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

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