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

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