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

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