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

model_manager.cc 60 kB

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

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