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

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

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