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

model_manager.cc 58 kB

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

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