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

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