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

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
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
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
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
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
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
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
5 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
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
4 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
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
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
4 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
5 years ago
4 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
4 years ago
5 years ago
4 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
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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/model_manager/model_manager.h"
  17. #include <string>
  18. #include "aicpu/aicpu_schedule/aicpu_op_type_list.h"
  19. #include "common/model_parser/model_parser.h"
  20. #include "common/dump/dump_manager.h"
  21. #include "common/l2_cache_optimize.h"
  22. #include "common/profiling/profiling_manager.h"
  23. #include "graph/common/ge_call_wrapper.h"
  24. #include "graph/load/model_manager/davinci_model.h"
  25. #include "model/ge_root_model.h"
  26. #include "common/formats/utils/formats_trans_utils.h"
  27. #include "toolchain/adx_datadump_server.h"
  28. namespace ge {
  29. thread_local uint32_t device_count = 0;
  30. namespace {
  31. const int kCmdParSize = 2;
  32. const int kDumpCmdPairSize = 2;
  33. const std::size_t kProfCmdParaMaxSize = 1000;
  34. const std::size_t kProfStartCmdParaSize = 2;
  35. const std::string kCmdTypeDump = "dump";
  36. const std::string kCmdTypeProfInit = "prof_init";
  37. const std::string kCmdTypeProfFinalize = "prof_finalize";
  38. const std::string kCmdTypeProfStart = "prof_start";
  39. const std::string kCmdTypeProfStop = "prof_stop";
  40. const std::string kCmdTypeProfModelSubscribe = "prof_model_subscribe";
  41. const std::string kCmdTypeProfModelUnsubscribe = "prof_model_cancel_subscribe";
  42. const char *const kBatchLoadBuf = "batchLoadsoFrombuf";
  43. const char *const kDeleteCustOp = "deleteCustOp";
  44. const int kTimeSpecNano = 1000000000;
  45. const int kTimeSpecMiro = 1000000;
  46. const int kOpNameMaxSize = 100;
  47. const uint64_t kInferSessionId = 0;
  48. const int32_t kDumpStatus = 0;
  49. #pragma pack(push, 1)
  50. struct CustAicpuSoBuf {
  51. uint64_t kernelSoBuf;
  52. uint32_t kernelSoBufLen;
  53. uint64_t kernelSoName;
  54. uint32_t kernelSoNameLen;
  55. };
  56. struct BatchLoadOpFromBufArgs {
  57. uint32_t soNum;
  58. uint64_t args;
  59. };
  60. #pragma pack(pop)
  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. uint32_t sub_model_id) {
  75. STR_FWK_OP_KERNEL param_base = {};
  76. void *devicebase = nullptr;
  77. void *aicpu_kernel_addr = nullptr;
  78. const uint32_t kKernelType = 0;
  79. param_base.fwkKernelType = kKernelType;
  80. param_base.fwkKernelBase.fwk_kernel.opType = op_type;
  81. param_base.fwkKernelBase.fwk_kernel.sessionID = session_id;
  82. if (op_type == aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY) {
  83. std::vector<uint64_t> v_aicpu_kernel;
  84. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id) + "_" +
  85. std::to_string(sub_model_id);
  86. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  87. auto iter = model_aicpu_kernel_.find(model_key);
  88. if (iter != model_aicpu_kernel_.end()) {
  89. GELOGD("kernel destroy session_id %lu, model_id %u, sub_model_id %u..", session_id, model_id, sub_model_id);
  90. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  91. // Insert size of aicpu kernel vector in the first element
  92. v_aicpu_kernel.insert(v_aicpu_kernel.begin(), v_aicpu_kernel.size());
  93. auto kernel_size = sizeof(uint64_t) * (v_aicpu_kernel.size());
  94. rtError_t rt_ret = rtMalloc(&aicpu_kernel_addr, kernel_size, RT_MEMORY_HBM);
  95. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE,
  96. REPORT_CALL_ERROR("E19999", "Call rtMalloc failed, size:%zu, ret: 0x%X",
  97. kernel_size, rt_ret);
  98. GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret);
  99. return RT_ERROR_TO_GE_STATUS(rt_ret);)
  100. rt_ret = rtMemcpy(aicpu_kernel_addr, kernel_size, v_aicpu_kernel.data(), kernel_size, RT_MEMCPY_HOST_TO_DEVICE);
  101. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE,
  102. REPORT_CALL_ERROR("E19999", "Call rtMemcpy failed, size:%zu, ret: 0x%X",
  103. kernel_size, rt_ret);
  104. GELOGE(RT_FAILED, "rtMemcpy to input_output_addr_ error: 0x%X", rt_ret);
  105. GE_CHK_RT(rtFree(aicpu_kernel_addr)); return RT_ERROR_TO_GE_STATUS(rt_ret);)
  106. uint64_t kernel_id_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(aicpu_kernel_addr));
  107. param_base.fwkKernelBase.fwk_kernel.kernelID = kernel_id_addr;
  108. // In the scene of loading once and running many times, the kernel needs to be destroyed many times,
  109. // and connot be removed from kernel map.
  110. }
  111. }
  112. rtError_t rt_ret = rtMalloc(&(devicebase), sizeof(STR_FWK_OP_KERNEL), RT_MEMORY_HBM);
  113. if (rt_ret != RT_ERROR_NONE) {
  114. REPORT_CALL_ERROR("E19999", "Call rtMalloc failed, size:%zu, ret: 0x%X",
  115. sizeof(STR_FWK_OP_KERNEL), rt_ret);
  116. GELOGE(RT_FAILED, "malloc device memory failed. ret: 0x%X", rt_ret);
  117. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  118. return RT_ERROR_TO_GE_STATUS(rt_ret);
  119. }
  120. rt_ret =
  121. rtMemcpy(devicebase, sizeof(STR_FWK_OP_KERNEL), &param_base, sizeof(STR_FWK_OP_KERNEL), RT_MEMCPY_HOST_TO_DEVICE);
  122. if (rt_ret != RT_ERROR_NONE) {
  123. REPORT_CALL_ERROR("E19999", "Call rtMemcpy failed, size:%zu, ret: 0x%X",
  124. sizeof(STR_FWK_OP_KERNEL), rt_ret);
  125. GELOGE(RT_FAILED, "memory copy to device failed. ret: 0x%X", rt_ret);
  126. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  127. GE_CHK_RT(rtFree(devicebase));
  128. return RT_ERROR_TO_GE_STATUS(rt_ret);
  129. }
  130. rtStream_t stream = nullptr;
  131. rt_ret = rtStreamCreate(&stream, 0);
  132. if (rt_ret != RT_ERROR_NONE) {
  133. REPORT_CALL_ERROR("E19999", "Call rtStreamCreate failed, ret: 0x%X", rt_ret);
  134. GELOGE(RT_FAILED, "create stream failed. ret: 0x%X", rt_ret);
  135. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  136. GE_CHK_RT(rtFree(devicebase));
  137. return RT_ERROR_TO_GE_STATUS(rt_ret);
  138. }
  139. rt_ret = rtKernelLaunchEx(devicebase, sizeof(STR_FWK_OP_KERNEL), 0, stream);
  140. if (rt_ret != RT_ERROR_NONE) {
  141. REPORT_CALL_ERROR("E19999", "Call rtKernelLaunchEx failed, ret: 0x%X", rt_ret);
  142. GELOGE(RT_FAILED, "rtKernelLaunchEx failed. ret: 0x%X", rt_ret);
  143. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  144. GE_CHK_RT(rtFree(devicebase));
  145. GE_CHK_RT(rtStreamDestroy(stream));
  146. return RT_ERROR_TO_GE_STATUS(rt_ret);
  147. }
  148. rt_ret = rtStreamSynchronize(stream);
  149. if (rt_ret != RT_ERROR_NONE) {
  150. REPORT_CALL_ERROR("E19999", "Call rtStreamSynchronize failed, ret: 0x%X",
  151. rt_ret);
  152. GELOGE(RT_FAILED, "rtStreamSynchronize failed. ret: 0x%X", rt_ret);
  153. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  154. GE_CHK_RT(rtFree(devicebase));
  155. GE_CHK_RT(rtStreamDestroy(stream));
  156. return RT_ERROR_TO_GE_STATUS(rt_ret);
  157. }
  158. if (aicpu_kernel_addr != nullptr) {
  159. rt_ret = rtFree(aicpu_kernel_addr);
  160. if (rt_ret != RT_ERROR_NONE) {
  161. REPORT_CALL_ERROR("E19999", "Call rtFree failed, ret: 0x%X", rt_ret);
  162. GELOGE(RT_FAILED, "free memory failed. ret: 0x%X", rt_ret);
  163. GE_CHK_RT(rtFree(devicebase));
  164. GE_CHK_RT(rtStreamDestroy(stream));
  165. return RT_ERROR_TO_GE_STATUS(rt_ret);
  166. }
  167. }
  168. rt_ret = rtFree(devicebase);
  169. if (rt_ret != RT_ERROR_NONE) {
  170. REPORT_CALL_ERROR("E19999", "Call rtFree failed, ret: 0x%X", rt_ret);
  171. GELOGE(RT_FAILED, "free memory failed. ret: 0x%X", rt_ret);
  172. GE_CHK_RT(rtStreamDestroy(stream));
  173. return RT_ERROR_TO_GE_STATUS(rt_ret);
  174. }
  175. rt_ret = rtStreamDestroy(stream);
  176. if (rt_ret != RT_ERROR_NONE) {
  177. REPORT_CALL_ERROR("E19999", "Call rtStreamDestroy failed, ret: 0x%X", rt_ret);
  178. GELOGE(RT_FAILED, "rtStreamDestroy failed. ret: 0x%X", rt_ret);
  179. return RT_ERROR_TO_GE_STATUS(rt_ret);
  180. }
  181. return SUCCESS;
  182. }
  183. void ModelManager::DestroyAicpuSession(uint64_t session_id) {
  184. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  185. auto it = sess_ids_.find(session_id);
  186. if (it == sess_ids_.end()) {
  187. GELOGI("The session: %lu not created.", session_id);
  188. return;
  189. } else {
  190. rtContext_t ctx = nullptr;
  191. bool has_ctx = (rtCtxGetCurrent(&ctx) == RT_ERROR_NONE);
  192. if (!has_ctx) {
  193. GELOGI("Set device %u.", GetContext().DeviceId());
  194. GE_CHK_RT(rtSetDevice(static_cast<int32_t>(GetContext().DeviceId())));
  195. }
  196. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_DESTROY, session_id, 0, 0);
  197. if (ret != SUCCESS) {
  198. GELOGW("The session: %lu destroy failed.", session_id);
  199. } else {
  200. (void)sess_ids_.erase(session_id);
  201. GELOGI("The session: %lu destroyed.", session_id);
  202. }
  203. if (!has_ctx) {
  204. GELOGI("Reset device %u.", GetContext().DeviceId());
  205. GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId())));
  206. }
  207. }
  208. }
  209. ge::Status ModelManager::DestroyAicpuSessionForInfer(uint32_t model_id) {
  210. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  211. auto hybrid_davinci_model = hybrid_model_map_.find(model_id);
  212. if (hybrid_davinci_model != hybrid_model_map_.end()) {
  213. uint64_t session_id = hybrid_davinci_model->second->GetSessionId();
  214. DestroyAicpuSession(session_id);
  215. return SUCCESS;
  216. }
  217. auto it = model_map_.find(model_id);
  218. if (it == model_map_.end()) {
  219. REPORT_INNER_ERROR("E19999", "Param model_id:%u can't find in model_map, check invalid",
  220. model_id);
  221. GELOGE(ACL_ERROR_GE_EXEC_MODEL_ID_INVALID, "model id %u does not exists.", model_id);
  222. return ACL_ERROR_GE_EXEC_MODEL_ID_INVALID;
  223. }
  224. uint64_t session_id = it->second->GetSessionId();
  225. DestroyAicpuSession(session_id);
  226. return SUCCESS;
  227. }
  228. ge::Status ModelManager::DestroyAicpuKernel(uint64_t session_id, uint32_t model_id, uint32_t sub_model_id) {
  229. GELOGD("destroy aicpu kernel in session_id %lu, model_id %u.", session_id, model_id);
  230. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  231. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id) + "_" +
  232. std::to_string(sub_model_id);
  233. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  234. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY, session_id, model_id,
  235. sub_model_id);
  236. if (ret != SUCCESS) {
  237. REPORT_CALL_ERROR("E19999", "Call KernelLaunchEx fail, model_id:%u, sub_model_id:%u, session_id:%lu",
  238. model_id, sub_model_id, session_id);
  239. GELOGE(FAILED, "Destroy aicpu kernel failed.");
  240. return FAILED;
  241. }
  242. }
  243. return SUCCESS;
  244. }
  245. ge::Status ModelManager::CreateAicpuKernel(uint64_t session_id, uint32_t model_id, uint32_t sub_model_id,
  246. uint64_t kernel_id) {
  247. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  248. std::vector<uint64_t> v_aicpu_kernel;
  249. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id) + "_" +
  250. std::to_string(sub_model_id);
  251. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  252. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  253. }
  254. v_aicpu_kernel.push_back(kernel_id);
  255. model_aicpu_kernel_[model_key] = v_aicpu_kernel;
  256. return SUCCESS;
  257. }
  258. ModelManager::~ModelManager() {
  259. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  260. model_map_.clear();
  261. model_aicpu_kernel_.clear();
  262. cust_aicpu_so_.clear();
  263. dump_exception_flag_ = false;
  264. GE_IF_BOOL_EXEC(device_count > 0, GE_CHK_RT(rtDeviceReset(0)));
  265. }
  266. ge::Status ModelManager::SetDynamicSize(uint32_t model_id, const std::vector<uint64_t> &batch_num,
  267. int32_t dynamic_type) {
  268. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  269. GE_CHECK_NOTNULL(davinci_model);
  270. davinci_model->SetDynamicSize(batch_num, dynamic_type);
  271. return SUCCESS;
  272. }
  273. ge::Status ModelManager::DoLoadHybridModelOnline(uint32_t model_id, const string &om_name,
  274. const shared_ptr<ge::GeRootModel> &ge_root_model,
  275. const shared_ptr<ModelListener> &listener) {
  276. auto hybrid_model = hybrid::HybridDavinciModel::Create(ge_root_model);
  277. GE_CHECK_NOTNULL(hybrid_model);
  278. hybrid_model->SetListener(listener);
  279. hybrid_model->SetModelId(model_id);
  280. hybrid_model->SetDeviceId(GetContext().DeviceId());
  281. hybrid_model->SetOmName(om_name);
  282. GE_CHK_STATUS_RET(hybrid_model->Init(), "Failed to init hybrid model. model_id = %u", model_id);
  283. auto shared_model = std::shared_ptr<hybrid::HybridDavinciModel>(hybrid_model.release());
  284. InsertModel(model_id, shared_model);
  285. return SUCCESS;
  286. }
  287. bool ModelManager::IsNeedHybridLoad(ge::GeRootModel &ge_root_model) {
  288. auto root_graph = ge_root_model.GetRootGraph();
  289. if (root_graph == nullptr) {
  290. REPORT_INNER_ERROR("E19999", "root graph in param ge_root_model is nullptr, model_id:%u, "
  291. "check invalid", ge_root_model.GetModelId());
  292. GELOGE(FAILED, "no model on root model");
  293. return false;
  294. }
  295. bool is_shape_unknown = root_graph->GetGraphUnknownFlag();
  296. bool is_dsp_partitioned_graph = false;
  297. (void)AttrUtils::GetBool(root_graph, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, is_dsp_partitioned_graph);
  298. return is_shape_unknown || is_dsp_partitioned_graph || GetContext().GetHostExecFlag();
  299. }
  300. bool ModelManager::IsDumpSeverInited(uint64_t session_id) {
  301. auto it = session_id_to_dump_server_init_flag_.find(session_id);
  302. return it != session_id_to_dump_server_init_flag_.end() && it->second;
  303. }
  304. Status ModelManager::AddDumpProperties(uint64_t session_id, const DumpProperties &dump_properties) {
  305. if (!IsDumpSeverInited(session_id)) {
  306. if (dump_properties.IsDumpOpen() || dump_properties.IsOpDebugOpen()) {
  307. GE_IF_BOOL_EXEC(AdxDataDumpServerInit() != kDumpStatus,
  308. GELOGE(PARAM_INVALID, "[Init][AdxDataDumpServer] failed, session_id:%lu.", session_id);
  309. return PARAM_INVALID)
  310. GELOGI("Init adx data dump server success");
  311. session_id_to_dump_server_init_flag_[session_id] = true;
  312. }
  313. }
  314. DumpManager::GetInstance().AddDumpProperties(session_id, dump_properties);
  315. return SUCCESS;
  316. }
  317. Status ModelManager::InitDumPropertiesWithNewSessionId(uint64_t session_id) {
  318. DumpProperties dump_properties;
  319. dump_properties.InitByOptions();
  320. GE_CHK_STATUS_RET(AddDumpProperties(session_id, dump_properties), "[Add][DumpProperties] failed.");
  321. return SUCCESS;
  322. }
  323. Status ModelManager::UpdateSessionId(uint32_t model_id, GeModelPtr ge_model,
  324. std::shared_ptr<DavinciModel> &davinci_model, uint64_t &session_id) {
  325. uint64_t new_session_id;
  326. Status ret = GenSessionId(new_session_id);
  327. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Generate session_id for infer failed.");
  328. ret = davinci_model->UpdateSessionId(new_session_id);
  329. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Update session_id for infer failed.");
  330. ge_model->InsertSessionMap(model_id, new_session_id);
  331. GELOGD("Update new session id: %lu.", new_session_id);
  332. session_id = new_session_id;
  333. return SUCCESS;
  334. }
  335. bool ModelManager::HasVarNode(ComputeGraphPtr &compute_graph) const {
  336. for (ge::NodePtr &node : compute_graph->GetAllNodes()) {
  337. if (node == nullptr) {
  338. continue;
  339. }
  340. if (node->GetType() == VARIABLE) {
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. ///
  347. /// @ingroup domi_ome
  348. /// @brief load model online
  349. /// @return Status run result
  350. ///
  351. Status ModelManager::LoadModelOnline(uint32_t &model_id, const shared_ptr<ge::GeRootModel> &ge_root_model,
  352. std::shared_ptr<ModelListener> listener) {
  353. GE_CHK_BOOL_RET_STATUS(listener.get() != nullptr, PARAM_INVALID, "Param incorrect, listener is null");
  354. if (model_id == INVALID_MODEL_ID) {
  355. GenModelId(&model_id);
  356. GELOGD("Generate new model_id:%u", model_id);
  357. }
  358. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  359. string om_name;
  360. if (IsNeedHybridLoad(*ge_root_model)) {
  361. return DoLoadHybridModelOnline(model_id, om_name, ge_root_model, listener);
  362. }
  363. mmTimespec timespec = mmGetTickCount();
  364. std::shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(0, listener);
  365. GE_CHECK_NOTNULL(davinci_model);
  366. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * kTimeSpecNano +
  367. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  368. davinci_model->SetId(model_id);
  369. davinci_model->SetDeviceId(GetContext().DeviceId());
  370. auto root_graph = ge_root_model->GetRootGraph();
  371. GE_CHECK_NOTNULL(root_graph);
  372. string root_model_name = root_graph->GetName();
  373. GeModelPtr ge_model = name_to_model[root_model_name];
  374. Status ret = SUCCESS;
  375. do {
  376. GE_TIMESTAMP_START(Assign);
  377. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Assign(ge_model)), GELOGW("assign model to modeldef failed.");
  378. break;);
  379. GE_TIMESTAMP_END(Assign, "GraphLoader::ModelAssign");
  380. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  381. /// These session_ids come from the same model, so the values of session_id are the same.
  382. /// Update session_id for infer in load model to avoid the same session_id.
  383. uint64_t session_id = GetContext().SessionId();
  384. // Inference graph with variable node is not support for multi-threads scenario
  385. if (!ge_root_model->GetTrainFlag() && !HasVarNode(root_graph)) {
  386. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(UpdateSessionId(model_id, ge_model, davinci_model, session_id) != SUCCESS,
  387. return ret,
  388. "UpdateSessionId failed.");
  389. GE_CHK_RT_RET(rtSetDevice(GetContext().DeviceId()));
  390. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(InitDumPropertiesWithNewSessionId(session_id) != SUCCESS,
  391. GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId())));
  392. return ret,
  393. "Init DumProperties with new session_id failed.");
  394. }
  395. const DumpProperties &dump_properties = DumpManager::GetInstance().GetDumpProperties(session_id);
  396. davinci_model->SetDumpProperties(dump_properties);
  397. dump_properties_ = dump_properties;
  398. GE_TIMESTAMP_START(Init);
  399. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Init()), GELOGW("DavinciInit failed."); break;);
  400. GE_TIMESTAMP_END(Init, "GraphLoader::ModelInit");
  401. InsertModel(model_id, davinci_model);
  402. GELOGI("Parse model %u success.", model_id);
  403. } while (0);
  404. return ret;
  405. }
  406. void ModelManager::InsertModel(uint32_t model_id, std::shared_ptr<DavinciModel> &davinci_model) {
  407. GE_CHK_BOOL_EXEC(davinci_model != nullptr, return, "davinci_model ptr is null, id: %u", model_id);
  408. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  409. model_map_[model_id] = davinci_model;
  410. }
  411. void ModelManager::InsertModel(uint32_t model_id, shared_ptr<hybrid::HybridDavinciModel> &hybrid_model) {
  412. GE_CHK_BOOL_EXEC(hybrid_model != nullptr, return, "hybrid_model ptr is null, id: %u", model_id);
  413. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  414. hybrid_model_map_[model_id] = hybrid_model;
  415. }
  416. Status ModelManager::DeleteModel(uint32_t id) {
  417. // These two pointers are used to unbind erase() and model destruction process.
  418. std::shared_ptr<DavinciModel> tmp_model;
  419. std::shared_ptr<hybrid::HybridDavinciModel> tmp_hybrid_model;
  420. {
  421. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  422. auto it = model_map_.find(id);
  423. auto hybrid_model_it = hybrid_model_map_.find(id);
  424. if (it != model_map_.end()) {
  425. uint64_t session_id = it->second->GetSessionId();
  426. std::string model_key = std::to_string(session_id) + "_" + std::to_string(id) + "_" +
  427. std::to_string(it->second->SubModelId());
  428. auto iter_aicpu_kernel = model_aicpu_kernel_.find(model_key);
  429. if (iter_aicpu_kernel != model_aicpu_kernel_.end()) {
  430. (void)model_aicpu_kernel_.erase(iter_aicpu_kernel);
  431. }
  432. tmp_model = it->second;
  433. (void)model_map_.erase(it);
  434. } else if (hybrid_model_it != hybrid_model_map_.end()) {
  435. tmp_hybrid_model = hybrid_model_it->second;
  436. (void)hybrid_model_map_.erase(hybrid_model_it);
  437. } else {
  438. REPORT_INNER_ERROR("E19999", "model_id:%u not exist in model_map, check invalid", id);
  439. GELOGE(ACL_ERROR_GE_EXEC_MODEL_ID_INVALID, "model id %u does not exists.", id);
  440. return ACL_ERROR_GE_EXEC_MODEL_ID_INVALID;
  441. }
  442. }
  443. return SUCCESS;
  444. }
  445. std::shared_ptr<DavinciModel> ModelManager::GetModel(uint32_t id) {
  446. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  447. auto it = model_map_.find(id);
  448. return (it == model_map_.end()) ? nullptr : it->second;
  449. }
  450. std::shared_ptr<hybrid::HybridDavinciModel> ModelManager::GetHybridModel(uint32_t id) {
  451. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  452. auto it = hybrid_model_map_.find(id);
  453. return (it == hybrid_model_map_.end()) ? nullptr : it->second;
  454. }
  455. Status ModelManager::Unload(uint32_t model_id) {
  456. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload model id: %u", model_id);
  457. if (device_count > 0) {
  458. device_count--;
  459. GELOGI("Unload model %u success.", model_id);
  460. } else {
  461. GELOGI("Unload model %u success.no need reset device,device_count: %u", model_id, device_count);
  462. }
  463. std::lock_guard<std::mutex> lock(exeception_infos_mutex_);
  464. exception_infos_.clear();
  465. return SUCCESS;
  466. }
  467. Status ModelManager::UnloadModeldef(uint32_t model_id) {
  468. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload modeldef id: %u", model_id);
  469. return SUCCESS;
  470. }
  471. Status ModelManager::DataInput(const InputData &input_data, OutputData &output_data) {
  472. GELOGI("calling the DataInput");
  473. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  474. GE_CHECK_NOTNULL(data_wrap);
  475. Status status = data_wrap->Init(input_data, output_data);
  476. if (status != SUCCESS) {
  477. REPORT_CALL_ERROR("E19999", "Init InputDataWrapper failed, input data index: %u", input_data.index);
  478. GELOGE(domi::PUSH_DATA_FAILED, "Init InputDataWrapper failed, input data index: %u.", input_data.index);
  479. return domi::PUSH_DATA_FAILED;
  480. }
  481. uint32_t model_id = input_data.model_id;
  482. output_data.model_id = model_id;
  483. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  484. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid model id %u in InputData! ", model_id);
  485. GE_IF_BOOL_EXEC(model->GetDataInputTid() == 0, model->SetDataInputTid(mmGetTid()));
  486. DataInputer *inputer = model->GetDataInputer();
  487. GE_CHECK_NOTNULL(inputer);
  488. if (inputer->Push(data_wrap) != SUCCESS) {
  489. REPORT_CALL_ERROR("E19999", "DataInputer queue is full, please call again later, model_id %u", model_id);
  490. GELOGE(domi::DATA_QUEUE_ISFULL, "Data queue is full, please call again later, model_id %u ", model_id);
  491. return domi::DATA_QUEUE_ISFULL;
  492. }
  493. GELOGD("Data input success, model id:%u", model_id);
  494. return SUCCESS;
  495. }
  496. Status ModelManager::GetCurDynamicDims(const vector<vector<int64_t>> &user_real_input_dims,
  497. const vector<pair<string, vector<int64_t>>> &user_input_dims,
  498. vector<int32_t> &cur_dynamic_dims) {
  499. GELOGD("Start get cur dynamic dims.");
  500. if (user_real_input_dims.size() != user_input_dims.size()) {
  501. REPORT_INNER_ERROR("E19999", "Param user_real_input_dims.size:%zu != user_input_dims.size:%zu, "
  502. "check invalid",
  503. user_real_input_dims.size(), user_input_dims.size());
  504. GELOGE(INTERNAL_ERROR,
  505. "The input count of user: %zu should be equal to the data count of graph: %zu",
  506. user_real_input_dims.size(), user_input_dims.size());
  507. return INTERNAL_ERROR;
  508. }
  509. for (size_t i = 0; i < user_input_dims.size(); ++i) {
  510. if (user_real_input_dims[i].size() != user_input_dims[i].second.size()) {
  511. REPORT_INNER_ERROR("E19999", "Param user_real_input_dims[%zu].size:%zu != user_input_dims[%zu].size:%zu, "
  512. "check invalid", i, user_real_input_dims[i].size(),
  513. i, user_input_dims[i].second.size());
  514. GELOGE(INTERNAL_ERROR,
  515. "The shape size: %zu of dynamic input: %s should be equal to the shape size of input shape: %zu.",
  516. user_real_input_dims[i].size(), user_input_dims[i].first.c_str(), user_input_dims[i].second.size());
  517. return INTERNAL_ERROR;
  518. }
  519. for (size_t j = 0; j < user_input_dims.at(i).second.size(); ++j) {
  520. if (user_input_dims.at(i).second.at(j) < 0) {
  521. cur_dynamic_dims.emplace_back(static_cast<int32_t>(user_real_input_dims[i][j]));
  522. }
  523. }
  524. }
  525. GELOGD("Cur dynamic dims is %s.", formats::JoinToString(cur_dynamic_dims).c_str());
  526. bool cur_dynamic_dims_valid = false;
  527. std::vector<std::string> shape_strs = ge::StringUtils::Split(GetLocalOmgContext().dynamic_dims, ';');
  528. for (auto dynamic_dim : shape_strs) {
  529. if (dynamic_dim == formats::JoinToString(cur_dynamic_dims)) {
  530. cur_dynamic_dims_valid = true;
  531. break;
  532. }
  533. }
  534. if (!cur_dynamic_dims_valid) {
  535. REPORT_INNER_ERROR("E19999", "cur dynamic dims is %s, not exist in options, check invalid",
  536. formats::JoinToString(cur_dynamic_dims).c_str());
  537. GELOGE(INTERNAL_ERROR, "Cur dynamic dims is %s, not exist in options.",
  538. formats::JoinToString(cur_dynamic_dims).c_str());
  539. return INTERNAL_ERROR;
  540. }
  541. return SUCCESS;
  542. }
  543. ///
  544. /// @ingroup domi_ome
  545. /// @brief load Input and output TensorInfo for Model
  546. /// @return Status run result
  547. ///
  548. Status ModelManager::DataInputTensor(uint32_t model_id, const std::vector<ge::Tensor> &inputs) {
  549. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  550. auto hybrid_model = GetHybridModel(model_id);
  551. if (hybrid_model == nullptr) {
  552. GE_CHECK_NOTNULL(model);
  553. }
  554. InputData input_data;
  555. input_data.model_id = model_id;
  556. input_data.timeout = 0;
  557. input_data.timestamp = 0;
  558. input_data.index = 0;
  559. for (size_t i = 0; i < inputs.size(); ++i) {
  560. DataBuffer data;
  561. const TensorDesc &tensor_desc = inputs[i].GetTensorDesc();
  562. data.data = reinterpret_cast<void *>(const_cast<uint8_t *>(inputs[i].GetData()));
  563. data.length = inputs[i].GetSize();
  564. data.placement = static_cast<uint32_t>(tensor_desc.GetPlacement());
  565. input_data.shapes.emplace_back(tensor_desc.GetShape().GetDims());
  566. input_data.blobs.push_back(data);
  567. }
  568. if (!GetLocalOmgContext().user_input_dims.empty() && GetLocalOmgContext().need_multi_batch) {
  569. std::vector<int32_t> cur_dynamic_dims;
  570. if (!GetLocalOmgContext().user_real_input_dims.empty()) {
  571. if (GetCurDynamicDims(GetLocalOmgContext().user_real_input_dims, GetLocalOmgContext().user_input_dims,
  572. cur_dynamic_dims) != SUCCESS) {
  573. GELOGE(INTERNAL_ERROR, "[Train_Dynamic] Failed to Parse real_dynamic_dims.");
  574. return INTERNAL_ERROR;
  575. }
  576. DataBuffer data;
  577. data.data = new(std::nothrow) int32_t[cur_dynamic_dims.size()];
  578. GE_CHECK_NOTNULL(data.data);
  579. uint32_t length = static_cast<uint32_t>(cur_dynamic_dims.size() * sizeof(int32_t));
  580. GE_CHK_BOOL_EXEC(memcpy_s(data.data, length, cur_dynamic_dims.data(), length) == EOK, return INTERNAL_ERROR,
  581. "Failed to memcpy data.");
  582. data.length = length;
  583. input_data.blobs.push_back(data);
  584. }
  585. }
  586. OutputData output_data;
  587. output_data.model_id = model_id;
  588. output_data.index = 0;
  589. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  590. GE_CHECK_NOTNULL(data_wrap);
  591. GE_CHK_STATUS_EXEC(data_wrap->Init(input_data, output_data), return domi::PUSH_DATA_FAILED,
  592. "Init InputDataWrapper failed,input data model_id is : %u.", model_id);
  593. if (hybrid_model != nullptr) {
  594. GE_CHK_STATUS_RET(hybrid_model->EnqueueData(data_wrap), "Data queue is full, please call again later, model_id %u ",
  595. model_id);
  596. return SUCCESS;
  597. }
  598. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid model id %u in InputData! ", model_id);
  599. DataInputer *inputer = model->GetDataInputer();
  600. GE_CHECK_NOTNULL(inputer);
  601. GE_CHK_STATUS_EXEC(inputer->Push(data_wrap), return domi::DATA_QUEUE_ISFULL,
  602. "Data queue is full, please call again later, model_id %u ", model_id);
  603. GELOGD("Data input success, model id:%u", model_id);
  604. return SUCCESS;
  605. }
  606. ///
  607. /// @ingroup domi_ome
  608. /// @brief create model thread, start to execute model
  609. /// @param [in] model_id Model ID to be started
  610. /// @return Status model run result
  611. /// @author
  612. ///
  613. Status ModelManager::Start(uint32_t model_id) {
  614. auto hybrid_model = GetHybridModel(model_id);
  615. if (hybrid_model != nullptr) {
  616. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStart());
  617. GELOGI("Start hybrid model %u success.", model_id);
  618. return SUCCESS;
  619. }
  620. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  621. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid model id %u to start! ", model_id);
  622. Status status = davinci_model->ModelRunStart();
  623. if (status == SUCCESS) {
  624. GELOGI("Start model %u success.", model_id);
  625. }
  626. return status;
  627. }
  628. ///
  629. /// @ingroup domi_ome
  630. /// @brief Model ID stop
  631. /// @only when unloaded
  632. /// @param [in] model_id Model ID to be stopped
  633. /// @return Status model stop result
  634. /// @author
  635. ///
  636. Status ModelManager::Stop(uint32_t model_id) {
  637. auto hybrid_model = GetHybridModel(model_id);
  638. if (hybrid_model != nullptr) {
  639. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStop());
  640. GELOGI("Stop hybrid model %u success.", model_id);
  641. return SUCCESS;
  642. }
  643. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  644. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid model id %u to stop!", model_id);
  645. Status status = davinci_model->ModelRunStop();
  646. if (status == SUCCESS) {
  647. GELOGI("Stop model %u success.", model_id);
  648. }
  649. return status;
  650. }
  651. ///
  652. /// @ingroup domi_ome
  653. /// @brief Command handle
  654. /// @iterator 1 only Ieference, Debug 2 modes
  655. /// @param [in] command command to handle
  656. /// @return Status command handle result
  657. /// @author
  658. ///
  659. Status ModelManager::HandleCommand(const Command &command) {
  660. static const std::map<std::string, std::function<uint32_t(const Command &)>> cmds = {
  661. {kCmdTypeDump, HandleDumpCommand}, {kCmdTypeProfInit, HandleProfInitCommand},
  662. {kCmdTypeProfFinalize, HandleProfFinalizeCommand}, {kCmdTypeProfStart, HandleProfStartCommand},
  663. {kCmdTypeProfStop, HandleProfStopCommand},
  664. {kCmdTypeProfModelSubscribe, HandleProfModelSubscribeCommand},
  665. {kCmdTypeProfModelUnsubscribe, HandleProfModelUnsubscribeCommand}};
  666. auto iter = cmds.find(command.cmd_type);
  667. if (iter == cmds.end()) {
  668. REPORT_INNER_ERROR("E19999", "Unsupported command:%s check",
  669. command.cmd_type.c_str());
  670. GELOGE(PARAM_INVALID, "Unsupported command: %s", command.cmd_type.c_str());
  671. return PARAM_INVALID;
  672. } else {
  673. return iter->second(command);
  674. }
  675. }
  676. Status ModelManager::GetModelByCmd(const Command &command,
  677. std::shared_ptr<DavinciModel> &davinci_model) {
  678. if (command.cmd_params.size() < kCmdParSize) {
  679. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu < kCmdParSize:%u, command_type:%s, "
  680. "check invalid", command.cmd_params.size(), kCmdParSize,
  681. command.cmd_type.c_str());
  682. GELOGE(PARAM_INVALID, "When the cmd_type is '%s', the size of cmd_params must larger than 2.",
  683. command.cmd_type.c_str());
  684. return PARAM_INVALID;
  685. }
  686. std::string map_key = command.cmd_params[0];
  687. std::string value = command.cmd_params[1];
  688. if (map_key == PROFILE_MODEL_ID) {
  689. int32_t model_id = 0;
  690. try {
  691. model_id = std::stoi(value);
  692. } catch (std::invalid_argument &) {
  693. REPORT_INNER_ERROR("E19999", "%s param:%s, check invalid", PROFILE_MODEL_ID.c_str(),
  694. value.c_str());
  695. GELOGE(PARAM_INVALID, "Model id: %s is invalid.", value.c_str());
  696. return PARAM_INVALID;
  697. } catch (std::out_of_range &) {
  698. REPORT_INNER_ERROR("E19999", "%s param:%s, check out of range", PROFILE_MODEL_ID.c_str(),
  699. value.c_str());
  700. GELOGE(PARAM_INVALID, "Model id: %s is out of range.", value.c_str());
  701. return PARAM_INVALID;
  702. } catch (...) {
  703. REPORT_INNER_ERROR("E19999", "%s param:%s, check cannot change to int",
  704. PROFILE_MODEL_ID.c_str(), value.c_str());
  705. GELOGE(FAILED, "Model id: %s cannot change to int.", value.c_str());
  706. return FAILED;
  707. }
  708. auto model_manager = ModelManager::GetInstance();
  709. GE_CHECK_NOTNULL(model_manager);
  710. davinci_model = model_manager->GetModel(static_cast<uint32_t>(model_id));
  711. if (davinci_model == nullptr) {
  712. REPORT_INNER_ERROR("E19999", "GetModel from model_manager fail, model_id:%u",
  713. model_id);
  714. GELOGE(FAILED, "Model id: %d is invaild or model is not loaded.", model_id);
  715. return FAILED;
  716. }
  717. } else {
  718. REPORT_INNER_ERROR("E19999", "Fisrt cmd_param not %s, check invalid",
  719. PROFILE_MODEL_ID.c_str());
  720. GELOGE(FAILED, "The model_id parameter is not found in the command.");
  721. return FAILED;
  722. }
  723. return SUCCESS;
  724. }
  725. Status ModelManager::HandleProfModelSubscribeCommand(const Command &command) {
  726. std::shared_ptr<DavinciModel> davinci_model = nullptr;
  727. Status ret = GetModelByCmd(command, davinci_model);
  728. if (ret != SUCCESS) {
  729. return ret;
  730. }
  731. if (ProfilingManager::Instance().ProfModelSubscribe(command.module_index,
  732. static_cast<void *>(davinci_model.get())) != SUCCESS) {
  733. GELOGE(FAILED, "Handle prof model subscribe failed.");
  734. return FAILED;
  735. }
  736. return SUCCESS;
  737. }
  738. Status ModelManager::HandleProfModelUnsubscribeCommand(const Command &command) {
  739. std::shared_ptr<DavinciModel> davinci_model = nullptr;
  740. Status ret = GetModelByCmd(command, davinci_model);
  741. if (ret != SUCCESS) {
  742. return ret;
  743. }
  744. if (ProfilingManager::Instance().ProfModelUnsubscribe(static_cast<void *>(davinci_model.get())) != SUCCESS) {
  745. GELOGE(FAILED, "Handle prof model unsubscribe failed.");
  746. return FAILED;
  747. }
  748. return SUCCESS;
  749. }
  750. Status ModelManager::HandleProfInitCommand(const Command &command) {
  751. uint64_t module_index = command.module_index;
  752. if (ProfilingManager::Instance().ProfInit(module_index) != SUCCESS) {
  753. GELOGE(FAILED, "Handle prof init failed.");
  754. return FAILED;
  755. }
  756. return SUCCESS;
  757. }
  758. Status ModelManager::HandleProfFinalizeCommand(const Command &command) {
  759. if (ProfilingManager::Instance().ProfFinalize() != SUCCESS) {
  760. GELOGE(FAILED, "Handle prof finalize failed.");
  761. return FAILED;
  762. }
  763. return SUCCESS;
  764. }
  765. /*
  766. * cmd para when prof start
  767. * "devNums:2"
  768. * "devIdList:1,2"
  769. * "profilingOption:PROF_OP_TRACE"
  770. * "aicoreMetrics:AICORE_ARITHMATIC_THROUGHPUT"
  771. */
  772. Status ModelManager::HandleProfStartCommand(const Command &command) {
  773. if (command.cmd_params.size() < kProfStartCmdParaSize) {
  774. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu < %zu, check invalid",
  775. command.cmd_params.size(), kProfStartCmdParaSize);
  776. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile start', the size of cmd_params must larger than 2.");
  777. return PARAM_INVALID;
  778. }
  779. if (command.cmd_params.size() > kProfCmdParaMaxSize) {
  780. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu > %zu, check invalid",
  781. command.cmd_params.size(), kProfCmdParaMaxSize);
  782. GELOGE(PARAM_INVALID, "Command para size[%zu] larger than max[1000].", command.cmd_params.size());
  783. return PARAM_INVALID;
  784. }
  785. std::map<std::string, std::string> cmd_params_map;
  786. uint32_t step = 2;
  787. for (uint32_t i = 0; i < command.cmd_params.size(); i += step) {
  788. if (i + 1 >= command.cmd_params.size()) {
  789. continue;
  790. }
  791. cmd_params_map[command.cmd_params[i]] = command.cmd_params[i + 1];
  792. }
  793. uint64_t module_index = command.module_index;
  794. if (ProfilingManager::Instance().ProfStartProfiling(module_index, cmd_params_map) != SUCCESS) {
  795. GELOGE(FAILED, "Handle prof start failed.");
  796. return FAILED;
  797. }
  798. return SUCCESS;
  799. }
  800. Status ModelManager::HandleProfStopCommand(const Command &command) {
  801. if (command.cmd_params.size() < kProfStartCmdParaSize) {
  802. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu < %zu, check invalid",
  803. command.cmd_params.size(), kProfStartCmdParaSize);
  804. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile stop', the size of cmd_params must larger than 2.");
  805. return PARAM_INVALID;
  806. }
  807. if (command.cmd_params.size() > kProfCmdParaMaxSize) {
  808. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu > %zu, check invalid",
  809. command.cmd_params.size(), kProfCmdParaMaxSize);
  810. GELOGE(PARAM_INVALID, "Command para size[%zu] larger than max[1000].", command.cmd_params.size());
  811. return PARAM_INVALID;
  812. }
  813. std::map<std::string, std::string> cmd_params_map;
  814. uint32_t step = 2;
  815. for (uint32_t i = 0; i < command.cmd_params.size(); i += step) {
  816. if (i + 1 >= command.cmd_params.size()) {
  817. continue;
  818. }
  819. cmd_params_map[command.cmd_params[i]] = command.cmd_params[i + 1];
  820. }
  821. uint64_t module_index = command.module_index;
  822. if (ProfilingManager::Instance().ProfStopProfiling(module_index, cmd_params_map) != SUCCESS) {
  823. GELOGE(FAILED, "Handle prof finalize failed.");
  824. return FAILED;
  825. }
  826. return SUCCESS;
  827. }
  828. static Status ParserPara(const Command &command, const string &dump_key, string &dump_value) {
  829. auto iter = std::find(command.cmd_params.begin(), command.cmd_params.end(), dump_key);
  830. if (iter != command.cmd_params.end()) {
  831. ++iter;
  832. if (iter == command.cmd_params.end()) {
  833. REPORT_INNER_ERROR("E19999", "dump_key:%s can't find in command.param, check invalid",
  834. dump_key.c_str());
  835. GELOGE(PARAM_INVALID, "Invalid access.");
  836. return PARAM_INVALID;
  837. }
  838. dump_value = *iter;
  839. }
  840. return SUCCESS;
  841. }
  842. Status ModelManager::HandleDumpCommand(const Command &command) {
  843. if (command.cmd_params.size() % kDumpCmdPairSize != 0) {
  844. REPORT_INNER_ERROR("E19999", "command.cmd_params.size:%zu MOD 2 != 0, check invalid",
  845. command.cmd_params.size());
  846. GELOGE(PARAM_INVALID, "When the cmd_type is 'dump', the size of cmd_params must be a even number.");
  847. return PARAM_INVALID;
  848. }
  849. std::string dump_status("off");
  850. std::string dump_model(DUMP_ALL_MODEL);
  851. std::string dump_path("/");
  852. std::string dump_mode("output");
  853. std::set<std::string> dump_layers;
  854. auto ret = ParserPara(command, DUMP_STATUS, dump_status);
  855. if (ret != SUCCESS) {
  856. GELOGE(PARAM_INVALID, "parser dump status failed");
  857. return FAILED;
  858. }
  859. GELOGI("dump status = %s.", dump_status.c_str());
  860. ret = ParserPara(command, DUMP_MODEL, dump_model);
  861. if (ret != SUCCESS) {
  862. GELOGE(PARAM_INVALID, "parser dump model failed");
  863. return FAILED;
  864. }
  865. GELOGI("dump model = %s.", dump_model.c_str());
  866. if (dump_status == "off" || dump_status == "OFF") {
  867. dump_properties_.DeletePropertyValue(dump_model);
  868. return SUCCESS;
  869. }
  870. for (size_t i = 0; i < command.cmd_params.size() / kDumpCmdPairSize; ++i) {
  871. if (command.cmd_params.at(i * kDumpCmdPairSize).find(DUMP_LAYER) != std::string::npos) {
  872. GELOGI("dump layer: %s.", command.cmd_params.at(i * kDumpCmdPairSize + 1).c_str());
  873. dump_layers.insert(command.cmd_params.at(i * kDumpCmdPairSize + 1));
  874. }
  875. }
  876. ret = ParserPara(command, DUMP_FILE_PATH, dump_path);
  877. if (ret != SUCCESS) {
  878. GELOGE(PARAM_INVALID, "parser dump path failed");
  879. return FAILED;
  880. }
  881. if (!dump_path.empty() && dump_path[dump_path.size() - 1] != '/') {
  882. dump_path = dump_path + "/";
  883. }
  884. dump_path = dump_path + CurrentTimeInStr() + "/";
  885. GELOGI("dump path = %s.", dump_path.c_str());
  886. ret = ParserPara(command, DUMP_MODE, dump_mode);
  887. if (ret != SUCCESS) {
  888. GELOGE(PARAM_INVALID, "parser dump mode failed");
  889. return FAILED;
  890. }
  891. GELOGI("dump mode = %s", dump_mode.c_str());
  892. dump_properties_.AddPropertyValue(dump_model, dump_layers);
  893. dump_properties_.SetDumpPath(dump_path);
  894. dump_properties_.SetDumpMode(dump_mode);
  895. return SUCCESS;
  896. }
  897. Status ModelManager::GetMaxUsedMemory(const uint32_t model_id, uint64_t &max_size) {
  898. auto hybrid_model = GetHybridModel(model_id);
  899. if (hybrid_model != nullptr) {
  900. max_size = 0;
  901. return SUCCESS;
  902. }
  903. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  904. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetMaxUsedMemory Failed, Invalid model id %u!",
  905. model_id);
  906. max_size = davinci_model->TotalMemSize();
  907. return SUCCESS;
  908. }
  909. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  910. vector<InputOutputDescInfo> &output_desc) {
  911. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  912. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetInputOutputDescInfo Failed, Invalid model id %u!",
  913. model_id);
  914. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc);
  915. }
  916. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  917. vector<InputOutputDescInfo> &output_desc,
  918. std::vector<uint32_t> &inputFormats, std::vector<uint32_t> &outputFormats,
  919. bool new_model_desc) {
  920. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  921. if (hybrid_davinci_model != nullptr) {
  922. hybrid_davinci_model->SetModelDescVersion(new_model_desc);
  923. return hybrid_davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats);
  924. }
  925. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  926. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  927. "GetInputOutputDescInfo Failed, Invalid model id %u!", model_id);
  928. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats, new_model_desc);
  929. }
  930. ///
  931. /// @ingroup ge
  932. /// @brief Get dynamic batch_info
  933. /// @param [in] model_id
  934. /// @param [out] batch_info
  935. /// @return execute result
  936. ///
  937. Status ModelManager::GetDynamicBatchInfo(const uint32_t model_id, std::vector<std::vector<int64_t>> &batch_info,
  938. int32_t &dynamic_type) {
  939. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  940. if (hybrid_davinci_model != nullptr) {
  941. return hybrid_davinci_model->GetDynamicBatchInfo(batch_info, dynamic_type);
  942. }
  943. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  944. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  945. "GetDynamicBatchInfo failed, Invalid model id %u!", model_id);
  946. return davinci_model->GetDynamicBatchInfo(batch_info, dynamic_type);
  947. }
  948. ///
  949. /// @ingroup ge
  950. /// @brief Get combined dynamic dims info
  951. /// @param [in] model_id
  952. /// @param [out] batch_info
  953. /// @return execute result
  954. ///
  955. Status ModelManager::GetCombinedDynamicDims(const uint32_t model_id, vector<vector<int64_t>> &batch_info) {
  956. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  957. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  958. "GetCombinedDynamicDims Failed, Invalid Model ID %u!", model_id);
  959. davinci_model->GetCombinedDynamicDims(batch_info);
  960. return SUCCESS;
  961. }
  962. ///
  963. /// @ingroup ge
  964. /// @brief Get user designate shape order
  965. /// @param [in] model_id
  966. /// @param [out] user_input_shape_order
  967. /// @return execute result
  968. ///
  969. Status ModelManager::GetUserDesignateShapeOrder(const uint32_t model_id,
  970. std::vector<std::string> &user_input_shape_order) {
  971. auto hybrid_davinci_model = GetHybridModel(model_id);
  972. if (hybrid_davinci_model != nullptr) {
  973. hybrid_davinci_model->GetUserDesignateShapeOrder(user_input_shape_order);
  974. return SUCCESS;
  975. }
  976. auto davinci_model = GetModel(model_id);
  977. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  978. "GetUserDesignateShapeOrder Failed, Invalid Model ID %u!", model_id)
  979. davinci_model->GetUserDesignateShapeOrder(user_input_shape_order);
  980. return SUCCESS;
  981. }
  982. Status ModelManager::GetCurShape(const uint32_t model_id, std::vector<int64_t> &batch_info, int32_t &dynamic_type) {
  983. auto davinci_model = GetModel(model_id);
  984. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  985. "GetCurShape Failed, Invalid Model ID %u!", model_id);
  986. davinci_model->GetCurShape(batch_info, dynamic_type);
  987. return SUCCESS;
  988. }
  989. Status ModelManager::GetOpAttr(uint32_t model_id, const std::string &op_name, const std::string &attr_name,
  990. std::string &attr_value) {
  991. auto davinci_model = GetModel(model_id);
  992. if (davinci_model != nullptr) {
  993. return davinci_model->GetOpAttr(op_name, attr_name, attr_value);
  994. }
  995. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  996. if (hybrid_davinci_model != nullptr) {
  997. return hybrid_davinci_model->GetOpAttr(op_name, attr_name, attr_value);
  998. }
  999. GELOGE(ACL_ERROR_GE_EXEC_MODEL_ID_INVALID, "[Get][Model]Get model failed, invalid model id:%u.", model_id);
  1000. REPORT_INNER_ERROR("E19999", "Get model failed, invalid model id:%u.", model_id);
  1001. return ACL_ERROR_GE_EXEC_MODEL_ID_INVALID;
  1002. }
  1003. Status ModelManager::GetModelAttr(uint32_t model_id, std::vector<string> &dynamic_output_shape_info) {
  1004. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  1005. if (hybrid_davinci_model != nullptr) {
  1006. hybrid_davinci_model->GetModelAttr(dynamic_output_shape_info);
  1007. return SUCCESS;
  1008. }
  1009. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1010. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1011. "GetModelAttr Failed, Invalid Model ID %u!", model_id);
  1012. davinci_model->GetModelAttr(dynamic_output_shape_info);
  1013. return SUCCESS;
  1014. }
  1015. ///
  1016. /// @ingroup ge
  1017. /// @brief Get AIPP info
  1018. /// @param [in] model_id
  1019. /// @param [in] index
  1020. /// @param [out] aipp_info
  1021. /// @return execute result
  1022. ///
  1023. Status ModelManager::GetAippInfo(const uint32_t model_id, uint32_t index, AippConfigInfo &aipp_info) {
  1024. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1025. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1026. "GetAIPPInfo failed, invalid model_id is %u.", model_id);
  1027. return davinci_model->GetAippInfo(index, aipp_info);
  1028. }
  1029. Status ModelManager::GetAippType(uint32_t model_id, uint32_t index, InputAippType &type, size_t &aipp_index) {
  1030. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1031. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1032. "GetAIPPInfo failed, invalid model_id is %u.", model_id);
  1033. return davinci_model->GetAippType(index, type, aipp_index);
  1034. }
  1035. Status ModelManager::GenSessionId(uint64_t &session_id) {
  1036. const uint64_t kSessionTimeMask = 0xffffffffffff0000;
  1037. const uint64_t kSessionPidMask = 0x000000000000ff00;
  1038. const uint64_t kSessionBiasMask = 0x00000000000000ff;
  1039. const uint64_t kMaskPerOffset = 8;
  1040. std::lock_guard<std::mutex> lock(session_id_create_mutex_);
  1041. mmTimeval tv;
  1042. if (mmGetTimeOfDay(&tv, nullptr) != 0) {
  1043. REPORT_CALL_ERROR("E19999", "Call mmGetTimeOfDay fail. errmsg:%s", strerror(errno));
  1044. GELOGE(INTERNAL_ERROR, "Failed to get current time.");
  1045. return INTERNAL_ERROR;
  1046. }
  1047. uint64_t timestamp = static_cast<uint64_t>(tv.tv_sec * kTimeSpecMiro + tv.tv_usec); // 1000000us
  1048. static uint32_t pid = mmGetPid();
  1049. session_id_bias_++;
  1050. session_id = ((timestamp<<kMaskPerOffset<<kMaskPerOffset) & kSessionTimeMask) +
  1051. ((pid<<kMaskPerOffset) & kSessionPidMask) + (session_id_bias_ & kSessionBiasMask);
  1052. GELOGD("Generate new session id: %lu.", session_id);
  1053. return SUCCESS;
  1054. }
  1055. Status ModelManager::LoadModelOffline(uint32_t &model_id, const ModelData &model, shared_ptr<ModelListener> listener,
  1056. void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) {
  1057. GE_CHK_BOOL_RET_STATUS(model.key.empty() || mmAccess2(model.key.c_str(), M_F_OK) == EN_OK,
  1058. ACL_ERROR_GE_PARAM_INVALID, "Input key file path %s is invalid, %s", model.key.c_str(), strerror(errno));
  1059. GenModelId(&model_id);
  1060. mmTimespec timespec = mmGetTickCount();
  1061. ModelHelper model_helper;
  1062. Status ret = model_helper.LoadRootModel(model);
  1063. if (ret != SUCCESS) {
  1064. GELOGE(ret, "load model failed.");
  1065. return ret;
  1066. }
  1067. if (model_helper.GetModelType()) {
  1068. bool is_shape_unknown = false;
  1069. GE_CHK_STATUS_RET(model_helper.GetGeRootModel()->CheckIsUnknownShape(is_shape_unknown),
  1070. "CheckIsUnknownShape failed, model id:%u", model_id);
  1071. if (is_shape_unknown || GetContext().GetHostExecFlag()) {
  1072. return DoLoadHybridModelOnline(model_id, model.om_name, model_helper.GetGeRootModel(), listener);
  1073. }
  1074. }
  1075. do {
  1076. GeModelPtr ge_model = model_helper.GetGeModel();
  1077. shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(model.priority, listener);
  1078. if (davinci_model == nullptr) {
  1079. REPORT_CALL_ERROR("E19999", "New DavinciModel fail");
  1080. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "Make shared failed");
  1081. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  1082. }
  1083. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * kTimeSpecNano +
  1084. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  1085. ret = davinci_model->Assign(ge_model);
  1086. if (ret != SUCCESS) {
  1087. GELOGW("assign model failed.");
  1088. break;
  1089. }
  1090. davinci_model->SetId(model_id);
  1091. int32_t device_id = 0;
  1092. rtError_t rt_ret = rtGetDevice(&device_id);
  1093. if (rt_ret != RT_ERROR_NONE || device_id < 0) {
  1094. REPORT_CALL_ERROR("E19999", "Call rtGetDevice failed, ret = 0x%X", rt_ret);
  1095. GELOGE(rt_ret, "Call rtGetDevice failed, ret = 0x%X, device_id = %d.", rt_ret, device_id);
  1096. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1097. }
  1098. davinci_model->SetDeviceId(device_id);
  1099. davinci_model->SetOmName(model.om_name);
  1100. if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsDumpOpen()) {
  1101. davinci_model->SetDumpProperties(DumpManager::GetInstance().GetDumpProperties(kInferSessionId));
  1102. } else {
  1103. davinci_model->SetDumpProperties(dump_properties_);
  1104. }
  1105. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  1106. /// These session_ids come from the same model, so the values of session_id are the same.
  1107. /// Update session_id for infer in load model to avoid the same session_id.
  1108. uint64_t new_session_id;
  1109. ret = GenSessionId(new_session_id);
  1110. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Generate session_id for inference failed.");
  1111. ret = davinci_model->UpdateSessionId(new_session_id);
  1112. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Update session_id for inference failed.");
  1113. ret = davinci_model->Init(dev_ptr, mem_size, weight_ptr, weight_size);
  1114. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "DavinciInit failed.");
  1115. InsertModel(model_id, davinci_model);
  1116. GELOGI("Parse model %u success.", model_id);
  1117. GE_IF_BOOL_EXEC(ret == SUCCESS, device_count++);
  1118. } while (0);
  1119. return ret;
  1120. }
  1121. ///
  1122. /// @ingroup ge
  1123. /// @brief ACL case, Load task list with queue.
  1124. /// @param [out] model_id: model id for manager.
  1125. /// @param [in] model_data: Model data load from offline model file.
  1126. /// @param [in] input_que_ids: input queue ids from user, num equals Data Op.
  1127. /// @param [in] output_que_ids: input queue ids from user, num equals NetOutput Op.
  1128. /// @return: 0 for success / others for fail
  1129. ///
  1130. Status ModelManager::LoadModelWithQ(uint32_t &model_id, const ModelData &model_data,
  1131. const std::vector<uint32_t> &input_queue_ids,
  1132. const std::vector<uint32_t> &output_queue_ids) {
  1133. GE_CHK_BOOL_RET_STATUS(model_data.key.empty() || mmAccess2(model_data.key.c_str(), M_F_OK) == EN_OK,
  1134. ACL_ERROR_GE_PARAM_INVALID, "input key file path %s is not valid, %s",
  1135. model_data.key.c_str(), strerror(errno));
  1136. ModelHelper model_helper;
  1137. Status ret = model_helper.LoadModel(model_data);
  1138. if (ret != SUCCESS) {
  1139. GELOGE(ret, "load model failed.");
  1140. return ret;
  1141. }
  1142. shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(model_data.priority, nullptr);
  1143. if (davinci_model == nullptr) {
  1144. REPORT_CALL_ERROR("E19999", "New DavinciModel fail");
  1145. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "create model failed.");
  1146. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  1147. }
  1148. ret = davinci_model->Assign(model_helper.GetGeModel());
  1149. if (ret != SUCCESS) {
  1150. GELOGE(ret, "assign model failed.");
  1151. return ret;
  1152. }
  1153. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  1154. /// These session_ids come from the same model, so the values of session_id are the same.
  1155. /// Update session_id for infer in load model to avoid the same session_id.
  1156. uint64_t new_session_id;
  1157. ret = GenSessionId(new_session_id);
  1158. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Generate session_id for infer failed.");
  1159. ret = davinci_model->UpdateSessionId(new_session_id);
  1160. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Update session_id for infer failed.");
  1161. GenModelId(&model_id);
  1162. davinci_model->SetId(model_id);
  1163. ret = davinci_model->SetQueIds(input_queue_ids, output_queue_ids);
  1164. if (ret != SUCCESS) {
  1165. GELOGE(ret, "set model queue ids failed.");
  1166. return ret;
  1167. }
  1168. davinci_model->SetDumpProperties(dump_properties_);
  1169. ret = davinci_model->Init();
  1170. if (ret != SUCCESS) {
  1171. GELOGE(ret, "init model failed.");
  1172. return ret;
  1173. }
  1174. InsertModel(model_id, davinci_model);
  1175. GELOGI("Parse model %u success.", model_id);
  1176. return SUCCESS;
  1177. }
  1178. ///
  1179. /// @ingroup domi_ome
  1180. /// @brief ACL case, not start new thread, return result
  1181. /// @param [in] model_id mode id
  1182. /// @param [in] stream model stream
  1183. /// @param [in] async_mode is asynchronize mode.
  1184. /// @param [in] input_data input data
  1185. /// @param [in] input_desc description of input data
  1186. /// @param [out] output_data output data
  1187. /// @param [out] output_desc description of output data
  1188. ///
  1189. Status ModelManager::ExecuteModel(uint32_t model_id, rtStream_t stream, bool async_mode, const InputData &input_data,
  1190. const std::vector<GeTensorDesc> &input_desc, OutputData &output_data,
  1191. std::vector<GeTensorDesc> &output_desc) {
  1192. std::shared_ptr<hybrid::HybridDavinciModel> hybrid_davinci_model = GetHybridModel(model_id);
  1193. if (hybrid_davinci_model != nullptr) {
  1194. auto inputs = input_data.blobs;
  1195. auto outputs = output_data.blobs;
  1196. Status status = hybrid_davinci_model->Execute(inputs, input_desc, outputs, output_desc, stream);
  1197. if (status == SUCCESS) {
  1198. GELOGI("Execute model %u success.", model_id);
  1199. }
  1200. return status;
  1201. }
  1202. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1203. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1204. "Invalid model id %u, check whether model has been loaded or not.", model_id);
  1205. if (davinci_model->NeedDestroyAicpuKernel()) {
  1206. GELOGI("Start to destroy specified aicpu kernel.");
  1207. // Zero copy is enabled by default, no need to judge.
  1208. uint64_t session_id_davinci = davinci_model->GetSessionId();
  1209. uint32_t model_id_davinci = davinci_model->GetModelId();
  1210. uint32_t sub_model_id = davinci_model->SubModelId();
  1211. Status status = DestroyAicpuKernel(session_id_davinci, model_id_davinci, sub_model_id);
  1212. if (status != SUCCESS) {
  1213. GELOGW("Destroy specified aicpu kernel failed, session id is %lu, model id is %u.", session_id_davinci,
  1214. model_id_davinci);
  1215. }
  1216. }
  1217. Status status = davinci_model->NnExecute(stream, async_mode, input_data, output_data);
  1218. if (status == SUCCESS) {
  1219. GELOGD("Execute model %u success.", model_id);
  1220. }
  1221. return status;
  1222. }
  1223. Status ModelManager::CreateAicpuSession(uint64_t session_id) {
  1224. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  1225. auto it = sess_ids_.find(session_id);
  1226. // never been created by any model
  1227. if (it == sess_ids_.end()) {
  1228. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_CREATE, session_id, 0, 0);
  1229. if (ret == SUCCESS) {
  1230. (void)sess_ids_.insert(session_id);
  1231. GELOGI("The session: %lu create success.", session_id);
  1232. }
  1233. return ret;
  1234. }
  1235. return SUCCESS;
  1236. }
  1237. Status ModelManager::LoadCustAicpuSo(const OpDescPtr &op_desc, const string &so_name, bool &loaded) {
  1238. GELOGD("LoadCustAicpuSo in, op name %s, so name %s", op_desc->GetName().c_str(), so_name.c_str());
  1239. std::lock_guard<std::mutex> lock(cust_aicpu_mutex_);
  1240. CustAICPUKernelPtr aicpu_kernel = op_desc->TryGetExtAttr(OP_EXTATTR_CUSTAICPU_KERNEL, CustAICPUKernelPtr());
  1241. if (aicpu_kernel == nullptr) {
  1242. GELOGI("cust aicpu op %s has no corresponding kernel!", op_desc->GetName().c_str());
  1243. return SUCCESS;
  1244. }
  1245. // get current context
  1246. rtContext_t rt_cur_ctx = nullptr;
  1247. auto rt_error = rtCtxGetCurrent(&rt_cur_ctx);
  1248. if (rt_error != RT_ERROR_NONE) {
  1249. REPORT_CALL_ERROR("E19999", "Call rtCtxGetCurrent failed, ret = 0x%X",
  1250. rt_error);
  1251. GELOGE(RT_FAILED, "get current context failed, runtime result is %d", static_cast<int>(rt_error));
  1252. return RT_FAILED;
  1253. }
  1254. // use current context as resource key
  1255. uintptr_t resource_id = reinterpret_cast<uintptr_t>(rt_cur_ctx);
  1256. auto it = cust_aicpu_so_.find(resource_id);
  1257. if (it == cust_aicpu_so_.end()) {
  1258. std::map<string, CustAICPUKernelPtr> new_so_name;
  1259. new_so_name.insert({so_name, aicpu_kernel});
  1260. cust_aicpu_so_[resource_id] = new_so_name;
  1261. loaded = false;
  1262. GELOGD("LoadCustAicpuSo new aicpu so name %s, resource id %lu", so_name.c_str(), resource_id);
  1263. return SUCCESS;
  1264. }
  1265. auto it_so_name = it->second.find(so_name);
  1266. if (it_so_name == it->second.end()) {
  1267. it->second.insert({so_name, aicpu_kernel});
  1268. loaded = false;
  1269. GELOGD("LoadCustAicpuSo add aicpu so name %s, resource id %lu", so_name.c_str(), resource_id);
  1270. return SUCCESS;
  1271. }
  1272. loaded = true;
  1273. GELOGD("LoadCustAicpuSo so name %s has been loaded.", so_name.c_str());
  1274. return SUCCESS;
  1275. }
  1276. Status ModelManager::LaunchKernelCustAicpuSo(const string &kernel_name) {
  1277. GELOGD("Aicpu kernel launch task in, kernel name %s.", kernel_name.c_str());
  1278. std::lock_guard<std::mutex> lock(cust_aicpu_mutex_);
  1279. if (cust_aicpu_so_.size() == 0) return SUCCESS;
  1280. // get current context
  1281. rtContext_t rt_cur_ctx = nullptr;
  1282. auto rt_error = rtCtxGetCurrent(&rt_cur_ctx);
  1283. if (rt_error != RT_ERROR_NONE) {
  1284. REPORT_CALL_ERROR("E19999", "Call rtCtxGetCurrent failed, ret = 0x%X",
  1285. rt_error);
  1286. GELOGE(RT_FAILED, "get current context failed, runtime result is %d", static_cast<int>(rt_error));
  1287. return RT_FAILED;
  1288. }
  1289. uintptr_t resource_id = reinterpret_cast<uintptr_t>(rt_cur_ctx);
  1290. auto it = cust_aicpu_so_.find(resource_id);
  1291. if (it == cust_aicpu_so_.end()) {
  1292. GELOGI("Cust aicpu so map is empty, context id %lu", resource_id);
  1293. return SUCCESS;
  1294. }
  1295. vector<void *> allocated_mem;
  1296. rtError_t status;
  1297. rtStream_t stream = nullptr;
  1298. vector<CustAicpuSoBuf> v_cust_so;
  1299. void *args = nullptr;
  1300. for (const auto &it_so : it->second) {
  1301. const void *aicpu_data = it_so.second->GetBinData();
  1302. uint32_t aicpu_data_length = it_so.second->GetBinDataSize();
  1303. string so_name = it_so.first;
  1304. void *d_aicpu_data = nullptr;
  1305. void *d_so_name = nullptr;
  1306. status = rtMalloc(&d_aicpu_data, aicpu_data_length, RT_MEMORY_HBM);
  1307. if (status != RT_ERROR_NONE) {
  1308. REPORT_CALL_ERROR("E19999", "Call rtMalloc failed, size:%u, ret = 0x%X",
  1309. aicpu_data_length, status);
  1310. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1311. return RT_ERROR_TO_GE_STATUS(status);
  1312. }
  1313. allocated_mem.push_back(d_aicpu_data);
  1314. status = rtMalloc(&d_so_name, so_name.size(), RT_MEMORY_HBM);
  1315. if (status != RT_ERROR_NONE) {
  1316. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%zu, ret = 0x%X",
  1317. so_name.size(), status);
  1318. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1319. return RT_ERROR_TO_GE_STATUS(status);
  1320. }
  1321. allocated_mem.push_back(d_so_name);
  1322. GE_CHK_RT(rtMemcpy(d_aicpu_data, aicpu_data_length, aicpu_data, aicpu_data_length, RT_MEMCPY_HOST_TO_DEVICE));
  1323. GE_CHK_RT(rtMemcpy(d_so_name, so_name.size(), reinterpret_cast<const void *>(so_name.c_str()),
  1324. so_name.size(), RT_MEMCPY_HOST_TO_DEVICE));
  1325. CustAicpuSoBuf cust_aicpu_so_buf;
  1326. cust_aicpu_so_buf.kernelSoBuf = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_aicpu_data));
  1327. cust_aicpu_so_buf.kernelSoBufLen = aicpu_data_length;
  1328. cust_aicpu_so_buf.kernelSoName = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_so_name));
  1329. cust_aicpu_so_buf.kernelSoNameLen = so_name.size();
  1330. v_cust_so.push_back(cust_aicpu_so_buf);
  1331. }
  1332. if (kernel_name == kDeleteCustOp) {
  1333. (void)cust_aicpu_so_.erase(it);
  1334. }
  1335. uint32_t args_size = sizeof(CustAicpuSoBuf) * v_cust_so.size();
  1336. status = rtMalloc(&args, args_size, RT_MEMORY_HBM);
  1337. if (status != RT_ERROR_NONE) {
  1338. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%u, ret = 0x%X",
  1339. args_size, status);
  1340. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1341. return RT_ERROR_TO_GE_STATUS(status);
  1342. }
  1343. allocated_mem.push_back(args);
  1344. GE_CHK_RT(rtMemcpy(args, args_size, v_cust_so.data(), args_size, RT_MEMCPY_HOST_TO_DEVICE));
  1345. BatchLoadOpFromBufArgs batch_cust_so;
  1346. batch_cust_so.soNum = v_cust_so.size();
  1347. batch_cust_so.args = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(args));
  1348. void *batch_args = nullptr;
  1349. uint32_t batch_args_size = sizeof(BatchLoadOpFromBufArgs);
  1350. status = rtMalloc(&batch_args, batch_args_size, RT_MEMORY_HBM);
  1351. if (status != RT_ERROR_NONE) {
  1352. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%u, ret = 0x%X",
  1353. batch_args_size, status);
  1354. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1355. return RT_ERROR_TO_GE_STATUS(status);
  1356. }
  1357. allocated_mem.push_back(batch_args);
  1358. GE_CHK_RT(rtMemcpy(batch_args, batch_args_size, static_cast<void *>(&batch_cust_so),
  1359. batch_args_size, RT_MEMCPY_HOST_TO_DEVICE));
  1360. GE_CHK_RT(rtStreamCreate(&stream, 0));
  1361. GE_CHK_RT(rtCpuKernelLaunch(nullptr, kernel_name.c_str(), 1, batch_args, batch_args_size, nullptr, stream));
  1362. status = rtStreamSynchronize(stream);
  1363. if (status != RT_ERROR_NONE) {
  1364. REPORT_CALL_ERROR("E19999", "Call rtStreamSynchronize fail, ret = 0x%X",
  1365. status);
  1366. GELOGE(RT_FAILED, "Call rt stream sync failed, status: 0x%x", status);
  1367. return RT_ERROR_TO_GE_STATUS(status);
  1368. }
  1369. std::function<void()> callback = [&]() {
  1370. for (auto mem : allocated_mem) {
  1371. GE_CHK_RT(rtFree(mem));
  1372. }
  1373. GE_CHK_RT(rtStreamDestroy(stream));
  1374. };
  1375. GE_MAKE_GUARD(release, callback);
  1376. GELOGI("Cpu kernel launch task success.");
  1377. return SUCCESS;
  1378. }
  1379. Status ModelManager::ClearAicpuSo() {
  1380. GE_CHK_STATUS_RET(LaunchKernelCustAicpuSo(kDeleteCustOp), "delete cust op so failed.");
  1381. return SUCCESS;
  1382. }
  1383. Status ModelManager::LaunchCustAicpuSo() {
  1384. GE_CHK_STATUS_RET(LaunchKernelCustAicpuSo(kBatchLoadBuf), "launch cust op so failed.");
  1385. return SUCCESS;
  1386. }
  1387. ///
  1388. /// @ingroup ge
  1389. /// @brief get model memory size and weight
  1390. /// @param [in] const ModelData model: model type
  1391. /// @param [out] size_t memSize: model memory usage
  1392. /// size_t weightSize: model weight and memory size
  1393. /// @return SUCCESS success / others failure
  1394. ///
  1395. Status ModelManager::GetModelMemAndWeightSize(const ModelData &model, size_t &mem_size, size_t &weight_size) {
  1396. uint8_t *model_data = nullptr;
  1397. uint32_t model_len = 0;
  1398. Status ret = ModelParserBase::ParseModelContent(model, model_data, model_len);
  1399. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ACL_ERROR_GE_PARAM_INVALID, "parse model content failed!");
  1400. OmFileLoadHelper om_file_helper;
  1401. ret = om_file_helper.Init(model_data, model_len);
  1402. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "om file helperInit failed!");
  1403. auto partition_table = reinterpret_cast<ModelPartitionTable *>(model_data);
  1404. if (partition_table->num == 1) {
  1405. REPORT_INNER_ERROR("E19999", "partition_table num in model_data is 1, check invalid");
  1406. GELOGE(ACL_ERROR_GE_PARAM_INVALID, "om model is error,please use executable om model");
  1407. return ACL_ERROR_GE_PARAM_INVALID;
  1408. }
  1409. ModelPartition task_partition;
  1410. if (om_file_helper.GetModelPartition(ModelPartitionType::TASK_INFO, task_partition) != SUCCESS) {
  1411. GELOGE(ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED, "get task model partition failed.");
  1412. return ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED;
  1413. }
  1414. std::shared_ptr<domi::ModelTaskDef> model_task_def = MakeShared<domi::ModelTaskDef>();
  1415. if (model_task_def == nullptr) {
  1416. return MEMALLOC_FAILED;
  1417. }
  1418. if (task_partition.size != 0) {
  1419. if (!ReadProtoFromArray(task_partition.data, static_cast<int>(task_partition.size), model_task_def.get())) {
  1420. GELOGE(ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED, "ReadProtoFromArray failed.");
  1421. return ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED;
  1422. }
  1423. }
  1424. ModelPartition partition_weight;
  1425. ret = om_file_helper.GetModelPartition(ModelPartitionType::WEIGHTS_DATA, partition_weight);
  1426. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ACL_ERROR_GE_EXEC_LOAD_WEIGHT_PARTITION_FAILED,
  1427. "Get weight partition failed. ret = %u", ret);
  1428. mem_size = model_task_def->memory_size();
  1429. weight_size = partition_weight.size;
  1430. return SUCCESS;
  1431. }
  1432. void ModelManager::GenModelId(uint32_t *id) {
  1433. if (id == nullptr) {
  1434. return;
  1435. }
  1436. std::lock_guard<std::recursive_mutex> lock(map_mutex_);
  1437. *id = ++max_model_id_;
  1438. }
  1439. Status ModelManager::GetOrigInputInfo(uint32_t model_id, uint32_t index, OriginInputInfo &orig_input_info) {
  1440. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1441. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1442. "GetOrigInputInfo failed, invalid model_id is %u.",
  1443. model_id);
  1444. return davinci_model->GetOrigInputInfo(index, orig_input_info);
  1445. }
  1446. Status ModelManager::GetAllAippInputOutputDims(uint32_t model_id, uint32_t index,
  1447. std::vector<InputOutputDims> &input_dims,
  1448. std::vector<InputOutputDims> &output_dims) {
  1449. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  1450. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, ACL_ERROR_GE_EXEC_MODEL_ID_INVALID,
  1451. "GetAllAippInputOutputDims failed, invalid model_id is %u.", model_id);
  1452. return davinci_model->GetAllAippInputOutputDims(index, input_dims, output_dims);
  1453. }
  1454. bool ModelManager::IsDynamicShape(uint32_t model_id) {
  1455. auto model = GetHybridModel(model_id);
  1456. return model != nullptr;
  1457. }
  1458. ge::Status ModelManager::SyncExecuteModel(uint32_t model_id, const vector<GeTensor> &inputs,
  1459. vector<GeTensor> &outputs) {
  1460. auto model = GetHybridModel(model_id);
  1461. if (model == nullptr) {
  1462. REPORT_INNER_ERROR("E19999", "partition_table num in model_data is 1, check invalid");
  1463. GELOGE(FAILED, "Hybrid model not found. model id = %u.", model_id);
  1464. return FAILED;
  1465. }
  1466. return model->Execute(inputs, outputs);
  1467. }
  1468. Status ModelManager::GetOpDescInfo(uint32_t device_id, uint32_t stream_id, uint32_t task_id, OpDescInfo &op_desc_info) {
  1469. for (const auto &model : model_map_) {
  1470. auto davinci_model = model.second;
  1471. if (davinci_model->GetDeviceId() == device_id) {
  1472. GELOGI("[Get][OpDescInfo] Start to GetOpDescInfo of device_id: %u in davinci model.", device_id);
  1473. if (davinci_model->GetOpDescInfo(stream_id, task_id, op_desc_info)) {
  1474. GELOGI("[Get][OpDescInfo] Find specific node of stream_id: %u, task_id: %u in davinci model.",
  1475. stream_id, task_id);
  1476. return SUCCESS;
  1477. }
  1478. }
  1479. }
  1480. for (const auto &model : hybrid_model_map_) {
  1481. auto hybrid_model = model.second;
  1482. if (hybrid_model->GetDeviceId() == device_id) {
  1483. GELOGI("[Get][OpDescInfo] Start to GetOpDescInfo of device_id: %u in hybrid model.", device_id);
  1484. if (hybrid_model->GetOpDescInfo(stream_id, task_id, op_desc_info)) {
  1485. GELOGI("[Get][OpDescInfo] Find specific node of stream_id: %u, task_id: %u in hybrid model.",
  1486. stream_id, task_id);
  1487. return SUCCESS;
  1488. }
  1489. }
  1490. }
  1491. return FAILED;
  1492. }
  1493. Status ModelManager::EnableExceptionDump(const std::map<string, string> &options) {
  1494. auto iter = options.find(OPTION_EXEC_ENABLE_EXCEPTION_DUMP);
  1495. if (iter != options.end()) {
  1496. GELOGI("Find option enable_exeception_dump is %s", iter->second.c_str());
  1497. if (iter->second == "1") {
  1498. dump_exception_flag_ = true;
  1499. rtError_t rt_ret = rtSetTaskFailCallback(reinterpret_cast<rtTaskFailCallback>(ExceptionCallback));
  1500. if (rt_ret != RT_ERROR_NONE) {
  1501. REPORT_CALL_ERROR("E19999", "Call rtSetTaskFailCallback fail, ret = 0x%X",
  1502. rt_ret);
  1503. GELOGE(RT_FAILED, "rtSetTaskFailCallback failed");
  1504. return RT_ERROR_TO_GE_STATUS(rt_ret);
  1505. }
  1506. } else {
  1507. GELOGI("Option enable exception dump is %s", iter->second.c_str());
  1508. }
  1509. } else {
  1510. GELOGI("Not find option enable exception dump");
  1511. }
  1512. return SUCCESS;
  1513. }
  1514. Status ModelManager::LaunchKernelCheckAicpuOp(std::vector<std::string> &aicpu_optype_list,
  1515. std::vector<std::string> &aicpu_tf_optype_list) {
  1516. std::string kernel_name = "checkOpType";
  1517. GELOGI("LaunchKernelCheckAicpuOpType in, kernel name %s", kernel_name.c_str());
  1518. std::lock_guard<std::mutex> lock(cust_aicpu_mutex_);
  1519. std::vector<SysOpInfo> req_aicpu_op_info_list;
  1520. std::vector<SysOpInfo> res_aicpu_op_info_list;
  1521. std::vector<ReturnCode> res_ret_code_list;
  1522. if (aicpu_optype_list.empty() && aicpu_tf_optype_list.empty()) {
  1523. GELOGI("No need to check aicpu op type.");
  1524. return SUCCESS;
  1525. }
  1526. vector<void *> allocated_mem;
  1527. rtError_t status;
  1528. rtStream_t stream = nullptr;
  1529. void *args = nullptr;
  1530. void *d_req_op_list = nullptr;
  1531. void *d_res_op_list = nullptr;
  1532. void *d_ret_code_list = nullptr;
  1533. size_t aicpu_op_nums = aicpu_optype_list.size();
  1534. size_t tf_op_nums = aicpu_tf_optype_list.size();
  1535. size_t op_nums = aicpu_op_nums + tf_op_nums;
  1536. std::function<void()> callback = [&]() {
  1537. for (auto mem : allocated_mem) {
  1538. GE_CHK_RT(rtFree(mem));
  1539. }
  1540. };
  1541. GE_MAKE_GUARD(release, callback);
  1542. // malloc sysOpInfoList in SysOpCheckInfo
  1543. status = rtMalloc(&d_req_op_list, op_nums * sizeof(SysOpInfo), RT_MEMORY_HBM);
  1544. if (status != RT_ERROR_NONE) {
  1545. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%zu, ret = 0x%X",
  1546. op_nums * sizeof(SysOpInfo), status);
  1547. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1548. return RT_ERROR_TO_GE_STATUS(status);
  1549. }
  1550. allocated_mem.push_back(d_req_op_list);
  1551. // malloc sysOpInfoList in SysOpCheckResp
  1552. status = rtMalloc(&d_res_op_list, op_nums * sizeof(SysOpInfo), RT_MEMORY_HBM);
  1553. if (status != RT_ERROR_NONE) {
  1554. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%zu, ret = 0x%X",
  1555. op_nums * sizeof(SysOpInfo), status);
  1556. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1557. return RT_ERROR_TO_GE_STATUS(status);
  1558. }
  1559. allocated_mem.push_back(d_res_op_list);
  1560. // malloc returnCodeList in SysOpCheckResp
  1561. status = rtMalloc(&d_ret_code_list, op_nums * sizeof(ReturnCode), RT_MEMORY_HBM);
  1562. if (status != RT_ERROR_NONE) {
  1563. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%zu, ret = 0x%X",
  1564. op_nums * sizeof(ReturnCode), status);
  1565. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1566. return RT_ERROR_TO_GE_STATUS(status);
  1567. }
  1568. allocated_mem.push_back(d_ret_code_list);
  1569. for (const auto &op_type : aicpu_optype_list) {
  1570. SysOpInfo op_info;
  1571. // malloc op_type name in SysOpInfo
  1572. void *d_op_type_name = nullptr;
  1573. status = rtMalloc(&d_op_type_name, op_type.length(), RT_MEMORY_HBM);
  1574. if (status != RT_ERROR_NONE) {
  1575. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%lu, ret = 0x%X",
  1576. op_type.length(), status);
  1577. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1578. return RT_ERROR_TO_GE_STATUS(status);
  1579. }
  1580. allocated_mem.push_back(d_op_type_name);
  1581. GE_CHK_RT(rtMemcpy(d_op_type_name, op_type.length(), op_type.c_str(), op_type.length(), RT_MEMCPY_HOST_TO_DEVICE));
  1582. op_info.opType = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_op_type_name));
  1583. op_info.opLen = op_type.length();
  1584. op_info.kernelsType = CPU_KERNEL;
  1585. req_aicpu_op_info_list.emplace_back(op_info);
  1586. }
  1587. for (const auto &op_type : aicpu_tf_optype_list) {
  1588. SysOpInfo op_info;
  1589. // malloc op_type name in SysOpInfo
  1590. void *d_op_type_name = nullptr;
  1591. status = rtMalloc(&d_op_type_name, op_type.size(), RT_MEMORY_HBM);
  1592. if (status != RT_ERROR_NONE) {
  1593. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%lu, ret = 0x%X",
  1594. op_type.length(), status);
  1595. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1596. return RT_ERROR_TO_GE_STATUS(status);
  1597. }
  1598. allocated_mem.push_back(d_op_type_name);
  1599. GE_CHK_RT(rtMemcpy(d_op_type_name, op_type.size(), op_type.c_str(), op_type.size(), RT_MEMCPY_HOST_TO_DEVICE));
  1600. op_info.opType = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_op_type_name));
  1601. op_info.opLen = op_type.size();
  1602. op_info.kernelsType = TF_KERNEL;
  1603. req_aicpu_op_info_list.emplace_back(op_info);
  1604. }
  1605. GELOGI("Check aicpu op all attr size: %zu, real attr size: %zu.", op_nums, req_aicpu_op_info_list.size());
  1606. GE_CHK_RT(rtMemcpy(d_req_op_list, sizeof(SysOpInfo) * req_aicpu_op_info_list.size(), req_aicpu_op_info_list.data(),
  1607. sizeof(SysOpInfo) * req_aicpu_op_info_list.size(), RT_MEMCPY_HOST_TO_DEVICE));
  1608. SysOpCheckInfo op_check_info_req = { 0 };
  1609. SysOpCheckResp op_check_info_res = { 0 };
  1610. op_check_info_req.opListNum = op_nums;
  1611. op_check_info_req.offSetLen = sizeof(SysOpCheckInfo);
  1612. op_check_info_req.sysOpInfoList = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_req_op_list));
  1613. op_check_info_res.opListNum = 0;
  1614. op_check_info_res.isWithoutJson = 0;
  1615. op_check_info_res.returnCodeList = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_ret_code_list));
  1616. op_check_info_res.sysOpInfoList = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(d_res_op_list));
  1617. uint32_t args_size = sizeof(SysOpCheckInfo) + sizeof(SysOpCheckResp);
  1618. status = rtMalloc(&args, args_size, RT_MEMORY_HBM);
  1619. if (status != RT_ERROR_NONE) {
  1620. REPORT_CALL_ERROR("E19999", "Call rtMalloc fail, size:%u, ret = 0x%X",
  1621. args_size, status);
  1622. GELOGE(RT_FAILED, "Call rt failed, status: 0x%x", status);
  1623. return RT_ERROR_TO_GE_STATUS(status);
  1624. }
  1625. allocated_mem.push_back(args);
  1626. GE_CHK_RT(rtMemcpy(args, sizeof(SysOpCheckInfo), reinterpret_cast<void *>(&op_check_info_req), sizeof(SysOpCheckInfo),
  1627. RT_MEMCPY_HOST_TO_DEVICE));
  1628. GE_CHK_RT(rtMemcpy(
  1629. reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<uint64_t>(reinterpret_cast<uintptr_t>(args)) +
  1630. op_check_info_req.offSetLen)), sizeof(SysOpCheckResp), reinterpret_cast<void *>(&op_check_info_res),
  1631. sizeof(SysOpCheckResp), RT_MEMCPY_HOST_TO_DEVICE));
  1632. GE_CHK_RT(rtStreamCreate(&stream, 0));
  1633. GE_CHK_RT(rtCpuKernelLaunch(nullptr, kernel_name.c_str(), 1, args, args_size, nullptr, stream));
  1634. status = rtStreamSynchronize(stream);
  1635. if (status != RT_ERROR_NONE) {
  1636. REPORT_CALL_ERROR("E19999", "Call rtStreamSynchronize fail, ret = 0x%X",
  1637. status);
  1638. GELOGE(RT_FAILED, "Call rt stream sync failed, status: 0x%x", status);
  1639. GE_CHK_RT(rtStreamDestroy(stream));
  1640. return RT_ERROR_TO_GE_STATUS(status);
  1641. }
  1642. // Check the response
  1643. SysOpCheckResp *d_op_check_info_res =
  1644. reinterpret_cast<SysOpCheckResp *>(reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<uint64_t>(
  1645. reinterpret_cast<uintptr_t>(args)) + op_check_info_req.offSetLen)));
  1646. (void)memset_s(&op_check_info_res, sizeof(SysOpCheckResp), 0, sizeof(SysOpCheckResp));
  1647. GE_CHK_RT(rtMemcpy(&op_check_info_res, sizeof(SysOpCheckResp), d_op_check_info_res, sizeof(SysOpCheckResp),
  1648. RT_MEMCPY_DEVICE_TO_HOST));
  1649. if (op_check_info_res.isWithoutJson) {
  1650. GELOGI("No need to check aicpu in this scenoria.");
  1651. GE_CHK_RT(rtStreamDestroy(stream));
  1652. return SUCCESS;
  1653. }
  1654. uint64_t res_op_nums = op_check_info_res.opListNum;
  1655. GELOGI("Check aicpu type, is without json: %d, res op num: %lu.", op_check_info_res.isWithoutJson, res_op_nums);
  1656. if (res_op_nums != 0) {
  1657. res_ret_code_list.clear();
  1658. res_ret_code_list.resize(res_op_nums);
  1659. res_aicpu_op_info_list.clear();
  1660. res_aicpu_op_info_list.resize(res_op_nums);
  1661. GE_CHK_RT(rtMemcpy(res_ret_code_list.data(), sizeof(ReturnCode) * res_op_nums,
  1662. reinterpret_cast<void *>(static_cast<uintptr_t>(op_check_info_res.returnCodeList)),
  1663. sizeof(ReturnCode) * res_op_nums, RT_MEMCPY_DEVICE_TO_HOST));
  1664. GE_CHK_RT(rtMemcpy(res_aicpu_op_info_list.data(), sizeof(SysOpInfo) * res_op_nums,
  1665. reinterpret_cast<void *>(static_cast<uintptr_t>(op_check_info_res.sysOpInfoList)),
  1666. sizeof(SysOpInfo) * res_op_nums, RT_MEMCPY_DEVICE_TO_HOST));
  1667. if (res_ret_code_list.size() != res_aicpu_op_info_list.size() || res_ret_code_list.size() != res_op_nums) {
  1668. REPORT_INNER_ERROR("E19999", "res_ret_code_list.size:%zu res_aicpu_op_info_list.size:%zu res_op_nums:%lu "
  1669. "not equal, check invalid",
  1670. res_ret_code_list.size(), res_aicpu_op_info_list.size(), res_op_nums);
  1671. GELOGE(FAILED, "Number of retcode is not equal to number of op type.");
  1672. GE_CHK_RT(rtStreamDestroy(stream));
  1673. return FAILED;
  1674. }
  1675. std::string fail_reason;
  1676. for (uint32_t i = 0; i < res_op_nums; i++) {
  1677. ReturnCode ret_code = res_ret_code_list.at(i);
  1678. SysOpInfo aicpu_info = res_aicpu_op_info_list.at(i);
  1679. GELOGI("Not support aicpu op type: %lu, kernel_type:%d, opLen:%lu, ret_code:%d", aicpu_info.opType,
  1680. aicpu_info.kernelsType, aicpu_info.opLen, ret_code);
  1681. std::vector<char> op_name;
  1682. op_name.clear();
  1683. op_name.resize(kOpNameMaxSize);
  1684. GE_CHK_RT(rtMemcpy(op_name.data(), aicpu_info.opLen, reinterpret_cast<void *>(aicpu_info.opType),
  1685. aicpu_info.opLen, RT_MEMCPY_DEVICE_TO_HOST));
  1686. std::string kernel_type =
  1687. (static_cast<OpKernelType>(aicpu_info.kernelsType) == TF_KERNEL) ? "TF_KERNEL" : "CPU_KERNEL";
  1688. string op_name_str(op_name.data());
  1689. fail_reason += "op_type: " + op_name_str + " kernel_type: " + kernel_type +
  1690. " ret code:" + std::to_string(static_cast<int>(ret_code)) +
  1691. "<0: op_type, 1: format, 2: datatype> \n";
  1692. }
  1693. fail_reason += "not support.";
  1694. REPORT_INNER_ERROR("E19999", "Check aicpu op_type failed, details:%s",
  1695. fail_reason.c_str());
  1696. GELOGE(FAILED, "Check aicpu op_type failed. details: %s", fail_reason.c_str());
  1697. GE_CHK_RT(rtStreamDestroy(stream));
  1698. return FAILED;
  1699. }
  1700. GE_CHK_RT(rtStreamDestroy(stream));
  1701. GELOGI("Cpu kernel launch check optype task success.");
  1702. return SUCCESS;
  1703. }
  1704. Status ModelManager::CheckAicpuOpList(GeModelPtr ge_model) {
  1705. std::vector<std::string> aicpu_optype_list;
  1706. std::vector<std::string> aicpu_tf_optype_list;
  1707. bool aicpu_need_check = ge::AttrUtils::GetListStr(ge_model, "needCheckCpu", aicpu_optype_list);
  1708. bool tf_need_check = ge::AttrUtils::GetListStr(ge_model, "needCheckTf", aicpu_tf_optype_list);
  1709. if (!aicpu_need_check && !tf_need_check) {
  1710. GELOGI("Graph:%s No need to check aicpu optype.", ge_model->GetGraph().GetName().c_str());
  1711. return SUCCESS;
  1712. }
  1713. GE_CHK_STATUS_RET(LaunchKernelCheckAicpuOp(aicpu_optype_list, aicpu_tf_optype_list),
  1714. "Launch check aicpu op type failed.");
  1715. return SUCCESS;
  1716. }
  1717. } // namespace ge

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