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

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

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