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

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