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.

hybrid_model_async_executor.cc 26 kB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 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
4 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 "hybrid/executor/hybrid_model_async_executor.h"
  17. #include "graph/load/model_manager/model_utils.h"
  18. #include "graph/utils/tensor_utils.h"
  19. #include "graph/utils/type_utils.h"
  20. #include "graph/ge_context.h"
  21. #include "omm/csa_interact.h"
  22. namespace ge {
  23. namespace hybrid {
  24. namespace {
  25. const int kDataOutputIndex = 0;
  26. const size_t kMinimumPiplineStages = 2;
  27. const int kDefaultLoopCount = 10;
  28. }
  29. HybridModelAsyncExecutor::HybridModelAsyncExecutor(HybridModel *model)
  30. : model_(model), run_flag_(false), data_dumper_(nullptr) {
  31. }
  32. HybridModelAsyncExecutor::~HybridModelAsyncExecutor() {
  33. if (stream_ != nullptr) {
  34. GE_CHK_RT(rtStreamDestroy(stream_));
  35. }
  36. }
  37. void HybridModelAsyncExecutor::SetDeviceId(uint32_t device_id) {
  38. device_id_ = device_id;
  39. }
  40. void HybridModelAsyncExecutor::SetModelId(uint32_t model_id) {
  41. model_id_ = model_id;
  42. }
  43. Status HybridModelAsyncExecutor::EnqueueData(const shared_ptr<InputDataWrapper> &data) {
  44. if (data_inputer_->Push(data) != SUCCESS) {
  45. REPORT_CALL_ERROR("E19999", "Data queue is full, please call again later when %s, model_id %u.",
  46. __FUNCTION__, model_id_);
  47. GELOGE(domi::DATA_QUEUE_ISFULL,
  48. "[Push][Data] Data queue is full, please call again later, model_id %u ", model_id_);
  49. return domi::DATA_QUEUE_ISFULL;
  50. }
  51. GELOGD("EnqueueData successfully. model_id = %u, data_index = %u", data->GetInput().model_id, data->GetInput().index);
  52. return SUCCESS;
  53. }
  54. Status HybridModelAsyncExecutor::Start(const std::shared_ptr<ModelListener> &listener) {
  55. GELOGD("HybridModelExecutor::Start IN, has listener = %d", listener != nullptr);
  56. std::lock_guard<std::mutex> lk(mu_);
  57. if (run_flag_) {
  58. REPORT_INNER_ERROR("E19999",
  59. "Model already started when HybridModelAsyncExecutor %s, model_id:%u.", __FUNCTION__, model_id_);
  60. GELOGE(INTERNAL_ERROR, "[Check][RunState] Model already started, model_id:%u.", model_id_);
  61. return INTERNAL_ERROR;
  62. }
  63. run_flag_ = true;
  64. listener_ = listener;
  65. future_ = std::async(std::launch::async, [&]() -> Status {
  66. GetThreadLocalContext() = *executor_->GetContext()->ge_context;
  67. GetContext().SetSessionId(executor_->GetContext()->session_id);
  68. GetContext().SetContextId(executor_->GetContext()->context_id);
  69. return RunInternal();
  70. });
  71. GE_CHK_BOOL_RET_STATUS(future_.valid(), INTERNAL_ERROR,
  72. "[Check][RunState] Failed to start, model_id:%u.", model_id_);
  73. GELOGD("HybridModelExecutor::Start successfully");
  74. return SUCCESS;
  75. }
  76. Status HybridModelAsyncExecutor::Stop() {
  77. std::lock_guard<std::mutex> lk(mu_);
  78. run_flag_ = false;
  79. data_inputer_->Stop();
  80. Status ret = SUCCESS;
  81. if (future_.valid()) {
  82. ret = future_.get();
  83. }
  84. if (is_op_debug_reg_) {
  85. op_debug_register_.UnregisterDebugForStream(stream_);
  86. }
  87. if (stream_ != nullptr) {
  88. GE_CHK_RT(rtStreamDestroy(stream_));
  89. stream_ = nullptr;
  90. }
  91. return ret;
  92. }
  93. Status HybridModelAsyncExecutor::Init() {
  94. data_inputer_ = std::unique_ptr<DataInputer>(new(std::nothrow) DataInputer());
  95. GE_CHECK_NOTNULL(data_inputer_);
  96. GE_CHK_RT_RET(rtStreamCreate(&stream_, RT_STREAM_PRIORITY_DEFAULT));
  97. executor_ = std::unique_ptr<HybridModelExecutor>(new(std::nothrow) HybridModelExecutor(model_, device_id_, stream_));
  98. GE_CHECK_NOTNULL(executor_);
  99. GE_CHK_STATUS_RET(executor_->Init(),
  100. "[Init][HybridModelExecutor] failed, model_id:%u.", model_id_);
  101. GE_CHK_STATUS_RET(DumpOpDebug(), "[Dump][OpDebug] failed, model_id:%u.", model_id_);
  102. GELOGI("HybridModel stage nums:%zu", model_->GetRootGraphItem()->NumGroups());
  103. if (model_->GetRootGraphItem()->NumGroups() >= kMinimumPiplineStages) {
  104. pipe_executor_ =
  105. std::unique_ptr<HybridModelPipelineExecutor>(new(std::nothrow) HybridModelPipelineExecutor(model_, device_id_));
  106. GE_CHECK_NOTNULL(pipe_executor_);
  107. GE_CHK_STATUS_RET(pipe_executor_->Init(),
  108. "[Init][HybridModelPipelineExecutor] failed, model_id:%u.", model_id_);
  109. }
  110. GE_CHK_STATUS_RET(InitInputDesc(), "[Init][InputDesc] failed, model_id:%u.", model_id_);
  111. return SUCCESS;
  112. }
  113. Status HybridModelAsyncExecutor::PreRun(InputData &current_data, HybridModelExecutor::ExecuteArgs &args) {
  114. GE_CHK_STATUS_RET(SyncVarData(), "[Invoke][SyncVarData] failed, model_id:%u.", model_id_);
  115. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[SyncVarData] End");
  116. GE_CHK_STATUS_RET(PrepareInputs(current_data, args),
  117. "[Invoke][PrepareInputs] failed to copy input data to model, model_id:%u.", model_id_);
  118. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[CopyInputData] End");
  119. return SUCCESS;
  120. }
  121. Status HybridModelAsyncExecutor::RunInternal() {
  122. auto device_id = static_cast<int32_t>(device_id_);
  123. GELOGD("Hybrid model start. model_id = %u, device_id = %u", model_id_, device_id_);
  124. GE_CHK_RT_RET(rtSetDevice(device_id));
  125. // DeviceReset before thread run finished!
  126. GE_MAKE_GUARD(not_used_var, [&] { GE_CHK_RT(rtDeviceReset(device_id)); });
  127. while (run_flag_) {
  128. std::shared_ptr<InputDataWrapper> data_wrapper;
  129. Status ret = data_inputer_->Pop(data_wrapper);
  130. if (data_wrapper == nullptr || ret != SUCCESS) {
  131. GELOGI("data_wrapper is null!, ret = %u", ret);
  132. continue;
  133. }
  134. GELOGI("Getting the input data, model_id:%u", model_id_);
  135. GE_IF_BOOL_EXEC(!run_flag_, break);
  136. InputData current_data = data_wrapper->GetInput();
  137. GELOGI("Model thread Run begin, model id:%u, data index:%u.", model_id_, current_data.index);
  138. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[RunInternal] [iteration = %d] Start", iterator_count_);
  139. HybridModelExecutor::ExecuteArgs args;
  140. ret = PreRun(current_data, args);
  141. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  142. ret != SUCCESS, (void) HandleResult(ret, current_data.index, args, data_wrapper->GetOutput());
  143. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  144. continue, "[Invoke][PreRun] failed, model_id:%u.", model_id_); // [No need to check value]
  145. if (pipe_executor_ != nullptr) {
  146. GELOGI("HybridModel will execute in pipeline mode");
  147. auto iter_per_run = std::getenv("ITER_NUM");
  148. if (iter_per_run) {
  149. args.num_loops = static_cast<int>(strtol(iter_per_run, nullptr, kDefaultLoopCount));
  150. }
  151. ret = pipe_executor_->Execute(args);
  152. } else {
  153. GELOGI("HybridModel will execute in singleline mode");
  154. ge::GetContext().SetSessionId(executor_->GetContext()->session_id);
  155. ge::GetContext().SetContextId(executor_->GetContext()->context_id);
  156. ret = executor_->Execute(args);
  157. }
  158. ret = HandleResult(ret, current_data.index, args, data_wrapper->GetOutput());
  159. if (ret != SUCCESS) {
  160. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  161. continue;
  162. }
  163. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[RunInternal] [iteration = %d] End", iterator_count_);
  164. iterator_count_++;
  165. GELOGI("run iterator count is %lu", iterator_count_);
  166. }
  167. CsaInteract::GetInstance().WriteInternalErrorCode();
  168. GELOGI("Model run end, model id:%u", model_id_);
  169. return SUCCESS;
  170. }
  171. Status HybridModelAsyncExecutor::HandleResult(Status exec_ret,
  172. uint32_t data_id,
  173. HybridModelExecutor::ExecuteArgs &args,
  174. OutputData *output_data) {
  175. GELOGD("Start to handle result. model id = %u, data index = %u, execution ret = %u", model_id_, data_id, exec_ret);
  176. std::vector<ge::OutputTensorInfo> output_tensor_info_list;
  177. if (args.is_eos) {
  178. GELOGI("End of sequence, model id = %u", model_id_);
  179. GE_CHK_STATUS_RET_NOLOG(OnComputeDone(data_id, END_OF_SEQUENCE, output_tensor_info_list));
  180. return SUCCESS;
  181. }
  182. if (exec_ret != SUCCESS) {
  183. GELOGE(exec_ret, "[Check][Param:Status] failed to execute graph. model_id = %u", model_id_);
  184. REPORT_INNER_ERROR("E19999",
  185. "failed to execute graph when HybridModelAsyncExecutor %s. model_id = %u", __FUNCTION__, model_id_);
  186. return OnComputeDone(data_id, INTERNAL_ERROR, output_tensor_info_list);
  187. }
  188. GE_CHECK_NOTNULL(output_data);
  189. auto ret = CopyOutputs(args, output_data, output_tensor_info_list);
  190. if (ret != SUCCESS) {
  191. OnComputeDone(data_id, INTERNAL_ERROR, output_tensor_info_list);
  192. return INTERNAL_ERROR;
  193. }
  194. GELOGD("Executed graph successfully, model id = %u, data_index = %u", model_id_, data_id);
  195. return OnComputeDone(data_id, SUCCESS, output_tensor_info_list);
  196. }
  197. Status HybridModelAsyncExecutor::SyncVarData() {
  198. GELOGI("Sync var data, model id:%u", model_id_);
  199. TensorValue *global_step_var = model_->GetVariable(NODE_NAME_GLOBAL_STEP);
  200. if (global_step_var != nullptr) {
  201. std::vector<uint64_t> v_step;
  202. v_step.push_back(iterator_count_);
  203. GE_CHK_RT_RET(rtMemcpy(global_step_var->MutableData(),
  204. global_step_var->GetSize(),
  205. v_step.data(),
  206. v_step.size() * sizeof(uint64_t),
  207. RT_MEMCPY_HOST_TO_DEVICE));
  208. } else {
  209. GELOGD("No GLOBAL_STEP variable was found.");
  210. }
  211. return SUCCESS;
  212. }
  213. Status HybridModelAsyncExecutor::PrepareInputs(const InputData &current_data, HybridModelExecutor::ExecuteArgs &args) {
  214. if (current_data.blobs.size() < input_tensor_desc_.size()) {
  215. GELOGE(PARAM_INVALID,
  216. "[Check][Size]Blob size mismatches, expect at least %zu, but got %zu, model_id = %u",
  217. input_tensor_desc_.size(), current_data.blobs.size(), model_id_);
  218. REPORT_INNER_ERROR("E19999",
  219. "Blob size mismatches, expect at least %zu, but got %zu when HybridModelAsyncExecutor %s, model_id = %u.",
  220. input_tensor_desc_.size(), current_data.blobs.size(), __FUNCTION__, model_id_);
  221. return PARAM_INVALID;
  222. }
  223. auto allocator = NpuMemoryAllocator::GetAllocator(device_id_);
  224. GE_CHECK_NOTNULL(allocator);
  225. args.input_desc.resize(input_tensor_desc_.size());
  226. const std::vector<DataBuffer> &blobs = current_data.blobs;
  227. for (size_t input_index = 0; input_index < input_tensor_desc_.size(); ++input_index) {
  228. auto tensor_size = input_sizes_[input_index];
  229. if (is_input_dynamic_[input_index]) {
  230. if (input_index >= current_data.shapes.size()) {
  231. GELOGE(PARAM_INVALID,
  232. "[Check][Range]Shape index out of range, index = %zu, shape size = %zu model_id = %u.",
  233. input_index, current_data.shapes.size(), model_id_);
  234. REPORT_INNER_ERROR("E19999",
  235. "Shape index out of range, index = %zu, shape size = %zu when HybridModelAsyncExecutor %s, model_id = %u.",
  236. input_index, current_data.shapes.size(), __FUNCTION__, model_id_);
  237. return PARAM_INVALID;
  238. }
  239. auto &tensor_desc = input_tensor_desc_[input_index];
  240. GeShape shape(current_data.shapes[input_index]);
  241. std::vector<std::pair<int64_t, int64_t>> range;
  242. auto range_ret = tensor_desc->GetShapeRange(range);
  243. GE_CHK_BOOL_RET_STATUS(range_ret == GRAPH_SUCCESS, INTERNAL_ERROR,
  244. "[Invoke][GetShapeRange] failed, ret=%u, model_id = %u.", range_ret, model_id_);
  245. for (size_t k = 0; k < range.size(); ++k) {
  246. if (k >= shape.GetDimNum()) {
  247. break;
  248. }
  249. // range[k].second can be -1
  250. if (shape.GetDim(k) < range[k].first || (range[k].second >= 0 && shape.GetDim(k) > range[k].second)) {
  251. GELOGE(PARAM_INVALID,
  252. "[Check][Range]Dim out of range, shape idx = %zu, dim idx = %zu, dim = %ld, range = [%ld, %ld], model_id = %u.",
  253. input_index, k, shape.GetDim(k), range[k].first, range[k].second, model_id_);
  254. REPORT_INNER_ERROR("E19999",
  255. "Dim out of range, shape idx = %zu, dim idx = %zu, dim = %ld, range = [%ld, %ld], model_id = %u.",
  256. input_index, k, shape.GetDim(k), range[k].first, range[k].second, model_id_);
  257. return PARAM_INVALID;
  258. }
  259. }
  260. tensor_desc->SetShape(shape);
  261. args.input_desc[input_index] = tensor_desc;
  262. GELOGD("Update shape of input[%zu] to [%s]", input_index, tensor_desc->MutableShape().ToString().c_str());
  263. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetTensorMemorySizeInBytes(*tensor_desc, tensor_size),
  264. "[Invoke][GetTensorMemorySizeInBytes]Failed to calc tensor size, index = %zu, shape = [%s], model_id = %u.",
  265. input_index, tensor_desc->GetShape().ToString().c_str(), model_id_);
  266. GELOGD("Input tensor[%zu] size = %zu", input_index, tensor_size);
  267. }
  268. GE_CHECK_GE(tensor_size, 0);
  269. AllocationAttr attr;
  270. if (GetContext().GetHostExecFlag()) {
  271. attr.SetMemType(HOST_DDR);
  272. }
  273. auto tensor_buffer = TensorBuffer::Create(allocator, tensor_size, &attr);
  274. GE_CHECK_NOTNULL(tensor_buffer);
  275. args.inputs.emplace_back(std::shared_ptr<TensorBuffer>(tensor_buffer.release()));
  276. GELOGD("To copy input data for input[%zu]", input_index);
  277. const DataBuffer &data_buf = blobs[input_index];
  278. auto mem_size = static_cast<uint64_t>(tensor_size);
  279. if (mem_size < data_buf.length) {
  280. REPORT_INNER_ERROR("E19999",
  281. "input data size(%lu) does not match model required size(%lu) when %s, ret failed, model_id = %u.",
  282. data_buf.length, mem_size, __FUNCTION__, model_id_);
  283. GELOGE(PARAM_INVALID,
  284. "[Check][Size]input data size(%lu) does not match model required size(%lu), ret failed, model_id = %u.",
  285. data_buf.length, mem_size, model_id_);
  286. return PARAM_INVALID;
  287. }
  288. if (data_buf.length > 0) {
  289. GELOGI("[IMAS]CopyPlainData memcpy graph_%u type[F] output[%zu] memaddr[%p] mem_size[%zu] datasize[%lu]",
  290. model_->root_runtime_param_.graph_id,
  291. input_index,
  292. args.inputs[input_index].GetData(),
  293. mem_size,
  294. data_buf.length);
  295. GE_CHK_RT_RET(rtMemcpy(args.inputs[input_index].MutableData(),
  296. mem_size,
  297. data_buf.data,
  298. data_buf.length,
  299. RT_MEMCPY_HOST_TO_DEVICE));
  300. }
  301. }
  302. return SUCCESS;
  303. }
  304. Status HybridModelAsyncExecutor::InitInputDesc() {
  305. int input_index = 0;
  306. for (const auto &input_node : model_->GetRootGraphItem()->GetInputNodes()) {
  307. GELOGD("Init input[%u], node = %s, is_dynamic = %d",
  308. input_index,
  309. input_node->NodeName().c_str(),
  310. input_node->is_dynamic);
  311. auto output_desc = input_node->MutableOutputDesc(kDataOutputIndex);
  312. GE_CHECK_NOTNULL(output_desc);
  313. int64_t tensor_size = -1;
  314. if (!input_node->is_dynamic) {
  315. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetSize(*output_desc, tensor_size),
  316. "Failed to get size from %s",
  317. input_node->NodeName().c_str());
  318. if (tensor_size == 0) {
  319. GELOGW("[%s] Tensor size == 0", input_node->NodeName().c_str());
  320. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetTensorMemorySizeInBytes(*output_desc, tensor_size),
  321. "Failed to calc tensor size");
  322. GELOGD("[%s] Tensor size updated to %ld", input_node->NodeName().c_str(), tensor_size);
  323. }
  324. }
  325. input_sizes_.emplace(input_index, tensor_size);
  326. input_tensor_desc_.emplace(input_index, output_desc);
  327. is_input_dynamic_.push_back(input_node->is_dynamic);
  328. input_index += 1;
  329. }
  330. return SUCCESS;
  331. }
  332. Status HybridModelAsyncExecutor::OnComputeDone(uint32_t data_index, uint32_t result_code,
  333. std::vector<ge::OutputTensorInfo> &outputs) {
  334. GELOGD("OnComputeDone. model id = %u, data index = %u, execution ret = %u", model_id_, data_index, result_code);
  335. if (listener_ != nullptr) {
  336. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_index, result_code, outputs),
  337. "[Invoke][OnComputeDone] failed, model_id = %u.", model_id_);
  338. }
  339. return result_code;
  340. }
  341. Status HybridModelAsyncExecutor::CopyOutputs(HybridModelExecutor::ExecuteArgs &args,
  342. OutputData *output_data,
  343. std::vector<ge::OutputTensorInfo> &outputs) {
  344. // copy output data from op to designated position
  345. std::vector<ConstGeTensorDescPtr> &output_tensor_desc_list = args.output_desc;
  346. std::vector<TensorValue> &output_tensors = args.outputs;
  347. if (output_tensor_desc_list.size() != output_tensors.size()) {
  348. GELOGE(INTERNAL_ERROR,
  349. "[Check][Size]Output sizes mismatch. From op_desc = %zu, and from output tensors = %zu, model_id = %u.",
  350. output_tensor_desc_list.size(), output_tensors.size(), model_id_);
  351. REPORT_INNER_ERROR("E19999", "Output sizes mismatch. From op_desc = %zu, and from output tensors = %zu, "
  352. "when HybridModelAsyncExecutor %s, model_id = %u.",
  353. output_tensor_desc_list.size(), output_tensors.size(), __FUNCTION__, model_id_);
  354. return INTERNAL_ERROR;
  355. }
  356. GELOGD("Number of outputs = %zu", output_tensor_desc_list.size());
  357. for (size_t i = 0; i < output_tensors.size(); ++i) {
  358. GELOGD("Start to process output[%zu]", i);
  359. auto &output_tensor = output_tensors[i];
  360. auto &tensor_desc = output_tensor_desc_list.at(i);
  361. GE_CHECK_NOTNULL(tensor_desc);
  362. int64_t output_size = -1;
  363. GE_CHK_GRAPH_STATUS_RET(TensorUtils::CalcTensorMemSize(tensor_desc->GetShape(),
  364. tensor_desc->GetFormat(),
  365. tensor_desc->GetDataType(),
  366. output_size),
  367. "Failed to calc tensor size for output[%zu]. shape = [%s], type = %s, format = %s",
  368. i,
  369. tensor_desc->GetShape().ToString().c_str(),
  370. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  371. TypeUtils::FormatToSerialString(tensor_desc->GetFormat()).c_str());
  372. GELOGD("Got tensor size for output[%zu] successfully. shape = [%s], type = %s, format = %s, size = %ld",
  373. i,
  374. tensor_desc->GetShape().ToString().c_str(),
  375. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  376. TypeUtils::FormatToSerialString(tensor_desc->GetFormat()).c_str(),
  377. output_size);
  378. GE_CHECK_GE(output_size, 0);
  379. GE_CHECK_LE(output_size, UINT32_MAX);
  380. if (output_tensor.GetSize() < static_cast<size_t>(output_size)) {
  381. GELOGE(INTERNAL_ERROR,
  382. "[Check][Size]output[%zu] tensor size(%zu) is not enough for output shape [%s], model_id = %u.",
  383. i, output_tensor.GetSize(), tensor_desc->GetShape().ToString().c_str(), model_id_);
  384. REPORT_INNER_ERROR("E19999",
  385. "output[%zu] tensor size(%zu) is not enough for output shape [%s] model_id = %u,"
  386. " when HybridModelAsyncExecutor %s.",
  387. i, output_tensor.GetSize(), tensor_desc->GetShape().ToString().c_str(), model_id_, __FUNCTION__);
  388. return INTERNAL_ERROR;
  389. }
  390. ge::OutputTensorInfo output;
  391. output.data_type = static_cast<uint32_t>(tensor_desc->GetDataType());
  392. output.dims = tensor_desc->GetShape().GetDims();
  393. output.length = output_size;
  394. if (output_size > 0) {
  395. std::unique_ptr<uint8_t[]> data_buf(new(std::nothrow) uint8_t[output_size]);
  396. GE_CHECK_NOTNULL(data_buf);
  397. GE_CHK_RT_RET(rtMemcpy(data_buf.get(),
  398. output_size,
  399. output_tensor.GetData(),
  400. output_size,
  401. RT_MEMCPY_DEVICE_TO_HOST));
  402. output.data = std::move(data_buf);
  403. output_data->blobs.emplace_back(data_buf.get(), static_cast<uint32_t>(output_size), false);
  404. } else {
  405. GELOGW("Output[%zu] is empty. shape = [%s]", i, tensor_desc->GetShape().ToString().c_str());
  406. output.data = nullptr;
  407. output_data->blobs.emplace_back(nullptr, 0U, false);
  408. }
  409. outputs.emplace_back(std::move(output));
  410. GELOGD("Output[%zu] added, type = %s, shape = [%s], size = %ld",
  411. i,
  412. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  413. tensor_desc->GetShape().ToString().c_str(),
  414. output_size);
  415. }
  416. return SUCCESS;
  417. }
  418. Status HybridModelAsyncExecutor::Execute(const std::vector<DataBuffer> &inputs,
  419. const std::vector<GeTensorDesc> &input_desc,
  420. std::vector<DataBuffer> &outputs,
  421. std::vector<GeTensorDesc> &output_desc) {
  422. GELOGI("Start to execute model.");
  423. HybridModelExecutor::ExecuteArgs args;
  424. args.inputs.resize(inputs.size());
  425. for (size_t i = 0; i < inputs.size(); ++i) {
  426. TensorValue tensor_value(inputs[i].data, inputs[i].length);
  427. args.inputs[i] = tensor_value;
  428. }
  429. for (size_t i = 0; i < outputs.size(); ++i) {
  430. args.outputs.emplace_back(TensorValue(outputs[i].data, outputs[i].length));
  431. }
  432. // usr must designate input tensorDesc when input shape is dynamic in inference
  433. for (size_t i = 0; i < input_desc.size(); ++i) {
  434. ConstGeTensorDescPtr tensor_desc_ptr = MakeShared<GeTensorDesc>(input_desc[i]);
  435. args.input_desc.emplace_back(tensor_desc_ptr);
  436. }
  437. GE_CHK_STATUS_RET(executor_->Execute(args), "[Invoke][Execute] Failed, model_id = %u.", model_id_);
  438. for (const auto &output_tensor_desc : args.output_desc) {
  439. output_desc.emplace_back(*output_tensor_desc);
  440. }
  441. return SUCCESS;
  442. }
  443. Status HybridModelAsyncExecutor::Execute(const vector<GeTensor> &inputs, vector<GeTensor> &outputs) {
  444. GELOGD("Start to execute model.");
  445. // prepare inputs
  446. InputData input_data;
  447. for (auto &tensor : inputs) {
  448. DataBuffer buffer;
  449. buffer.data = const_cast<uint8_t *>(tensor.GetData().GetData());
  450. buffer.length = tensor.GetData().size();
  451. input_data.blobs.emplace_back(buffer);
  452. input_data.shapes.emplace_back(tensor.GetTensorDesc().GetShape().GetDims());
  453. }
  454. HybridModelExecutor::ExecuteArgs args;
  455. GE_CHK_STATUS_RET(PrepareInputs(input_data, args),
  456. "[Invoke][PrepareInputs]Failed to copy input data to model, model_id = %u", model_id_);
  457. GELOGD("Done copying input data successfully.");
  458. GE_CHK_STATUS_RET(executor_->Execute(args), "[Invoke][Execute] Failed, model_id = %u.", model_id_);
  459. std::vector<ge::OutputTensorInfo> output_tensor_info_list;
  460. OutputData output_data;
  461. GE_CHK_STATUS_RET(CopyOutputs(args, &output_data, output_tensor_info_list),
  462. "[Invoke][CopyOutputs]Failed to copy outputs, model_id = %u.", model_id_);
  463. GELOGD("Done copying output data successfully. output count = %zu", output_tensor_info_list.size());
  464. int out_index = 0;
  465. outputs.resize(output_tensor_info_list.size());
  466. for (auto &out_tensor_info : output_tensor_info_list) {
  467. auto &ge_tensor = outputs[out_index];
  468. if (out_tensor_info.length > 0) {
  469. GE_CHK_GRAPH_STATUS_RET(ge_tensor.SetData(out_tensor_info.data.get(), out_tensor_info.length),
  470. "Failed to set output[%d].", out_index);
  471. }
  472. ge_tensor.MutableTensorDesc() = *args.output_desc[out_index];
  473. GELOGD("Set output[%d], tensor size = %ld, shape = [%s]",
  474. out_index,
  475. out_tensor_info.length,
  476. ge_tensor.MutableTensorDesc().MutableShape().ToString().c_str());
  477. ++out_index;
  478. }
  479. return SUCCESS;
  480. }
  481. Status HybridModelAsyncExecutor::DumpOpDebug() {
  482. const DumpProperties &dump_properties = executor_->GetContext()->dump_properties;
  483. if (dump_properties.IsOpDebugOpen()) {
  484. GELOGD("Opdebug is open in hybrid engine");
  485. uint32_t op_debug_mode = dump_properties.GetOpDebugMode();
  486. GE_CHK_RT_RET(op_debug_register_.RegisterDebugForStream(stream_, op_debug_mode, data_dumper_));
  487. is_op_debug_reg_ = true;
  488. data_dumper_.SetDumpProperties(dump_properties);
  489. data_dumper_.SetModelName(model_->GetModelName());
  490. data_dumper_.SetModelId(model_->GetModelId());
  491. data_dumper_.SetDeviceId(model_->GetDeviceId());
  492. void *global_step = nullptr;
  493. TensorValue *varible_global_step = model_->GetVariable(NODE_NAME_GLOBAL_STEP);
  494. if (varible_global_step != nullptr) {
  495. global_step = const_cast<void *>(varible_global_step->GetData());
  496. }
  497. void *loop_per_iter = nullptr;
  498. TensorValue *varible_loop_per_iter = model_->GetVariable(NODE_NAME_FLOWCTRL_LOOP_PER_ITER);
  499. if (varible_loop_per_iter != nullptr) {
  500. loop_per_iter = const_cast<void *>(varible_loop_per_iter->GetData());
  501. }
  502. void *loop_cond = nullptr;
  503. TensorValue *varible_loop_cond = model_->GetVariable(NODE_NAME_FLOWCTRL_LOOP_COND);
  504. if (varible_loop_cond != nullptr) {
  505. loop_cond = const_cast<void *>(varible_loop_cond->GetData());
  506. }
  507. data_dumper_.SetLoopAddr(global_step, loop_per_iter, loop_cond);
  508. GE_CHK_STATUS_RET(data_dumper_.LoadDumpInfo(),
  509. "[Invoke][LoadDumpInfo] failed in hybrid engine, model_id = %u.", model_id_);
  510. GELOGD("Dump op debug SUCCESS in hybrid engine");
  511. }
  512. return SUCCESS;
  513. }
  514. } // namespace hybrid
  515. } // namespace ge

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