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

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