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

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

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