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

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

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