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

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