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_executor.cc 10 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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_executor.h"
  17. #include "graph/ge_context.h"
  18. #include "graph/runtime_inference_context.h"
  19. #include "graph/utils/tensor_utils.h"
  20. #include "graph/load/model_manager/model_manager.h"
  21. #include "common/dump/dump_manager.h"
  22. #include "common/profiling/profiling_manager.h"
  23. namespace ge {
  24. namespace hybrid {
  25. namespace {
  26. const int kIntBase = 10;
  27. const char *const kEnvProfilingLevel = "HYBRID_PROFILING_LEVEL";
  28. } // namespace
  29. HybridModelExecutor::HybridModelExecutor(HybridModel *model, uint32_t device_id, rtStream_t stream)
  30. : model_(model), device_id_(device_id), stream_(stream) {
  31. }
  32. HybridModelExecutor::~HybridModelExecutor() {
  33. }
  34. Status HybridModelExecutor::Init(ThreadPool *thread_pool) {
  35. GELOGD("Start to init HybridGraphEngine.");
  36. GE_CHK_STATUS_RET_NOLOG(InitExecutionContext());
  37. root_graph_executor_.reset(
  38. new (std::nothrow) SubgraphExecutor(model_->GetRootGraphItem(), &context_, false, thread_pool));
  39. GE_CHECK_NOTNULL(root_graph_executor_);
  40. GELOGD("HybridGraphEngine initialized successfully.");
  41. return SUCCESS;
  42. }
  43. Status HybridModelExecutor::Execute(HybridModelExecutor::ExecuteArgs &args) {
  44. GELOGD("Start to execute model.");
  45. auto root_graph_item = model_->GetRootGraphItem();
  46. GE_CHECK_NOTNULL(root_graph_item);
  47. if (root_graph_item->IsDynamic() && !model_->IsSingleOp()) {
  48. GE_CHK_STATUS_RET(CheckInputShapeByShapeRange(root_graph_item, args),
  49. "[%s] check input node shape by shape range failed.",
  50. root_graph_item->GetName().c_str());
  51. }
  52. if (context_.global_step != nullptr) {
  53. GE_CHK_RT_RET(rtMemcpyAsync(context_.global_step, sizeof(uint64_t), &context_.iteration,
  54. sizeof(uint64_t), RT_MEMCPY_HOST_TO_DEVICE_EX, context_.stream));
  55. }
  56. auto ret = ExecuteGraphInternal(args);
  57. Cleanup();
  58. RECORD_MODEL_EXECUTION_EVENT(&context_, "[Cleanup] End");
  59. GELOGD("Model executed successfully.");
  60. if (context_.profiler != nullptr) {
  61. context_.profiler->Dump(std::cout);
  62. context_.profiler->Reset();
  63. }
  64. root_graph_executor_->ReleaseContext();
  65. context_.iteration += 1;
  66. if (ret == END_OF_SEQUENCE) {
  67. args.is_eos = true;
  68. } else {
  69. GE_CHK_STATUS_RET(ret, "[Invoke][ExecuteGraphInternal] Failed, ret:%d.", ret);
  70. }
  71. return SUCCESS;
  72. }
  73. Status HybridModelExecutor::ExecuteGraphInternal(HybridModelExecutor::ExecuteArgs &args) {
  74. RECORD_MODEL_EXECUTION_EVENT(&context_, "[InitContext] Start");
  75. GE_CHK_STATUS_RET_NOLOG(ResetExecutionContext(context_));
  76. RECORD_MODEL_EXECUTION_EVENT(&context_, "[InitContext] End");
  77. uint64_t index_id = context_.iteration + 1;
  78. uint64_t model_id = static_cast<uint64_t>(model_->GetModelId());
  79. int32_t device_id = static_cast<int32_t>(device_id_);
  80. auto &prof_mgr = ProfilingManager::Instance();
  81. // tag_id 0 means step begin, 1 meas step end.
  82. if (!model_->IsSingleOp()) {
  83. GE_CHK_STATUS_RET_NOLOG(prof_mgr.ProfileStepInfo(index_id, model_id, 0, stream_, device_id));
  84. }
  85. HYBRID_CHK_STATUS_RET(root_graph_executor_->ExecuteAsync(args.inputs, args.input_desc, args.outputs),
  86. "Failed to execute partitioned call.");
  87. RECORD_MODEL_EXECUTION_EVENT(&context_, "[ExecuteAsync] End");
  88. if (!model_->IsSingleOp()) {
  89. GE_CHK_STATUS_RET_NOLOG(prof_mgr.ProfileStepInfo(index_id, model_id, 1, stream_, device_id));
  90. }
  91. if (!model_->IsSingleOp()) {
  92. Status ret = root_graph_executor_->Synchronize();
  93. if (ret != ge::SUCCESS) {
  94. auto model_manager = ModelManager::GetInstance();
  95. GE_CHECK_NOTNULL(model_manager);
  96. auto exception_infos = model_manager->GetExceptionInfos();
  97. if (!exception_infos.empty()) {
  98. HYBRID_CHK_STATUS_RET(context_.DumpExceptionInfo(exception_infos),
  99. "[Execute][GraphInternal] Dump exception info failed.");
  100. }
  101. if (ret == ge::END_OF_SEQUENCE) {
  102. GELOGD("Got end of sequence");
  103. } else {
  104. GELOGE(ret, "[Execute][GraphInternal] Synchronize failed.");
  105. }
  106. return ret;
  107. }
  108. RECORD_MODEL_EXECUTION_EVENT(&context_, "[Synchronize] End");
  109. }
  110. args.outputs.clear();
  111. HYBRID_CHK_STATUS_RET(root_graph_executor_->GetOutputs(args.outputs, args.output_desc), "Failed to get outputs");
  112. RECORD_MODEL_EXECUTION_EVENT(&context_, "[GetOutput] End");
  113. return SUCCESS;
  114. }
  115. Status HybridModelExecutor::Cleanup() {
  116. GELOGD("Start to cleanup.");
  117. context_.callback_manager->Destroy();
  118. RuntimeInferenceContext::DestroyContext(std::to_string(context_.context_id));
  119. GELOGD("Cleanup successfully.");
  120. return SUCCESS;
  121. }
  122. Status HybridModelExecutor::InitExecutionContext() {
  123. GE_CHK_RT_RET(rtCtxGetCurrent(&context_.rt_context));
  124. GE_CHK_RT_RET(rtCtxSetCurrent(context_.rt_context));
  125. context_.global_step = model_->GetGlobalStep();
  126. context_.stream = stream_;
  127. context_.model = model_;
  128. context_.is_eos_ = false;
  129. context_.session_id = ::ge::GetContext().SessionId();
  130. context_.ge_context = &GetThreadLocalContext();
  131. GELOGD("session id from model = %lu, from context = %lu", model_->GetSessionId(), context_.session_id);
  132. context_.allocator = NpuMemoryAllocator::GetAllocator(device_id_);
  133. GE_CHECK_NOTNULL(context_.allocator);
  134. context_.callback_manager = std::unique_ptr<CallbackManager>(new(std::nothrow)CallbackManager());
  135. GE_CHECK_NOTNULL(context_.callback_manager);
  136. context_.dump_properties = DumpManager::GetInstance().GetDumpProperties(context_.session_id);
  137. const char *profiling_level = std::getenv(kEnvProfilingLevel);
  138. if (profiling_level != nullptr) {
  139. GraphExecutionContext::profiling_level = std::strtol(profiling_level, nullptr, kIntBase);
  140. GELOGD("Got profiling level = %ld", GraphExecutionContext::profiling_level);
  141. if (GraphExecutionContext::profiling_level > 0) {
  142. context_.profiler.reset(new(std::nothrow)HybridProfiler());
  143. GE_CHECK_NOTNULL(context_.profiler);
  144. }
  145. }
  146. if (IsLogEnable(GE_MODULE_NAME, DLOG_DEBUG)) {
  147. context_.trace_enabled = true;
  148. }
  149. return SUCCESS;
  150. }
  151. Status HybridModelExecutor::ResetExecutionContext(GraphExecutionContext &context) {
  152. GE_CHK_STATUS_RET_NOLOG(context.callback_manager->Init());
  153. string ctx_id = std::to_string(context.context_id);
  154. RuntimeInferenceContext::DestroyContext(ctx_id);
  155. GE_CHK_GRAPH_STATUS_RET(RuntimeInferenceContext::CreateContext(ctx_id), "Failed to Destroy RuntimeInferenceContext");
  156. RuntimeInferenceContext *ctx = nullptr;
  157. GE_CHK_GRAPH_STATUS_RET(RuntimeInferenceContext::GetContext(ctx_id, &ctx), "Failed to get context");
  158. for (auto &host_tensor : context.model->GetHostTensors()) {
  159. auto node_id = host_tensor.first;
  160. for (const auto &output_idx_and_tensor : host_tensor.second) {
  161. auto output_idx = output_idx_and_tensor.first;
  162. GELOGD("Preload const host tensor, node_id = %ld, output id = %d", node_id, output_idx);
  163. ctx->SetTensor(node_id, output_idx, output_idx_and_tensor.second.Clone());
  164. }
  165. }
  166. return SUCCESS;
  167. }
  168. Status HybridModelExecutor::CheckInputShapeByShapeRange(const GraphItem *graph_item,
  169. HybridModelExecutor::ExecuteArgs &args) {
  170. GE_CHECK_NOTNULL(graph_item);
  171. auto input_nodes = graph_item->GetInputNodes();
  172. for (size_t i = 0; i < input_nodes.size(); ++i) {
  173. auto &input_node = input_nodes[i];
  174. if (input_node == nullptr) {
  175. GELOGD("[%s] Input[%zu] is not needed by graph, skip it.", graph_item->GetName().c_str(), i);
  176. continue;
  177. }
  178. if (!input_node->is_dynamic) {
  179. GELOGD("[%s] Input[%zu] is not dynamic, skip it.", graph_item->GetName().c_str(), i);
  180. continue;
  181. }
  182. GeTensorDescPtr model_input_desc = input_node->MutableInputDesc(0);
  183. GE_CHECK_NOTNULL(model_input_desc);
  184. std::vector<std::pair<int64_t, int64_t>> shape_range;
  185. if (model_input_desc->GetShapeRange(shape_range) != SUCCESS) {
  186. REPORT_INNER_ERROR("E19999", "[%s] Input[%zu] get shape range failed", graph_item->GetName().c_str(), i);
  187. GELOGE(INTERNAL_ERROR, "[%s] Input[%zu] get shape range failed", graph_item->GetName().c_str(), i);
  188. return INTERNAL_ERROR;
  189. }
  190. if (shape_range.empty()) {
  191. GELOGD("[%s] Input[%zu] shape is not needed to check by shape range, skip it.", graph_item->GetName().c_str(), i);
  192. continue;
  193. }
  194. if (i >= args.input_desc.size()) {
  195. REPORT_INNER_ERROR("E19999", "[%s] Inputs[%zu] is greater than or equal to input desc size[%zu].",
  196. graph_item->GetName().c_str(), i, args.input_desc.size());
  197. GELOGE(INTERNAL_ERROR, "[%s] inputs[%zu] is greater than or equal to input desc size[%zu].",
  198. graph_item->GetName().c_str(), i, args.input_desc.size());
  199. return INTERNAL_ERROR;
  200. }
  201. ConstGeTensorDescPtr args_tensor_desc = args.input_desc[i];
  202. GE_CHECK_NOTNULL(args_tensor_desc);
  203. GeShape shape = args_tensor_desc->GetShape();
  204. if (shape.IsUnknownShape()) {
  205. REPORT_INNER_ERROR("E19999", "[%s] Input desc shape [%zu] designed by user must be static.",
  206. graph_item->GetName().c_str(), i);
  207. GELOGE(INTERNAL_ERROR, "[%s] Input desc shape [%zu] designed by user must be static.",
  208. graph_item->GetName().c_str(), i);
  209. return INTERNAL_ERROR;
  210. }
  211. if (TensorUtils::CheckShapeByShapeRange(shape, shape_range) != SUCCESS) {
  212. GELOGE(PARAM_INVALID, "[Check][InputShape] [%s] check input [%zu] shape failed by shape range.",
  213. graph_item->GetName().c_str(), i);
  214. return PARAM_INVALID;
  215. }
  216. }
  217. return SUCCESS;
  218. }
  219. } // namespace hybrid
  220. } // namespace ge

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