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

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

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