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

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

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