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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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/new_model_manager/model_utils.h"
  18. #include "graph/utils/tensor_utils.h"
  19. #include "graph/utils/type_utils.h"
  20. #include "omm/csa_interact.h"
  21. namespace ge {
  22. namespace hybrid {
  23. namespace {
  24. int kDataOutputIndex = 0;
  25. }
  26. HybridModelAsyncExecutor::HybridModelAsyncExecutor(HybridModel *model)
  27. : model_(model), run_flag_(false) {
  28. }
  29. HybridModelAsyncExecutor::~HybridModelAsyncExecutor() {
  30. if (stream_ != nullptr) {
  31. GE_CHK_RT(rtStreamDestroy(stream_));
  32. }
  33. }
  34. void HybridModelAsyncExecutor::SetDeviceId(uint32_t device_id) {
  35. device_id_ = device_id;
  36. }
  37. void HybridModelAsyncExecutor::SetModelId(uint32_t model_id) {
  38. model_id_ = model_id;
  39. }
  40. Status HybridModelAsyncExecutor::EnqueueData(const shared_ptr<InputDataWrapper> &data) {
  41. GE_CHK_STATUS_EXEC(data_inputer_->Push(data), return domi::DATA_QUEUE_ISFULL,
  42. "Data queue is full, please call again later, model_id %u ", model_id_);
  43. GELOGD("EnqueueData successfully. model_id = %u, data_index = %u", data->GetInput().model_id, data->GetInput().index);
  44. return SUCCESS;
  45. }
  46. Status HybridModelAsyncExecutor::Start(const std::shared_ptr<ModelListener> &listener) {
  47. GELOGD("HybridModelExecutor::Start IN, listener = %p", listener.get());
  48. std::lock_guard<std::mutex> lk(mu_);
  49. GE_CHK_BOOL_RET_STATUS(!run_flag_, INTERNAL_ERROR, "Model already started.");
  50. run_flag_ = true;
  51. listener_ = listener;
  52. future_ = std::async([&]() -> Status {
  53. return RunInternal();
  54. });
  55. GE_CHK_BOOL_RET_STATUS(future_.valid(), INTERNAL_ERROR, "Failed to start.");
  56. GELOGD("HybridModelExecutor::Start successfully");
  57. return SUCCESS;
  58. }
  59. Status HybridModelAsyncExecutor::Stop() {
  60. std::lock_guard<std::mutex> lk(mu_);
  61. run_flag_ = false;
  62. data_inputer_->Stop();
  63. auto ret = future_.get();
  64. if (stream_ != nullptr) {
  65. GE_CHK_RT(rtStreamDestroy(stream_));
  66. stream_ = nullptr;
  67. }
  68. return ret;
  69. }
  70. Status HybridModelAsyncExecutor::Init() {
  71. data_inputer_ = std::unique_ptr<DataInputer>(new(std::nothrow) DataInputer());
  72. GE_CHECK_NOTNULL(data_inputer_);
  73. GE_CHK_RT_RET(rtStreamCreate(&stream_, RT_STREAM_PRIORITY_DEFAULT));
  74. executor_ = std::unique_ptr<HybridModelExecutor>(new(std::nothrow) HybridModelExecutor(model_, device_id_, stream_));
  75. GE_CHECK_NOTNULL(executor_);
  76. GE_CHK_STATUS_RET(executor_->Init(), "Failed to init hybrid engine");
  77. GE_CHK_STATUS_RET(InitInputTensors(), "Failed to init input tensors");
  78. return SUCCESS;
  79. }
  80. Status HybridModelAsyncExecutor::PreRun(InputData &current_data) {
  81. GE_CHK_STATUS_RET(SyncVarData(), "Failed to sync var data");
  82. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[SyncVarData] End");
  83. GE_CHK_STATUS_RET(CopyInputData(current_data), "Failed to copy input data to model");
  84. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[CopyInputData] End");
  85. return SUCCESS;
  86. }
  87. Status HybridModelAsyncExecutor::RunInternal() {
  88. auto device_id = static_cast<int32_t>(device_id_);
  89. GELOGD("Hybrid model start. model_id = %u, device_id = %u", model_id_, device_id_);
  90. GE_CHK_RT_RET(rtSetDevice(device_id));
  91. // DeviceReset before thread run finished!
  92. GE_MAKE_GUARD(not_used_var, [&] { GE_CHK_RT(rtDeviceReset(device_id)); });
  93. while (run_flag_) {
  94. std::shared_ptr<InputDataWrapper> data_wrapper;
  95. Status ret = data_inputer_->Pop(data_wrapper);
  96. if (data_wrapper == nullptr || ret != SUCCESS) {
  97. GELOGI("data_wrapper is null!, ret = %u", ret);
  98. continue;
  99. }
  100. GELOGI("Getting the input data, model_id:%u", model_id_);
  101. GE_IF_BOOL_EXEC(!run_flag_, break);
  102. InputData current_data = data_wrapper->GetInput();
  103. GELOGI("Model thread Run begin, model id:%u, data index:%u.", model_id_, current_data.index);
  104. HybridModelExecutor::ExecuteArgs args;
  105. args.inputs.resize(input_tensors_.size());
  106. for (auto &it : input_tensors_) {
  107. args.inputs[it.first] = it.second;
  108. }
  109. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[RunInternal] [iteration = %d] Start", iterator_count_);
  110. ret = PreRun(current_data);
  111. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  112. ret != SUCCESS, (void) HandleResult(ret, current_data.index, args, data_wrapper->GetOutput());
  113. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_FMK, JOBSUBSTATE_GRAPH_EXEC);
  114. continue, "PreRun failed."); // [No need to check value]
  115. ret = executor_->Execute(args);
  116. ret = HandleResult(ret, current_data.index, args, data_wrapper->GetOutput());
  117. if (ret != SUCCESS) {
  118. CsaInteract::GetInstance().StoreInternalErrorCode(ret, ERROR_MODULE_RUNTIME, JOBSUBSTATE_GRAPH_EXEC);
  119. continue;
  120. }
  121. RECORD_MODEL_EXECUTION_EVENT(executor_->GetContext(), "[RunInternal] [iteration = %d] End", iterator_count_);
  122. iterator_count_++;
  123. GELOGI("run iterator count is %lu", iterator_count_);
  124. }
  125. CsaInteract::GetInstance().WriteInternalErrorCode();
  126. GELOGI("Model run end, model id:%u", model_id_);
  127. return SUCCESS;
  128. }
  129. Status HybridModelAsyncExecutor::HandleResult(Status exec_ret,
  130. uint32_t data_id,
  131. HybridModelExecutor::ExecuteArgs &args,
  132. OutputData *output_data) {
  133. GELOGD("Start to handle result. model id = %u, data index = %u, execution ret = %u", model_id_, data_id, exec_ret);
  134. std::vector<ge::OutputTensorInfo> output_tensor_info_list;
  135. if (exec_ret == END_OF_SEQUENCE) {
  136. GELOGW("End of sequence, model id = %u", model_id_);
  137. return OnComputeDone(data_id, END_OF_SEQUENCE, output_tensor_info_list);
  138. }
  139. if (exec_ret != SUCCESS) {
  140. GELOGE(exec_ret, "Failed to execute graph. model_id = %u", model_id_);
  141. return OnComputeDone(data_id, INTERNAL_ERROR, output_tensor_info_list);
  142. }
  143. GE_CHECK_NOTNULL(output_data);
  144. auto ret = CopyOutputs(args, output_data, output_tensor_info_list);
  145. if (ret != SUCCESS) {
  146. OnComputeDone(data_id, INTERNAL_ERROR, output_tensor_info_list);
  147. return INTERNAL_ERROR;
  148. }
  149. GELOGD("Executed graph successfully, model id = %u, data_index = %u", model_id_, data_id);
  150. return OnComputeDone(data_id, SUCCESS, output_tensor_info_list);
  151. }
  152. Status HybridModelAsyncExecutor::SyncVarData() {
  153. GELOGI("Sync var data, model id:%u", model_id_);
  154. TensorValue *global_step_var = model_->GetVariable(NODE_NAME_GLOBAL_STEP);
  155. if (global_step_var != nullptr) {
  156. std::vector<uint64_t> v_step;
  157. v_step.push_back(iterator_count_);
  158. GE_CHK_RT_RET(rtMemcpy(global_step_var->MutableData(),
  159. global_step_var->GetSize(),
  160. v_step.data(),
  161. v_step.size() * sizeof(uint64_t),
  162. RT_MEMCPY_HOST_TO_DEVICE));
  163. } else {
  164. GELOGD("No GLOBAL_STEP variable was found.");
  165. }
  166. return SUCCESS;
  167. }
  168. Status HybridModelAsyncExecutor::CopyInputData(const InputData &current_data) {
  169. const std::vector<DataBuffer> &blobs = current_data.blobs;
  170. for (const auto &it : input_tensors_) {
  171. auto input_index = it.first;
  172. auto input_tensor = it.second;
  173. auto data_size = input_tensor.GetSize();
  174. GELOGD("To copy input data for input[%u]", input_index);
  175. if (input_index >= blobs.size()) {
  176. GELOGE(FAILED, "Blobs not match: blobs=%zu, tensor=%zu, index=%u, size=%ld",
  177. blobs.size(), model_->input_nodes_.size(), input_index, data_size);
  178. return FAILED;
  179. }
  180. const DataBuffer &data_buf = blobs[input_index];
  181. auto mem_size = static_cast<uint32_t>(data_size);
  182. GE_CHK_BOOL_RET_STATUS(mem_size >= data_buf.length,
  183. PARAM_INVALID,
  184. "input data size(%u) does not match model required size(%u), ret failed.",
  185. data_buf.length,
  186. mem_size);
  187. GELOGI("[IMAS]CopyPlainData memcpy graph_%u type[F] output[%u] memaddr[%p] mem_size[%u] datasize[%u]",
  188. model_->root_runtime_param_.graph_id, input_index, input_tensor.GetData(), mem_size, data_buf.length);
  189. GE_CHK_RT_RET(rtMemcpy(input_tensor.MutableData(),
  190. mem_size,
  191. data_buf.data,
  192. data_buf.length,
  193. RT_MEMCPY_HOST_TO_DEVICE));
  194. }
  195. return SUCCESS;
  196. }
  197. Status HybridModelAsyncExecutor::InitInputTensors() {
  198. auto allocator = NpuMemoryAllocator::GetAllocator(device_id_);
  199. GE_CHECK_NOTNULL(allocator);
  200. int input_index = 0;
  201. for (const auto &input_node : model_->GetRootGraphItem()->GetInputNodes()) {
  202. GELOGD("Init input[%u], node = %s", input_index, input_node->NodeName().c_str());
  203. auto output_desc = input_node->op_desc->GetOutputDescPtr(kDataOutputIndex);
  204. GE_CHECK_NOTNULL(output_desc);
  205. int64_t tensor_size = 0;
  206. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetSize(*output_desc, tensor_size),
  207. "Failed to get size from %s",
  208. input_node->NodeName().c_str());
  209. if (tensor_size == 0) {
  210. GELOGW("[%s] Tensor size == 0", input_node->NodeName().c_str());
  211. GE_CHK_GRAPH_STATUS_RET(TensorUtils::GetTensorMemorySizeInBytes(*output_desc, tensor_size),
  212. "Failed to calc tensor size");
  213. GELOGD("[%s] Tensor size updated to %ld", input_node->NodeName().c_str(), tensor_size);
  214. }
  215. auto buffer = TensorBuffer::Create(allocator, tensor_size);
  216. GE_CHECK_NOTNULL(buffer);
  217. TensorValue tensor(shared_ptr<TensorBuffer>(buffer.release()));
  218. tensor.SetName("Input_" + input_node->NodeName());
  219. input_tensors_.emplace(input_index, tensor);
  220. input_index += 1;
  221. }
  222. return SUCCESS;
  223. }
  224. Status HybridModelAsyncExecutor::OnComputeDone(uint32_t data_index, uint32_t result_code,
  225. std::vector<ge::OutputTensorInfo> &outputs) {
  226. GELOGD("OnComputeDone. model id = %u, data index = %u, execution ret = %u", model_id_, data_index, result_code);
  227. if (listener_ != nullptr) {
  228. GE_CHK_STATUS(listener_->OnComputeDone(model_id_, data_index, result_code, outputs),
  229. "OnComputeDone failed");
  230. }
  231. return result_code;
  232. }
  233. Status HybridModelAsyncExecutor::CopyOutputs(HybridModelExecutor::ExecuteArgs &args,
  234. OutputData *output_data,
  235. std::vector<ge::OutputTensorInfo> &outputs) {
  236. // copy output data from op to designated position
  237. std::vector<ConstGeTensorDescPtr> &output_tensor_desc_list = args.output_desc;
  238. std::vector<TensorValue> &output_tensors = args.outputs;
  239. if (output_tensor_desc_list.size() != output_tensors.size()) {
  240. GELOGE(INTERNAL_ERROR,
  241. "Output sizes mismatch. From op_desc = %zu, and from output tensors = %zu",
  242. output_tensor_desc_list.size(),
  243. output_tensors.size());
  244. return INTERNAL_ERROR;
  245. }
  246. GELOGD("Number of outputs = %zu", output_tensor_desc_list.size());
  247. for (size_t i = 0; i < output_tensors.size(); ++i) {
  248. GELOGD("Start to process output[%zu]", i);
  249. auto &output_tensor = output_tensors[i];
  250. auto &tensor_desc = output_tensor_desc_list.at(i);
  251. GE_CHECK_NOTNULL(tensor_desc);
  252. int64_t output_size = -1;
  253. GE_CHK_GRAPH_STATUS_RET(TensorUtils::CalcTensorMemSize(tensor_desc->GetShape(),
  254. tensor_desc->GetFormat(),
  255. tensor_desc->GetDataType(),
  256. output_size),
  257. "Failed to calc tensor size for output[%zu]. shape = [%s], type = %s, format = %s",
  258. i,
  259. tensor_desc->GetShape().ToString().c_str(),
  260. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  261. TypeUtils::FormatToSerialString(tensor_desc->GetFormat()).c_str());
  262. GELOGD("Got tensor size for output[%zu] successfully. shape = [%s], type = %s, format = %s, size = %ld",
  263. i,
  264. tensor_desc->GetShape().ToString().c_str(),
  265. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  266. TypeUtils::FormatToSerialString(tensor_desc->GetFormat()).c_str(),
  267. output_size);
  268. GE_CHECK_GE(output_size, 0);
  269. GE_CHECK_LE(output_size, UINT32_MAX);
  270. if (output_tensor.GetSize() < static_cast<size_t>(output_size)) {
  271. GELOGE(INTERNAL_ERROR,
  272. "output[%zu] tensor size(%zu) is not enough for output shape [%s]",
  273. i, output_tensor.GetSize(), tensor_desc->GetShape().ToString().c_str());
  274. return INTERNAL_ERROR;
  275. }
  276. ge::OutputTensorInfo output;
  277. output.data_type = static_cast<uint32_t>(tensor_desc->GetDataType());
  278. output.dims = tensor_desc->GetShape().GetDims();
  279. output.length = output_size;
  280. if (output_size > 0) {
  281. std::unique_ptr<uint8_t[]> data_buf(new(std::nothrow) uint8_t[output_size]);
  282. GE_CHECK_NOTNULL(data_buf);
  283. GE_CHK_RT_RET(rtMemcpy(data_buf.get(),
  284. output_size,
  285. output_tensor.GetData(),
  286. output_size,
  287. RT_MEMCPY_DEVICE_TO_HOST));
  288. output.data = std::move(data_buf);
  289. output_data->blobs.emplace_back(data_buf.get(), static_cast<uint32_t>(output_size), false);
  290. } else {
  291. GELOGW("Output[%zu] is empty. shape = [%s]", i, tensor_desc->GetShape().ToString().c_str());
  292. output.data = nullptr;
  293. output_data->blobs.emplace_back(nullptr, 0U, false);
  294. }
  295. outputs.emplace_back(std::move(output));
  296. GELOGD("Output[%zu] added, type = %s, shape = [%s], size = %ld",
  297. i,
  298. TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()).c_str(),
  299. tensor_desc->GetShape().ToString().c_str(),
  300. output_size);
  301. }
  302. return SUCCESS;
  303. }
  304. Status HybridModelAsyncExecutor::Execute(const vector<GeTensor> &inputs, vector<GeTensor> &outputs) {
  305. GELOGD("Start to execute model.");
  306. // prepare inputs
  307. InputData input_data;
  308. for (auto &tensor : inputs) {
  309. DataBuffer buffer;
  310. buffer.data = const_cast<uint8_t *>(tensor.GetData().GetData());
  311. buffer.length = tensor.GetData().size();
  312. input_data.blobs.emplace_back(buffer);
  313. }
  314. GE_CHK_STATUS_RET(CopyInputData(input_data), "Failed to copy input data to model");
  315. GELOGD("Done copying input data successfully.");
  316. HybridModelExecutor::ExecuteArgs args;
  317. args.inputs.resize(input_tensors_.size());
  318. args.input_desc.resize(input_tensors_.size());
  319. for (auto &it : input_tensors_) {
  320. args.inputs[it.first] = it.second;
  321. args.input_desc[it.first] = MakeShared<GeTensorDesc>(inputs[it.first].GetTensorDesc());
  322. }
  323. GE_CHK_STATUS_RET(executor_->Execute(args), "Failed to execute model.");
  324. std::vector<ge::OutputTensorInfo> output_tensor_info_list;
  325. OutputData output_data;
  326. GE_CHK_STATUS_RET(CopyOutputs(args, &output_data, output_tensor_info_list), "Failed to copy outputs.");
  327. GELOGD("Done copying output data successfully. output count = %zu", output_tensor_info_list.size());
  328. int out_index = 0;
  329. outputs.resize(output_tensor_info_list.size());
  330. for (auto &out_tensor_info : output_tensor_info_list) {
  331. auto &ge_tensor = outputs[out_index];
  332. if (out_tensor_info.length > 0) {
  333. GE_CHK_GRAPH_STATUS_RET(ge_tensor.SetData(out_tensor_info.data.get(), out_tensor_info.length),
  334. "Failed to set output[%d].", out_index);
  335. }
  336. ge_tensor.MutableTensorDesc() = *args.output_desc[out_index];
  337. GELOGD("Set output[%d], tensor size = %ld, shape = [%s]",
  338. out_index,
  339. out_tensor_info.length,
  340. ge_tensor.MutableTensorDesc().MutableShape().ToString().c_str());
  341. ++out_index;
  342. }
  343. return SUCCESS;
  344. }
  345. } // namespace hybrid
  346. } // namespace ge

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