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

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