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 40 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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/l2_cache_optimize.h"
  19. #include "common/profiling/profiling_manager.h"
  20. #include "common/properties_manager.h"
  21. #include "framework/common/debug/ge_log.h"
  22. #include "graph/debug/ge_attr_define.h"
  23. #include "framework/common/util.h"
  24. #include "graph/load/new_model_manager/davinci_model.h"
  25. #include "graph/load/new_model_manager/davinci_model_parser.h"
  26. #include "model/ge_root_model.h"
  27. namespace ge {
  28. thread_local uint32_t device_count = 0;
  29. namespace {
  30. const int kCmdParSize = 2;
  31. const int kDumpCmdPairSize = 2;
  32. const char *const kNeedDestroySpecifiedAicpuKernel = "need_destroy_specified_aicpu_kernel";
  33. } // namespace
  34. std::shared_ptr<ModelManager> ModelManager::GetInstance() {
  35. static const std::shared_ptr<ModelManager> instance_ptr =
  36. shared_ptr<ModelManager>(new (std::nothrow) ModelManager(), ModelManager::FinalizeForPtr);
  37. return instance_ptr;
  38. }
  39. ModelManager::ModelManager() {
  40. max_model_id_ = 0;
  41. session_id_bias_ = 0;
  42. }
  43. Status ModelManager::KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType op_type, uint64_t session_id, uint32_t model_id) {
  44. STR_FWK_OP_KERNEL param_base = {};
  45. void *devicebase = nullptr;
  46. void *aicpu_kernel_addr = nullptr;
  47. const uint32_t kKernelType = 0;
  48. param_base.fwkKernelType = kKernelType;
  49. param_base.fwkKernelBase.fwk_kernel.opType = op_type;
  50. param_base.fwkKernelBase.fwk_kernel.sessionID = session_id;
  51. if (op_type == aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY) {
  52. std::vector<uint64_t> v_aicpu_kernel;
  53. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  54. auto iter = model_aicpu_kernel_.find(model_key);
  55. if (iter != model_aicpu_kernel_.end()) {
  56. GELOGD("kernel destroy session_id %lu, model_id %u.", session_id, model_id);
  57. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  58. // Insert size of aicpu kernel vector in the first element
  59. v_aicpu_kernel.insert(v_aicpu_kernel.begin(), v_aicpu_kernel.size());
  60. auto kernel_size = sizeof(uint64_t) * (v_aicpu_kernel.size());
  61. rtError_t rt_ret = rtMalloc(&aicpu_kernel_addr, kernel_size, RT_MEMORY_HBM);
  62. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(RT_FAILED, "rtMalloc error, ret: 0x%X", rt_ret);
  63. return RT_FAILED;)
  64. rt_ret = rtMemcpy(aicpu_kernel_addr, kernel_size, v_aicpu_kernel.data(), kernel_size, RT_MEMCPY_HOST_TO_DEVICE);
  65. GE_IF_BOOL_EXEC(rt_ret != RT_ERROR_NONE, GELOGE(rt_ret, "rtMemcpy to input_output_addr_ error: 0x%X", rt_ret);
  66. GE_CHK_RT(rtFree(aicpu_kernel_addr)); return FAILED;)
  67. uint64_t kernel_id_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(aicpu_kernel_addr));
  68. param_base.fwkKernelBase.fwk_kernel.kernelID = kernel_id_addr;
  69. // In the scene of loading once and running many times, the kernel needs to be destroyed many times,
  70. // and connot be removed from kernel map.
  71. }
  72. }
  73. rtError_t rt_ret = rtMalloc(&(devicebase), sizeof(STR_FWK_OP_KERNEL), RT_MEMORY_HBM);
  74. if (rt_ret != RT_ERROR_NONE) {
  75. GELOGE(rt_ret, "malloc device memory failed.");
  76. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  77. return FAILED;
  78. }
  79. rt_ret =
  80. rtMemcpy(devicebase, sizeof(STR_FWK_OP_KERNEL), &param_base, sizeof(STR_FWK_OP_KERNEL), RT_MEMCPY_HOST_TO_DEVICE);
  81. if (rt_ret != RT_ERROR_NONE) {
  82. GELOGE(rt_ret, "memory copy to device failed.");
  83. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  84. GE_CHK_RT(rtFree(devicebase));
  85. return FAILED;
  86. }
  87. rtStream_t stream = nullptr;
  88. rt_ret = rtStreamCreate(&stream, 0);
  89. if (rt_ret != RT_ERROR_NONE) {
  90. GELOGE(rt_ret, "create stream failed.");
  91. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  92. GE_CHK_RT(rtFree(devicebase));
  93. return FAILED;
  94. }
  95. rt_ret = rtKernelLaunchEx(devicebase, sizeof(STR_FWK_OP_KERNEL), 0, stream);
  96. if (rt_ret != RT_ERROR_NONE) {
  97. GELOGE(rt_ret, "rtKernelLaunchEx failed.");
  98. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  99. GE_CHK_RT(rtFree(devicebase));
  100. GE_CHK_RT(rtStreamDestroy(stream));
  101. return FAILED;
  102. }
  103. rt_ret = rtStreamSynchronize(stream);
  104. if (rt_ret != RT_ERROR_NONE) {
  105. GELOGE(rt_ret, "rtStreamSynchronize failed.");
  106. GE_IF_BOOL_EXEC(aicpu_kernel_addr != nullptr, GE_CHK_RT(rtFree(aicpu_kernel_addr)));
  107. GE_CHK_RT(rtFree(devicebase));
  108. GE_CHK_RT(rtStreamDestroy(stream));
  109. return FAILED;
  110. }
  111. if (aicpu_kernel_addr != nullptr) {
  112. rt_ret = rtFree(aicpu_kernel_addr);
  113. if (rt_ret != RT_ERROR_NONE) {
  114. GELOGE(rt_ret, "free memory failed.");
  115. GE_CHK_RT(rtFree(devicebase));
  116. GE_CHK_RT(rtStreamDestroy(stream));
  117. return FAILED;
  118. }
  119. }
  120. rt_ret = rtFree(devicebase);
  121. if (rt_ret != RT_ERROR_NONE) {
  122. GELOGE(rt_ret, "free memory failed.");
  123. GE_CHK_RT(rtStreamDestroy(stream));
  124. return FAILED;
  125. }
  126. rt_ret = rtStreamDestroy(stream);
  127. if (rt_ret != RT_ERROR_NONE) {
  128. GELOGE(rt_ret, "rtStreamDestroy failed.");
  129. return FAILED;
  130. }
  131. return SUCCESS;
  132. }
  133. void ModelManager::DestroyAicpuSession(uint64_t session_id) {
  134. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  135. auto it = sess_ids_.find(session_id);
  136. if (it == sess_ids_.end()) {
  137. GELOGI("The session: %lu not created.", session_id);
  138. return;
  139. } else {
  140. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_DESTROY, session_id, 0);
  141. if (ret != SUCCESS) {
  142. GELOGW("The session: %lu destroy failed.", session_id);
  143. } else {
  144. (void)sess_ids_.erase(session_id);
  145. GELOGI("The session: %lu destroyed.", session_id);
  146. }
  147. }
  148. }
  149. ge::Status ModelManager::DestroyAicpuSessionForInfer(uint32_t model_id) {
  150. GELOGI("Destroy aicpu session for infer, model id is %u.", model_id);
  151. std::lock_guard<std::mutex> lock(map_mutex_);
  152. auto it = model_map_.find(model_id);
  153. if (it == model_map_.end()) {
  154. GELOGE(PARAM_INVALID, "model id %u does not exists.", model_id);
  155. return PARAM_INVALID;
  156. }
  157. uint64_t session_id = it->second->GetSessionId();
  158. GELOGI("Destroy aicpu session for infer, session id is %u.", session_id);
  159. DestroyAicpuSession(session_id);
  160. return SUCCESS;
  161. }
  162. ge::Status ModelManager::DestroyAicpuKernel(uint64_t session_id, uint32_t model_id) {
  163. GELOGD("destroy aicpu kernel in session_id %lu, model_id %u.", session_id, model_id);
  164. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  165. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  166. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  167. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_KERNEL_DESTROY, session_id, model_id);
  168. if (ret != SUCCESS) {
  169. GELOGE(FAILED, "Destroy aicpu kernel failed.");
  170. return FAILED;
  171. }
  172. }
  173. return SUCCESS;
  174. }
  175. ge::Status ModelManager::CreateAicpuKernel(uint64_t session_id, uint32_t model_id, uint64_t kernel_id) {
  176. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  177. std::vector<uint64_t> v_aicpu_kernel;
  178. std::string model_key = std::to_string(session_id) + "_" + std::to_string(model_id);
  179. if (model_aicpu_kernel_.find(model_key) != model_aicpu_kernel_.end()) {
  180. v_aicpu_kernel = model_aicpu_kernel_.at(model_key);
  181. }
  182. v_aicpu_kernel.push_back(kernel_id);
  183. model_aicpu_kernel_[model_key] = v_aicpu_kernel;
  184. return SUCCESS;
  185. }
  186. ModelManager::~ModelManager() {
  187. std::lock_guard<std::mutex> lock(map_mutex_);
  188. model_map_.clear();
  189. model_aicpu_kernel_.clear();
  190. GE_IF_BOOL_EXEC(device_count > 0, GE_CHK_RT(rtDeviceReset(0)));
  191. }
  192. ///
  193. /// @ingroup domi_ome
  194. /// @brief set Device. If no device available, return failure
  195. /// @return Status run result
  196. /// @author
  197. ///
  198. Status ModelManager::SetDevice(int32_t deviceId) const {
  199. GE_CHK_RT_RET(rtSetDevice(deviceId));
  200. return SUCCESS;
  201. }
  202. ge::Status ModelManager::SetDynamicSize(uint32_t model_id, const std::vector<uint64_t> &batch_num) {
  203. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  204. GE_CHECK_NOTNULL(davinci_model);
  205. davinci_model->SetDynamicSize(batch_num);
  206. return SUCCESS;
  207. }
  208. ge::Status ModelManager::DoLoadHybridModelOnline(uint32_t model_id, const shared_ptr<ge::GeRootModel> &ge_root_model,
  209. const shared_ptr<ModelListener> &listener) {
  210. auto hybrid_model = hybrid::HybridDavinciModel::Create(ge_root_model);
  211. GE_CHECK_NOTNULL(hybrid_model);
  212. hybrid_model->SetListener(listener);
  213. hybrid_model->SetModelId(model_id);
  214. hybrid_model->SetDeviceId(GetContext().DeviceId());
  215. GE_CHK_STATUS_RET(hybrid_model->Init(), "Failed to init hybrid model. model_id = %u", model_id);
  216. auto shared_model = std::shared_ptr<hybrid::HybridDavinciModel>(hybrid_model.release());
  217. InsertModel(model_id, shared_model);
  218. return SUCCESS;
  219. }
  220. ///
  221. /// @ingroup domi_ome
  222. /// @brief load model online
  223. /// @return Status run result
  224. ///
  225. Status ModelManager::LoadModelOnline(uint32_t &model_id, const shared_ptr<ge::GeRootModel> &ge_root_model,
  226. std::shared_ptr<ModelListener> listener) {
  227. GE_CHK_BOOL_RET_STATUS(listener.get() != nullptr, PARAM_INVALID, "Param incorrect, listener is null");
  228. if (model_id == INVALID_MODEL_ID) {
  229. GenModelId(&model_id);
  230. }
  231. bool is_shape_unknown = false;
  232. GE_CHK_STATUS_RET(ge_root_model->CheckIsUnknownShape(is_shape_unknown), "CheckIsUnknownShape failed, model id:%u",
  233. model_id);
  234. if (is_shape_unknown) {
  235. return DoLoadHybridModelOnline(model_id, ge_root_model, listener);
  236. }
  237. GE_CHK_STATUS_RET(SetDevice(static_cast<int32_t>(GetContext().DeviceId())), "Set device failed, model id:%u.",
  238. model_id);
  239. mmTimespec timespec = mmGetTickCount();
  240. std::shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(0, listener);
  241. if (davinci_model == nullptr) {
  242. GELOGE(FAILED, "davinci_model is nullptr");
  243. return FAILED;
  244. }
  245. davinci_model->SetId(model_id);
  246. davinci_model->SetDeviceId(GetContext().DeviceId());
  247. auto root_graph = ge_root_model->GetRootGraph();
  248. GE_CHECK_NOTNULL(root_graph);
  249. string root_model_name = root_graph->GetName();
  250. auto name_to_model = ge_root_model->GetSubgraphInstanceNameToModel();
  251. GeModelPtr ge_model = name_to_model[root_model_name];
  252. Status ret = SUCCESS;
  253. do {
  254. GE_TIMESTAMP_START(Assign);
  255. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Assign(ge_model)), GELOGW("assign model to modeldef failed.");
  256. break;);
  257. GE_TIMESTAMP_END(Assign, "GraphLoader::ModelAssign");
  258. GE_TIMESTAMP_START(Init);
  259. GE_IF_BOOL_EXEC(SUCCESS != (ret = davinci_model->Init()), GELOGW("DavinciInit failed."); break;);
  260. GE_TIMESTAMP_END(Init, "GraphLoader::ModelInit");
  261. InsertModel(model_id, davinci_model);
  262. GELOGI("Parse model %u success.", model_id);
  263. if (ProfilingManager::Instance().ProfilingOn()) {
  264. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * 1000 * 1000 * 1000 +
  265. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  266. davinci_model->SetProfileTime(MODEL_LOAD_END);
  267. if (davinci_model->SinkModelProfile() != SUCCESS) {
  268. GELOGW("Sink model profile failed.");
  269. }
  270. }
  271. } while (0);
  272. GE_CHK_RT(rtDeviceReset(static_cast<int32_t>(GetContext().DeviceId())));
  273. return ret;
  274. }
  275. void ModelManager::InsertModel(uint32_t id, std::shared_ptr<DavinciModel> &davinci_model) {
  276. GE_CHK_BOOL_EXEC(davinci_model != nullptr, return, "davinci_model ptr is null, id: %u", id);
  277. std::lock_guard<std::mutex> lock(map_mutex_);
  278. model_map_[id] = davinci_model;
  279. }
  280. void ModelManager::InsertModel(uint32_t id, shared_ptr<hybrid::HybridDavinciModel> &hybrid_model) {
  281. GE_CHK_BOOL_EXEC(hybrid_model != nullptr, return, "hybrid_model ptr is null, id: %u", id);
  282. std::lock_guard<std::mutex> lock(map_mutex_);
  283. hybrid_model_map_[id] = hybrid_model;
  284. }
  285. Status ModelManager::DeleteModel(uint32_t id) {
  286. std::lock_guard<std::mutex> lock(map_mutex_);
  287. auto it = model_map_.find(id);
  288. auto hybrid_model_it = hybrid_model_map_.find(id);
  289. if (it != model_map_.end()) {
  290. uint64_t session_id = it->second->GetSessionId();
  291. std::string model_key = std::to_string(session_id) + "_" + std::to_string(id);
  292. auto iter_aicpu_kernel = model_aicpu_kernel_.find(model_key);
  293. if (iter_aicpu_kernel != model_aicpu_kernel_.end()) {
  294. (void)model_aicpu_kernel_.erase(iter_aicpu_kernel);
  295. }
  296. (void)model_map_.erase(it);
  297. } else if (hybrid_model_it != hybrid_model_map_.end()) {
  298. (void)hybrid_model_map_.erase(hybrid_model_it);
  299. } else {
  300. GELOGE(PARAM_INVALID, "model id %u does not exists.", id);
  301. return PARAM_INVALID;
  302. }
  303. return SUCCESS;
  304. }
  305. std::shared_ptr<DavinciModel> ModelManager::GetModel(uint32_t id) {
  306. std::lock_guard<std::mutex> lock(map_mutex_);
  307. auto it = model_map_.find(id);
  308. return (it == model_map_.end()) ? nullptr : it->second;
  309. }
  310. std::shared_ptr<hybrid::HybridDavinciModel> ModelManager::GetHybridModel(uint32_t id) {
  311. std::lock_guard<std::mutex> lock(map_mutex_);
  312. auto it = hybrid_model_map_.find(id);
  313. return (it == hybrid_model_map_.end()) ? nullptr : it->second;
  314. }
  315. Status ModelManager::Unload(uint32_t model_id) {
  316. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload model id: %u", model_id);
  317. if (device_count > 0) {
  318. device_count--;
  319. GELOGI("Unload model %u success.", model_id);
  320. } else {
  321. GELOGI("Unload model %u success.no need reset device,device_count: %u", model_id, device_count);
  322. }
  323. return SUCCESS;
  324. }
  325. Status ModelManager::UnloadModeldef(uint32_t model_id) {
  326. GE_CHK_STATUS_RET(DeleteModel(model_id), "failed to unload modeldef id: %u", model_id);
  327. return SUCCESS;
  328. }
  329. Status ModelManager::DataInput(const InputData &input_data, OutputData &output_data) {
  330. GELOGI("calling the DataInput");
  331. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  332. GE_CHECK_NOTNULL(data_wrap);
  333. Status status = data_wrap->Init(input_data, output_data);
  334. if (status != SUCCESS) {
  335. GELOGE(domi::PUSH_DATA_FAILED, "Init InputDataWrapper failed, input data index: %u.", input_data.index);
  336. return domi::PUSH_DATA_FAILED;
  337. }
  338. uint32_t model_id = input_data.model_id;
  339. output_data.model_id = model_id;
  340. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  341. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid Model ID %u in InputData! ", model_id);
  342. GE_IF_BOOL_EXEC(model->GetDataInputTid() == 0, model->SetDataInputTid(mmGetTid()));
  343. DataInputer *inputer = model->GetDataInputer();
  344. GE_CHECK_NOTNULL(inputer);
  345. if (inputer->Push(data_wrap) != SUCCESS) {
  346. GELOGE(domi::DATA_QUEUE_ISFULL, "Data queue is full, please call again later, model_id %u ", model_id);
  347. return domi::DATA_QUEUE_ISFULL;
  348. }
  349. GELOGD("Data input success, model id:%u", model_id);
  350. return SUCCESS;
  351. }
  352. ///
  353. /// @ingroup domi_ome
  354. /// @brief load Input and output TensorInfo for Model
  355. /// @return Status run result
  356. ///
  357. Status ModelManager::DataInputTensor(uint32_t model_id, const std::vector<InputTensorInfo> &inputs) {
  358. std::shared_ptr<DavinciModel> model = GetModel(model_id);
  359. auto hybrid_model = GetHybridModel(model_id);
  360. if (hybrid_model == nullptr) {
  361. GE_CHECK_NOTNULL(model);
  362. }
  363. InputData input_data;
  364. input_data.model_id = model_id;
  365. input_data.timeout = 0;
  366. input_data.timestamp = 0;
  367. input_data.index = 0;
  368. for (size_t i = 0; i < inputs.size(); ++i) {
  369. DataBuffer data;
  370. data.data = inputs[i].data;
  371. data.length = static_cast<uint32_t>(inputs[i].length);
  372. input_data.blobs.push_back(data);
  373. }
  374. OutputData output_data;
  375. output_data.model_id = model_id;
  376. output_data.index = 0;
  377. shared_ptr<InputDataWrapper> data_wrap(new (std::nothrow) InputDataWrapper());
  378. GE_CHECK_NOTNULL(data_wrap);
  379. GE_CHK_STATUS_EXEC(data_wrap->Init(input_data, output_data), return domi::PUSH_DATA_FAILED,
  380. "Init InputDataWrapper failed,input data model_id is : %u.", model_id);
  381. if (hybrid_model != nullptr) {
  382. GE_CHK_STATUS_RET(hybrid_model->EnqueueData(data_wrap), "Data queue is full, please call again later, model_id %u ",
  383. model_id);
  384. return SUCCESS;
  385. }
  386. GE_CHK_BOOL_RET_STATUS(model != nullptr, PARAM_INVALID, "Invalid Model ID %u in InputData! ", model_id);
  387. DataInputer *inputer = model->GetDataInputer();
  388. GE_CHECK_NOTNULL(inputer);
  389. GE_CHK_STATUS_EXEC(inputer->Push(data_wrap), return domi::DATA_QUEUE_ISFULL,
  390. "Data queue is full, please call again later, model_id %u ", model_id);
  391. GELOGD("Data input success, model id:%u", model_id);
  392. return SUCCESS;
  393. }
  394. ///
  395. /// @ingroup domi_ome
  396. /// @brief create model thread, start to execute model
  397. /// @param [in] model_id Model ID to be started
  398. /// @return Status model run result
  399. /// @author
  400. ///
  401. Status ModelManager::Start(uint32_t model_id) {
  402. auto hybrid_model = GetHybridModel(model_id);
  403. if (hybrid_model != nullptr) {
  404. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStart());
  405. GELOGI("Start hybrid model %u success.", model_id);
  406. return SUCCESS;
  407. }
  408. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  409. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to start! ", model_id);
  410. Status status = davinci_model->ModelRunStart();
  411. if (status == SUCCESS) {
  412. GELOGI("Start model %u success.", model_id);
  413. }
  414. return status;
  415. }
  416. ///
  417. /// @ingroup domi_ome
  418. /// @brief Model ID stop
  419. /// @only when unloaded
  420. /// @param [in] model_id Model ID to be stopped
  421. /// @return Status model stop result
  422. /// @author
  423. ///
  424. Status ModelManager::Stop(uint32_t model_id) {
  425. auto hybrid_model = GetHybridModel(model_id);
  426. if (hybrid_model != nullptr) {
  427. GE_CHK_STATUS_RET_NOLOG(hybrid_model->ModelRunStop());
  428. GELOGI("Stop hybrid model %u success.", model_id);
  429. return SUCCESS;
  430. }
  431. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  432. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to stop!", model_id);
  433. Status status = davinci_model->ModelRunStop();
  434. if (status == SUCCESS) {
  435. GELOGI("Stop model %u success.", model_id);
  436. }
  437. return status;
  438. }
  439. ///
  440. /// @ingroup domi_ome
  441. /// @brief Command handle
  442. /// @iterator 1 only Ieference, Debug 2 modes
  443. /// @param [in] command command to handle
  444. /// @return Status command handle result
  445. /// @author
  446. ///
  447. Status ModelManager::HandleCommand(const Command &command) {
  448. static const std::map<std::string, std::function<uint32_t(const Command &)>> cmds = {
  449. {"profile", HandleProfileCommand}, {"dump", HandleDumpCommand}, {"profiling", HandleAclProfilingCommand}};
  450. auto iter = cmds.find(command.cmd_type);
  451. if (iter == cmds.end()) {
  452. GELOGE(PARAM_INVALID, "Unsupported command: %s", command.cmd_type.c_str());
  453. return PARAM_INVALID;
  454. } else {
  455. return iter->second(command);
  456. }
  457. }
  458. Status ModelManager::HandleAclProfilingCommand(const Command &command) {
  459. if (command.cmd_params.size() < kCmdParSize) {
  460. GELOGE(PARAM_INVALID, "When the cmd_type is 'profiling', the size of cmd_params must larger than 2.");
  461. return PARAM_INVALID;
  462. }
  463. std::string map_key = command.cmd_params[0];
  464. std::string value = command.cmd_params[1];
  465. if (map_key == PROFILE_CONFIG) {
  466. ProfilingManager::Instance().SetProfilingConfig(value);
  467. }
  468. return SUCCESS;
  469. }
  470. Status ModelManager::HandleProfileCommand(const Command &command) {
  471. if (command.cmd_params.size() < kCmdParSize) {
  472. GELOGE(PARAM_INVALID, "When the cmd_type is 'profile', the size of cmd_params must larger than 2.");
  473. return PARAM_INVALID;
  474. }
  475. std::string map_key = command.cmd_params[0];
  476. std::string value = command.cmd_params[1];
  477. GELOGI("Profiling mode, Command key:%s , value:%s ", map_key.c_str(), value.c_str());
  478. auto iter = PROFILE_COMPONENT_MAP.find(map_key);
  479. if (iter != PROFILE_COMPONENT_MAP.end()) {
  480. std::string property_value = (value == "on") ? "1" : "0";
  481. PropertiesManager::Instance().SetPropertyValue(iter->second, property_value);
  482. }
  483. if ((map_key == PROFILER_JOBCTX || map_key == PROFILER_TARGET_PATH || map_key == RTS_PROFILE_PATH)) {
  484. PropertiesManager::Instance().SetPropertyValue(map_key, value);
  485. }
  486. if ((map_key == PROFILE_STOP_KEY) && (value == PROFILE_STOP_VALUE)) {
  487. rtError_t rt_ret = rtProfilerStop();
  488. if (rt_ret != RT_ERROR_NONE) {
  489. GELOGE(PARAM_INVALID, "Call rtProfilerStop ret:%d", rt_ret);
  490. return PARAM_INVALID;
  491. }
  492. }
  493. return SUCCESS;
  494. }
  495. static Status ParserPara(const Command &command, const string &dump_key, string &dump_value) {
  496. auto iter = std::find(command.cmd_params.begin(), command.cmd_params.end(), dump_key);
  497. if (iter != command.cmd_params.end()) {
  498. ++iter;
  499. if (iter == command.cmd_params.end()) {
  500. GELOGE(PARAM_INVALID, "Invalid access.");
  501. return PARAM_INVALID;
  502. }
  503. dump_value = *iter;
  504. }
  505. return SUCCESS;
  506. }
  507. Status ModelManager::HandleDumpCommand(const Command &command) {
  508. if (command.cmd_params.size() % kDumpCmdPairSize != 0) {
  509. GELOGE(PARAM_INVALID, "When the cmd_type is 'dump', the size of cmd_params must be a even number.");
  510. return PARAM_INVALID;
  511. }
  512. std::string dump_status("off");
  513. std::string dump_model(DUMP_ALL_MODEL);
  514. std::string dump_path("/");
  515. std::string dump_mode("output");
  516. std::set<std::string> dump_layers;
  517. auto ret = ParserPara(command, DUMP_STATUS, dump_status);
  518. if (ret != SUCCESS) {
  519. GELOGE(PARAM_INVALID, "parser dump status failed");
  520. return FAILED;
  521. }
  522. GELOGI("dump status = %s.", dump_status.c_str());
  523. ret = ParserPara(command, DUMP_MODEL, dump_model);
  524. if (ret != SUCCESS) {
  525. GELOGE(PARAM_INVALID, "parser dump model failed");
  526. return FAILED;
  527. }
  528. GELOGI("dump status = %s.", dump_model.c_str());
  529. if (dump_status == "off" || dump_status == "OFF") {
  530. PropertiesManager::Instance().DeleteDumpPropertyValue(dump_model);
  531. return SUCCESS;
  532. }
  533. for (size_t i = 0; i < command.cmd_params.size() / kDumpCmdPairSize; ++i) {
  534. if (command.cmd_params.at(i * kDumpCmdPairSize).find(DUMP_LAYER) != std::string::npos) {
  535. GELOGI("dump layer: %s.", command.cmd_params.at(i * kDumpCmdPairSize + 1).c_str());
  536. dump_layers.insert(command.cmd_params.at(i * kDumpCmdPairSize + 1));
  537. }
  538. }
  539. ret = ParserPara(command, DUMP_FILE_PATH, dump_path);
  540. if (ret != SUCCESS) {
  541. GELOGE(PARAM_INVALID, "parser dump path failed");
  542. return FAILED;
  543. }
  544. if (!dump_path.empty() && dump_path[dump_path.size() - 1] != '/') {
  545. dump_path = dump_path + "/" + CurrentTimeInStr() + "/";
  546. }
  547. GELOGI("dump status = %s.", dump_path.c_str());
  548. ret = ParserPara(command, DUMP_MODE, dump_mode);
  549. if (ret != SUCCESS) {
  550. GELOGE(PARAM_INVALID, "parser dump mode failed");
  551. return FAILED;
  552. }
  553. GELOGI("dump mode = %s", dump_mode.c_str());
  554. auto iter_dump_mode = std::find(command.cmd_params.begin(), command.cmd_params.end(), DUMP_MODE);
  555. if (iter_dump_mode != command.cmd_params.end()) {
  556. ++iter_dump_mode;
  557. if (iter_dump_mode == command.cmd_params.end()) {
  558. GELOGE(PARAM_INVALID, "Invalid access.");
  559. return PARAM_INVALID;
  560. }
  561. dump_mode = *iter_dump_mode;
  562. GELOGI("dump mode = %s", dump_mode.c_str());
  563. }
  564. PropertiesManager::Instance().AddDumpPropertyValue(dump_model, dump_layers);
  565. PropertiesManager::Instance().SetDumpOutputPath(dump_path);
  566. PropertiesManager::Instance().SetDumpMode(dump_mode);
  567. return SUCCESS;
  568. }
  569. Status ModelManager::GetMaxUsedMemory(const uint32_t model_id, uint64_t &max_size) {
  570. auto hybrid_model = GetHybridModel(model_id);
  571. if (hybrid_model != nullptr) {
  572. max_size = 0;
  573. return SUCCESS;
  574. }
  575. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  576. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetMaxUsedMemory Failed, Invalid Model ID %u !",
  577. model_id);
  578. max_size = davinci_model->TotalMemSize();
  579. return SUCCESS;
  580. }
  581. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  582. vector<InputOutputDescInfo> &output_desc) {
  583. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  584. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID,
  585. "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id);
  586. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc);
  587. }
  588. Status ModelManager::GetInputOutputDescInfo(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  589. vector<InputOutputDescInfo> &output_desc,
  590. std::vector<uint32_t> &inputFormats, std::vector<uint32_t> &outputFormats,
  591. bool new_model_desc) {
  592. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  593. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID,
  594. "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id);
  595. davinci_model->SetModelDescVersion(new_model_desc);
  596. return davinci_model->GetInputOutputDescInfo(input_desc, output_desc, inputFormats, outputFormats);
  597. }
  598. ///
  599. /// @ingroup ge
  600. /// @brief Get dynamic batch_info
  601. /// @param [in] model_id
  602. /// @param [out] batch_info
  603. /// @return execute result
  604. ///
  605. Status ModelManager::GetDynamicBatchInfo(const uint32_t model_id, std::vector<std::vector<int64_t>> &batch_info) {
  606. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  607. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetDynamicBatchInfo Failed, Invalid Model ID %u !",
  608. model_id);
  609. return davinci_model->GetDynamicBatchInfo(batch_info);
  610. }
  611. Status ModelManager::GetCurShape(const uint32_t model_id, std::vector<int64_t> &batch_info) {
  612. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  613. GE_CHECK_NOTNULL(davinci_model);
  614. davinci_model->GetCurShape(batch_info);
  615. return SUCCESS;
  616. }
  617. Status ModelManager::GetModelAttr(uint32_t model_id, std::vector<string> &dynamic_output_shape_info) {
  618. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  619. GE_CHECK_NOTNULL(davinci_model);
  620. davinci_model->GetModelAttr(dynamic_output_shape_info);
  621. return SUCCESS;
  622. }
  623. Status ModelManager::GetInputOutputDescInfoForZeroCopy(const uint32_t model_id, vector<InputOutputDescInfo> &input_desc,
  624. vector<InputOutputDescInfo> &output_desc,
  625. std::vector<uint32_t> &inputFormats,
  626. std::vector<uint32_t> &outputFormats) {
  627. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  628. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID,
  629. "GetInputOutputDescInfo Failed, Invalid Model ID %u !", model_id);
  630. return davinci_model->GetInputOutputDescInfoForZeroCopy(input_desc, output_desc, inputFormats, outputFormats);
  631. }
  632. ///
  633. /// @ingroup ge
  634. /// @brief Get AIPP info
  635. /// @param [in] model_id
  636. /// @param [in] index
  637. /// @param [out] aipp_info
  638. /// @return execute result
  639. ///
  640. Status ModelManager::GetAIPPInfo(const uint32_t model_id, uint32_t index, AippConfigInfo &aipp_info) {
  641. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  642. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetAIPPInfo failed, invalid model_id is %u.",
  643. model_id);
  644. return davinci_model->GetAIPPInfo(index, aipp_info);
  645. }
  646. Status ModelManager::GenSessionId(uint64_t &session_id) {
  647. std::lock_guard<std::mutex> lock(session_id_create_mutex_);
  648. struct timeval tv;
  649. if (gettimeofday(&tv, nullptr) != 0) {
  650. GELOGE(INTERNAL_ERROR, "Failed to get current time.");
  651. return INTERNAL_ERROR;
  652. }
  653. session_id = static_cast<uint64_t>(tv.tv_sec * 1000000 + tv.tv_usec); // 1000000us
  654. session_id_bias_++;
  655. // max bais 100.
  656. session_id_bias_ = session_id_bias_ % 100;
  657. session_id = session_id * 100 + session_id_bias_;
  658. GELOGD("Generate new session id: %lu.", session_id);
  659. return SUCCESS;
  660. }
  661. Status ModelManager::UpdateSessionId(std::shared_ptr<DavinciModel> &davinci_model, uint64_t session_id) {
  662. GeModelPtr ge_model_current = davinci_model->GetGeModel();
  663. GE_CHECK_NOTNULL(ge_model_current);
  664. if (!ge::AttrUtils::SetInt(ge_model_current, ge::MODEL_ATTR_SESSION_ID, static_cast<int64_t>(session_id))) {
  665. GELOGW("Set attr[%s] failed in updating session_id.", MODEL_ATTR_SESSION_ID.c_str());
  666. }
  667. GELOGD("Update session id: %lu.", session_id);
  668. return SUCCESS;
  669. }
  670. Status ModelManager::LoadModelOffline(uint32_t &model_id, const ModelData &model, shared_ptr<ModelListener> listener,
  671. void *dev_ptr, size_t mem_size, void *weight_ptr, size_t weight_size) {
  672. GE_CHK_BOOL_RET_STATUS(model.key.empty() || access(model.key.c_str(), F_OK) == 0, PARAM_INVALID,
  673. "input key file path is not valid, %s", strerror(errno));
  674. GenModelId(&model_id);
  675. shared_ptr<DavinciModel> davinci_model = nullptr;
  676. mmTimespec timespec = mmGetTickCount();
  677. ModelHelper model_helper;
  678. Status ret = model_helper.LoadModel(model);
  679. if (ret != SUCCESS) {
  680. GELOGE(ret, "load model failed.");
  681. return ret;
  682. }
  683. do {
  684. GeModelPtr ge_model = model_helper.GetGeModel();
  685. try {
  686. davinci_model = std::make_shared<DavinciModel>(model.priority, listener);
  687. } catch (std::bad_alloc &) {
  688. GELOGE(FAILED, "Make shared failed");
  689. return FAILED;
  690. } catch (...) {
  691. GELOGE(FAILED, "Make shared failed since other exception raise");
  692. return FAILED;
  693. }
  694. ret = davinci_model->Assign(ge_model);
  695. if (ret != SUCCESS) {
  696. GELOGW("assign model failed.");
  697. break;
  698. }
  699. davinci_model->SetId(model_id);
  700. int32_t device_id = 0;
  701. rtError_t rt_ret = rtGetDevice(&device_id);
  702. if (rt_ret != RT_ERROR_NONE || device_id < 0) {
  703. GELOGE(RT_FAILED, "Call rtGetDevice failed, ret = 0x%X, device_id = %d.", rt_ret, device_id);
  704. return FAILED;
  705. }
  706. davinci_model->SetDeviceId(device_id);
  707. davinci_model->SetOmName(model.om_name);
  708. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  709. /// These session_ids come from the same model, so the values of session_id are the same.
  710. /// Update session_id for infer in load model to avoid the same session_id.
  711. uint64_t new_session_id;
  712. ret = GenSessionId(new_session_id);
  713. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Generate session_id for infer failed.");
  714. ret = UpdateSessionId(davinci_model, new_session_id);
  715. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "Update session_id for infer failed.");
  716. ret = davinci_model->Init(dev_ptr, mem_size, weight_ptr, weight_size);
  717. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, break, "DavinciInit failed.");
  718. InsertModel(model_id, davinci_model);
  719. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(davinci_model == nullptr, ret = PARAM_INVALID; break, "Insert model failed");
  720. GELOGI("Parse model %u success.", model_id);
  721. if (ProfilingManager::Instance().ProfilingOn()) {
  722. davinci_model->SetProfileTime(MODEL_LOAD_START, (timespec.tv_sec * 1000 * 1000 * 1000 +
  723. timespec.tv_nsec)); // 1000 ^ 3 converts second to nanosecond
  724. davinci_model->SetProfileTime(MODEL_LOAD_END);
  725. if (davinci_model->SinkModelProfile() != SUCCESS) {
  726. GELOGW("Sink model profile failed.");
  727. }
  728. }
  729. GE_IF_BOOL_EXEC(ret == SUCCESS, device_count++);
  730. return SUCCESS;
  731. } while (0);
  732. return ret;
  733. }
  734. ///
  735. /// @ingroup ge
  736. /// @brief ACL case, Load task list with queue.
  737. /// @param [out] model_id: model id for manager.
  738. /// @param [in] model_data: Model data load from offline model file.
  739. /// @param [in] input_que_ids: input queue ids from user, num equals Data Op.
  740. /// @param [in] output_que_ids: input queue ids from user, num equals NetOutput Op.
  741. /// @return: 0 for success / others for fail
  742. ///
  743. Status ModelManager::LoadModelWithQ(uint32_t &model_id, const ModelData &model_data,
  744. const std::vector<uint32_t> &input_queue_ids,
  745. const std::vector<uint32_t> &output_queue_ids) {
  746. GE_CHK_BOOL_RET_STATUS(model_data.key.empty() || access(model_data.key.c_str(), F_OK) == 0, PARAM_INVALID,
  747. "input key file path is not valid, %s", strerror(errno));
  748. ModelHelper model_helper;
  749. Status ret = model_helper.LoadModel(model_data);
  750. if (ret != SUCCESS) {
  751. GELOGE(ret, "load model failed.");
  752. return ret;
  753. }
  754. shared_ptr<DavinciModel> davinci_model = MakeShared<DavinciModel>(model_data.priority, nullptr);
  755. if (davinci_model == nullptr) {
  756. GELOGE(FAILED, "create model failed.");
  757. return FAILED;
  758. }
  759. ret = davinci_model->Assign(model_helper.GetGeModel());
  760. if (ret != SUCCESS) {
  761. GELOGE(ret, "assign model failed.");
  762. return ret;
  763. }
  764. /// In multi-threaded inference, using the same session_id among multiple threads may cause some threads to fail.
  765. /// These session_ids come from the same model, so the values of session_id are the same.
  766. /// Update session_id for infer in load model to avoid the same session_id.
  767. uint64_t new_session_id;
  768. ret = GenSessionId(new_session_id);
  769. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Generate session_id for infer failed.");
  770. ret = UpdateSessionId(davinci_model, new_session_id);
  771. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Update session_id for infer failed.");
  772. GenModelId(&model_id);
  773. davinci_model->SetId(model_id);
  774. ret = davinci_model->SetQueIds(input_queue_ids, output_queue_ids);
  775. if (ret != SUCCESS) {
  776. GELOGE(ret, "set model queue ids failed.");
  777. return ret;
  778. }
  779. ret = davinci_model->Init();
  780. if (ret != SUCCESS) {
  781. GELOGE(ret, "init model failed.");
  782. return ret;
  783. }
  784. InsertModel(model_id, davinci_model);
  785. GELOGI("Parse model %u success.", model_id);
  786. return SUCCESS;
  787. }
  788. ///
  789. /// @ingroup domi_ome
  790. /// @brief ACL case, not start new thread, return result
  791. /// @param [in] model_id mode id
  792. /// @param [in] stream model stream
  793. /// @param [in] async_mode is asynchronize mode.
  794. /// @param [in] input_data input data
  795. /// @param [out] output_data output data
  796. ///
  797. Status ModelManager::ExecuteModel(uint32_t model_id, rtStream_t stream, bool async_mode, const InputData &input_data,
  798. OutputData &output_data) {
  799. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  800. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "Invalid Model ID %u to start! ", model_id);
  801. GeModelPtr ge_model_current = davinci_model->GetGeModel();
  802. bool need_destroy_aicpu_kernel = false;
  803. bool result = ge::AttrUtils::GetBool(ge_model_current, kNeedDestroySpecifiedAicpuKernel, need_destroy_aicpu_kernel);
  804. if (result && need_destroy_aicpu_kernel) {
  805. GELOGI("Get attr %s successfully, start to destroy specified aicpu kernel.", kNeedDestroySpecifiedAicpuKernel);
  806. // Zero copy is enabled by default, no need to judge.
  807. uint64_t session_id_davinci = davinci_model->GetSessionId();
  808. uint32_t model_id_davinci = davinci_model->GetModelId();
  809. Status status = DestroyAicpuKernel(session_id_davinci, model_id_davinci);
  810. if (status != SUCCESS) {
  811. GELOGW("Destroy specified aicpu kernel failed, session id is %lu, model id is %u.", session_id_davinci,
  812. model_id_davinci);
  813. }
  814. }
  815. Status status = davinci_model->NnExecute(stream, async_mode, input_data, output_data);
  816. if (status == SUCCESS) {
  817. GELOGI("Execute model %u success.", model_id);
  818. }
  819. return status;
  820. }
  821. Status ModelManager::CreateAicpuSession(uint64_t session_id) {
  822. std::lock_guard<std::mutex> lock(sess_ids_mutex_);
  823. auto it = sess_ids_.find(session_id);
  824. // never been created by any model
  825. if (it == sess_ids_.end()) {
  826. Status ret = KernelLaunchEx(aicpu::FWKAdapter::FWKOperateType::FWK_ADPT_SESSION_CREATE, session_id, 0);
  827. if (ret == SUCCESS) {
  828. (void)sess_ids_.insert(session_id);
  829. GELOGI("The session: %lu create success.", session_id);
  830. }
  831. return ret;
  832. }
  833. return SUCCESS;
  834. }
  835. ///
  836. /// @ingroup ge
  837. /// @brief get model memory size and weight
  838. /// @param [in] const ModelData model: model type
  839. /// @param [out] size_t memSize: model memory usage
  840. /// size_t weightSize: model weight and memory size
  841. /// @return SUCCESS success / others failure
  842. ///
  843. Status ModelManager::GetModelMemAndWeightSize(const ModelData &model, size_t &mem_size, size_t &weight_size) {
  844. uint8_t *model_data = nullptr;
  845. uint32_t model_len = 0;
  846. Status ret = DavinciModelParser::ParseModelContent(model, model_data, model_len);
  847. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "parse model content failed!");
  848. OmFileLoadHelper om_file_helper;
  849. ret = om_file_helper.Init(model_data, model_len);
  850. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "om file helperInit failed!");
  851. auto partition_table = reinterpret_cast<ModelPartitionTable *>(model_data);
  852. if (partition_table->num == 1) {
  853. GELOGE(FAILED, "om model is error,please use executable om model");
  854. return FAILED;
  855. }
  856. ModelPartition task_partition;
  857. if (om_file_helper.GetModelPartition(ModelPartitionType::TASK_INFO, task_partition) != SUCCESS) {
  858. GELOGE(FAILED, "get task model partition failed.");
  859. return FAILED;
  860. }
  861. std::shared_ptr<domi::ModelTaskDef> model_task_def = MakeShared<domi::ModelTaskDef>();
  862. if (model_task_def == nullptr) {
  863. return FAILED;
  864. }
  865. if (task_partition.size != 0) {
  866. if (!ReadProtoFromArray(task_partition.data, static_cast<int>(task_partition.size), model_task_def.get())) {
  867. GELOGE(FAILED, "ReadProtoFromArray failed.");
  868. return FAILED;
  869. }
  870. }
  871. ModelPartition partition_weight;
  872. ret = om_file_helper.GetModelPartition(ModelPartitionType::WEIGHTS_DATA, partition_weight);
  873. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ret != SUCCESS, return ret, "Get weight partition failed. ret = %u", ret);
  874. mem_size = model_task_def->memory_size();
  875. weight_size = partition_weight.size;
  876. return SUCCESS;
  877. }
  878. void ModelManager::GenModelId(uint32_t *id) {
  879. if (id == nullptr) {
  880. return;
  881. }
  882. std::lock_guard<std::mutex> lock(map_mutex_);
  883. *id = ++max_model_id_;
  884. }
  885. Status ModelManager::GetOrigInputInfo(uint32_t model_id, uint32_t index, OriginInputInfo &orig_input_info) {
  886. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  887. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID, "GetOrigInputInfo failed, invalid model_id is %u.",
  888. model_id);
  889. return davinci_model->GetOrigInputInfo(index, orig_input_info);
  890. }
  891. Status ModelManager::GetAllAippInputOutputDims(uint32_t model_id, uint32_t index,
  892. std::vector<InputOutputDims> &input_dims,
  893. std::vector<InputOutputDims> &output_dims) {
  894. std::shared_ptr<DavinciModel> davinci_model = GetModel(model_id);
  895. GE_CHK_BOOL_RET_STATUS(davinci_model != nullptr, PARAM_INVALID,
  896. "GetAllAippInputOutputDims failed, invalid model_id is %u.", model_id);
  897. return davinci_model->GetAllAippInputOutputDims(index, input_dims, output_dims);
  898. }
  899. } // namespace ge

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