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

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

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