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

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