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.

subgraph_executor.cc 18 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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/subgraph_executor.h"
  17. #include "graph/ge_context.h"
  18. #include "hybrid/executor/worker/task_compile_engine.h"
  19. #include "hybrid/executor/worker/execution_engine.h"
  20. #include "hybrid/node_executor/node_executor.h"
  21. namespace ge {
  22. namespace hybrid {
  23. namespace {
  24. constexpr int kDefaultThreadNum = 4;
  25. constexpr int kDataInputIndex = 0;
  26. }
  27. SubgraphExecutor::SubgraphExecutor(const GraphItem *graph_item, GraphExecutionContext *context, bool force_infer_shape)
  28. : graph_item_(graph_item),
  29. context_(context),
  30. force_infer_shape_(force_infer_shape),
  31. pre_run_pool_(kDefaultThreadNum) {
  32. }
  33. SubgraphExecutor::~SubgraphExecutor() {
  34. GELOGD("[%s] SubgraphExecutor destroyed.", graph_item_->GetName().c_str());
  35. }
  36. Status SubgraphExecutor::Init(const std::vector<TensorValue> &inputs,
  37. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  38. subgraph_context_.reset(new(std::nothrow)SubgraphContext(graph_item_));
  39. GE_CHECK_NOTNULL(subgraph_context_);
  40. GE_CHK_STATUS_RET(subgraph_context_->Init(), "[%s] Failed to init subgraph context.", graph_item_->GetName().c_str());
  41. shape_inference_engine_.reset(new(std::nothrow) ShapeInferenceEngine(context_, subgraph_context_.get()));
  42. GE_CHECK_NOTNULL(shape_inference_engine_);
  43. if (graph_item_->IsDynamic()) {
  44. GE_CHK_STATUS_RET(InitInputsForUnknownShape(inputs, input_desc),
  45. "[%s] Failed to set inputs.",
  46. graph_item_->GetName().c_str());
  47. } else {
  48. GE_CHK_STATUS_RET(InitInputsForKnownShape(inputs),
  49. "[%s] Failed to init subgraph executor for known shape subgraph.",
  50. graph_item_->GetName().c_str());
  51. }
  52. return SUCCESS;
  53. }
  54. Status SubgraphExecutor::InitInputsForUnknownShape(const std::vector<TensorValue> &inputs,
  55. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  56. // Number of inputs of parent node should be greater or equal than that of subgraph
  57. auto input_nodes = graph_item_->GetInputNodes();
  58. if (inputs.size() < input_nodes.size()) {
  59. GELOGE(INTERNAL_ERROR, "[%s] Number of inputs [%zu] is not sufficient for subgraph which needs [%zu] inputs.",
  60. graph_item_->GetName().c_str(), inputs.size(), input_nodes.size());
  61. return INTERNAL_ERROR;
  62. }
  63. for (size_t i = 0; i < input_nodes.size(); ++i) {
  64. auto &input_node = input_nodes[i];
  65. if (input_node == nullptr) {
  66. GELOGD("[%s] Input[%zu] is not needed by subgraph, skip it.", graph_item_->GetName().c_str(), i);
  67. continue;
  68. }
  69. auto &input_tensor = inputs[i];
  70. GELOGD("[%s] Set input tensor[%zu] to inputs with index = %d, tensor = %s",
  71. graph_item_->GetName().c_str(),
  72. i,
  73. input_node->input_start,
  74. input_tensor.DebugString().c_str());
  75. GE_CHK_STATUS_RET(subgraph_context_->SetInput(*input_node, kDataInputIndex, input_tensor),
  76. "[%s] Failed to set input tensor[%zu]",
  77. graph_item_->GetName().c_str(),
  78. i);
  79. if (force_infer_shape_ || input_node->is_dynamic) {
  80. GELOGD("[%s] Start to update input[%zu] for subgraph data node.", graph_item_->GetName().c_str(), i);
  81. GE_CHECK_LE(i + 1, input_desc.size());
  82. const auto &tensor_desc = input_desc[i];
  83. GE_CHECK_NOTNULL(tensor_desc);
  84. auto node_state = subgraph_context_->GetOrCreateNodeState(input_node);
  85. GE_CHECK_NOTNULL(node_state);
  86. node_state->GetShapeInferenceState().UpdateInputShape(0, tensor_desc->GetOriginShape(), tensor_desc->GetShape());
  87. }
  88. }
  89. GELOGD("[%s] Done setting inputs.", graph_item_->GetName().c_str());
  90. return SUCCESS;
  91. }
  92. Status SubgraphExecutor::InitInputsForKnownShape(const std::vector<TensorValue> &inputs) {
  93. auto &input_index_mapping = graph_item_->GetInputIndexMapping();
  94. for (size_t i = 0; i < input_index_mapping.size(); ++i) {
  95. auto &parent_input_index = input_index_mapping[i];
  96. if (static_cast<size_t>(parent_input_index) >= inputs.size()) {
  97. GELOGE(INTERNAL_ERROR,
  98. "[%s] Number of inputs [%zu] is not sufficient for subgraph which needs at lease [%d] inputs",
  99. graph_item_->GetName().c_str(),
  100. inputs.size(),
  101. parent_input_index + 1);
  102. return INTERNAL_ERROR;
  103. }
  104. auto &input_tensor = inputs[parent_input_index];
  105. subgraph_context_->SetInput(static_cast<int>(i), input_tensor);
  106. GELOGD("[%s] Set input tensor[%zu] with inputs with index = %d, tensor = %s",
  107. graph_item_->GetName().c_str(),
  108. i,
  109. parent_input_index,
  110. input_tensor.DebugString().c_str());
  111. }
  112. return SUCCESS;
  113. }
  114. Status SubgraphExecutor::ExecuteAsync(const std::vector<TensorValue> &inputs,
  115. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  116. GELOGD("[%s] is dynamic = %s", graph_item_->GetName().c_str(), graph_item_->IsDynamic() ? "true" : "false");
  117. GE_CHK_STATUS_RET(Init(inputs, input_desc), "[%s] Failed to init executor.", graph_item_->GetName().c_str());
  118. if (!graph_item_->IsDynamic()) {
  119. return ExecuteAsyncForKnownShape(inputs);
  120. }
  121. GE_CHK_STATUS_RET(ScheduleTasks(), "[%s] Failed to execute tasks.", graph_item_->GetName().c_str());
  122. GELOGD("[%s] Done executing subgraph successfully.", graph_item_->GetName().c_str());
  123. return SUCCESS;
  124. }
  125. Status SubgraphExecutor::ExecuteAsyncForKnownShape(const std::vector<TensorValue> &inputs) {
  126. GELOGD("[%s] subgraph is not dynamic.", graph_item_->GetName().c_str());
  127. if (graph_item_->GetAllNodes().size() != 1) {
  128. GELOGE(INTERNAL_ERROR,
  129. "[%s] Invalid known shape subgraph. node size = %zu",
  130. graph_item_->GetName().c_str(),
  131. graph_item_->GetAllNodes().size());
  132. return INTERNAL_ERROR;
  133. }
  134. auto node_item = graph_item_->GetAllNodes()[0];
  135. GE_CHECK_NOTNULL(node_item);
  136. auto node_state = subgraph_context_->GetOrCreateNodeState(node_item);
  137. GE_CHECK_NOTNULL(node_state);
  138. node_state->SetKernelTask(node_item->kernel_task);
  139. known_shape_task_context_ = TaskContext::Create(*node_item, context_, subgraph_context_.get());
  140. GE_CHECK_NOTNULL(known_shape_task_context_);
  141. GE_CHK_STATUS_RET(ExecutionEngine::ExecuteAsync(*node_state, known_shape_task_context_, *context_),
  142. "[%s] Failed to execute node [%s] for known subgraph.",
  143. graph_item_->GetName().c_str(),
  144. known_shape_task_context_->GetNodeName());
  145. GELOGD("[%s] Done execute non-dynamic subgraph successfully.", graph_item_->GetName().c_str());
  146. return SUCCESS;
  147. }
  148. Status SubgraphExecutor::ExecuteAsync(TaskContext &task_context) {
  149. std::vector<TensorValue> inputs;
  150. std::vector<ConstGeTensorDescPtr> input_desc;
  151. for (int i = 0; i < task_context.NumInputs(); ++i) {
  152. auto tensor = task_context.GetInput(i);
  153. GE_CHECK_NOTNULL(tensor);
  154. inputs.emplace_back(*tensor);
  155. input_desc.emplace_back(task_context.GetInputDesc(i));
  156. }
  157. GE_CHK_STATUS_RET(ExecuteAsync(inputs, input_desc),
  158. "[%s] Failed to execute subgraph.",
  159. graph_item_->GetName().c_str());
  160. GE_CHK_STATUS_RET(SetOutputsToParentNode(task_context),
  161. "[%s] Failed to set output shapes to parent node.",
  162. graph_item_->GetName().c_str());
  163. return SUCCESS;
  164. }
  165. Status SubgraphExecutor::PrepareNodes() {
  166. GELOGD("[%s] Start to prepare nodes. force infer shape = %s.",
  167. graph_item_->GetName().c_str(),
  168. force_infer_shape_ ? "true" : "false");
  169. auto &all_nodes = graph_item_->GetAllNodes();
  170. for (auto all_node : all_nodes) {
  171. auto &node_item = *all_node;
  172. // for while op
  173. if (force_infer_shape_ && !node_item.is_dynamic) {
  174. GELOGD("[%s] Force infer shape is set, updating node to dynamic.", node_item.NodeName().c_str());
  175. auto &mutable_node_item = const_cast<NodeItem &>(node_item);
  176. mutable_node_item.SetToDynamic();
  177. }
  178. GELOGD("[%s] Start to prepare node [%s].", graph_item_->GetName().c_str(), node_item.NodeName().c_str());
  179. auto node_state = subgraph_context_->GetOrCreateNodeState(&node_item);
  180. GE_CHECK_NOTNULL(node_state);
  181. auto p_node_state = node_state.get();
  182. if (node_item.node_type == NETOUTPUT) {
  183. // Wait for all inputs become valid
  184. // after PrepareNodes returned. all output tensors and shapes are valid
  185. GE_CHK_STATUS_RET_NOLOG(p_node_state->GetShapeInferenceState().AwaitShapesReady(*context_));
  186. GE_CHK_STATUS_RET_NOLOG(p_node_state->AwaitInputTensors(*context_));
  187. continue;
  188. }
  189. // only do shape inference and compilation for nodes with dynamic shapes.
  190. if (node_item.is_dynamic) {
  191. auto prepare_future = pre_run_pool_.commit([this, p_node_state]() -> Status {
  192. GetContext().SetSessionId(context_->session_id);
  193. GE_CHK_STATUS_RET_NOLOG(InferShape(shape_inference_engine_.get(), *p_node_state));
  194. return PrepareForExecution(context_, *p_node_state);
  195. });
  196. p_node_state->SetPrepareFuture(std::move(prepare_future));
  197. } else {
  198. GELOGD("[%s] Skipping shape inference and compilation for node with static shape.", node_item.NodeName().c_str());
  199. if (node_item.kernel_task == nullptr) {
  200. GELOGW("[%s] Node of static shape got no task.", node_item.NodeName().c_str());
  201. GE_CHK_STATUS_RET(TaskCompileEngine::Compile(*p_node_state, context_),
  202. "[%s] Failed to create task.", p_node_state->GetName().c_str());
  203. } else {
  204. node_state->SetKernelTask(node_item.kernel_task);
  205. }
  206. }
  207. if (!ready_queue_.Push(p_node_state)) {
  208. GELOGE(INTERNAL_ERROR, "[%s] Error occurs while launching tasks. quit from preparing nodes.",
  209. graph_item_->GetName().c_str());
  210. return INTERNAL_ERROR;
  211. }
  212. GELOGD("[%s] Push node [%s] to queue.", graph_item_->GetName().c_str(), node_item.NodeName().c_str());
  213. }
  214. return SUCCESS;
  215. }
  216. Status SubgraphExecutor::InferShape(ShapeInferenceEngine *shape_inference_engine, NodeState &node_state) {
  217. const auto &node_item = *node_state.GetNodeItem();
  218. GE_CHK_STATUS_RET(shape_inference_engine->InferShape(node_state),
  219. "[%s] Failed to InferShape.", node_state.GetName().c_str());
  220. GE_CHK_STATUS_RET(shape_inference_engine->PropagateOutputShapes(node_item),
  221. "[%s] Failed to PropagateOutputShapes.", node_state.GetName().c_str());
  222. return SUCCESS;
  223. }
  224. Status SubgraphExecutor::PrepareForExecution(GraphExecutionContext *ctx, NodeState &node_state) {
  225. auto &node_item = *node_state.GetNodeItem();
  226. if (node_item.kernel_task == nullptr) {
  227. GE_CHK_STATUS_RET(TaskCompileEngine::Compile(node_state, ctx),
  228. "Failed to create task for node[%s]", node_state.GetName().c_str());
  229. } else {
  230. node_state.SetKernelTask(node_item.kernel_task);
  231. }
  232. GELOGD("[%s] Start to invoke CalcOpRunningParam.", node_item.NodeName().c_str());
  233. RECORD_COMPILE_EVENT(ctx, node_item.NodeName().c_str(), "[CalcOpRunningParam] Start");
  234. GE_CHK_STATUS_RET(NodeExecutorManager::GetInstance().CalcOpRunningParam(*node_item.node),
  235. "[%s] Failed to invoke CalcOpRunningParam.", node_item.NodeName().c_str());
  236. RECORD_COMPILE_EVENT(ctx, node_item.NodeName().c_str(), "[CalcOpRunningParam] End");
  237. GELOGD("[%s] Done invoking CalcOpRunningParam successfully.", node_item.NodeName().c_str());
  238. return SUCCESS;
  239. }
  240. Status SubgraphExecutor::LaunchTasks() {
  241. while (true) {
  242. NodeState *node_state = nullptr;
  243. if (!ready_queue_.Pop(node_state)) {
  244. GELOGE(INTERNAL_ERROR, "[%s] Failed to pop node.", graph_item_->GetName().c_str());
  245. return INTERNAL_ERROR;
  246. }
  247. if (node_state == nullptr) {
  248. GELOGD("[%s] Got EOF from queue.", graph_item_->GetName().c_str());
  249. return SUCCESS;
  250. }
  251. GE_CHK_STATUS_RET_NOLOG(node_state->WaitForPrepareDone());
  252. GELOGD("[%s] Start to execute.", node_state->GetName().c_str());
  253. auto task_context = TaskContext::Create(*node_state->GetNodeItem(), context_, subgraph_context_.get());
  254. GE_CHECK_NOTNULL(task_context);
  255. task_context->SetForceInferShape(force_infer_shape_);
  256. auto shared_task_context = std::shared_ptr<TaskContext>(task_context.release());
  257. GE_CHK_STATUS_RET(ExecutionEngine::ExecuteAsync(*node_state, shared_task_context, *context_),
  258. "[%s] Execute node failed.",
  259. node_state->GetName().c_str());
  260. GELOGD("[%s] Done executing node successfully.", node_state->GetName().c_str());
  261. }
  262. }
  263. Status SubgraphExecutor::ScheduleTasks() {
  264. GELOGD("[%s] Start to schedule prepare workers.", graph_item_->GetName().c_str());
  265. auto prepare_future = std::async(std::launch::async, [&]() -> Status {
  266. GetContext().SetSessionId(context_->session_id);
  267. auto ret = PrepareNodes();
  268. ready_queue_.Push(nullptr);
  269. return ret;
  270. });
  271. GELOGD("[%s] Start to execute subgraph.", graph_item_->GetName().c_str());
  272. auto ret = LaunchTasks();
  273. if (ret != SUCCESS) {
  274. GELOGE(ret, "[%s] Failed to execute subgraph.", graph_item_->GetName().c_str());
  275. subgraph_context_->OnError(ret);
  276. context_->SetErrorCode(ret);
  277. ready_queue_.Stop();
  278. prepare_future.wait();
  279. return ret;
  280. }
  281. GE_CHK_STATUS_RET(prepare_future.get(),
  282. "[%s] Error occurred in task preparation.",
  283. graph_item_->GetName().c_str());
  284. GELOGD("[%s] Done launching all tasks successfully.", graph_item_->GetName().c_str());
  285. return SUCCESS;
  286. }
  287. Status SubgraphExecutor::GetOutputs(vector<TensorValue> &outputs) {
  288. return subgraph_context_->GetOutputs(outputs);
  289. }
  290. Status SubgraphExecutor::GetOutputs(vector<TensorValue> &outputs, std::vector<ConstGeTensorDescPtr> &output_desc) {
  291. GE_CHK_STATUS_RET(GetOutputs(outputs), "[%s] Failed to get output tensors.", graph_item_->GetName().c_str());
  292. // copy output data from op to designated position
  293. GE_CHK_STATUS_RET(graph_item_->GetOutputDescList(output_desc),
  294. "[%s] Failed to get output tensor desc.",
  295. graph_item_->GetName().c_str());
  296. if (outputs.size() != output_desc.size()) {
  297. GELOGE(INTERNAL_ERROR,
  298. "Number of output tensors(%zu) mismatch number of output tensor desc(%zu).",
  299. outputs.size(),
  300. output_desc.size());
  301. return INTERNAL_ERROR;
  302. }
  303. return SUCCESS;
  304. }
  305. Status SubgraphExecutor::Synchronize() {
  306. GELOGD("[%s] Synchronize start.", graph_item_->GetName().c_str());
  307. GE_CHK_RT_RET(rtStreamSynchronize(context_->stream));
  308. GELOGD("[%s] Done synchronizing successfully.", graph_item_->GetName().c_str());
  309. return SUCCESS;
  310. }
  311. Status SubgraphExecutor::SetOutputsToParentNode(TaskContext &task_context) {
  312. // get output tensors and tensor desc list
  313. std::vector<TensorValue> outputs;
  314. std::vector<ConstGeTensorDescPtr> output_desc_list;
  315. GE_CHK_STATUS_RET(subgraph_context_->GetOutputs(outputs),
  316. "[%s] Failed to get output tensors.",
  317. graph_item_->GetName().c_str());
  318. GE_CHK_STATUS_RET(graph_item_->GetOutputDescList(output_desc_list),
  319. "[%s] Failed to get output tensor desc.",
  320. graph_item_->GetName().c_str());
  321. if (outputs.size() != output_desc_list.size()) {
  322. GELOGE(INTERNAL_ERROR, "[%s] num output tensors = %zu, num output tensor desc = %zu",
  323. graph_item_->GetName().c_str(),
  324. outputs.size(),
  325. output_desc_list.size());
  326. return INTERNAL_ERROR;
  327. }
  328. // mapping to parent task context
  329. for (size_t i = 0; i < outputs.size(); ++i) {
  330. int parent_output_index = graph_item_->GetParentOutputIndex(i);
  331. GE_CHECK_GE(parent_output_index, 0);
  332. // update tensor
  333. GELOGD("[%s] Updating output[%zu] to parent output[%d]",
  334. graph_item_->GetName().c_str(),
  335. i,
  336. parent_output_index);
  337. GELOGD("[%s] Updating output tensor, index = %d, tensor = %s",
  338. graph_item_->GetName().c_str(),
  339. parent_output_index,
  340. outputs[i].DebugString().c_str());
  341. GE_CHK_STATUS_RET(task_context.SetOutput(parent_output_index, outputs[i]));
  342. // updating shapes. dynamic format/dtype is not supported.
  343. // It should be noted that even the subgraph is of known shape, it is also necessary to update parent output desc,
  344. // for instance, IfOp may have two known-shaped subgraphs of different output shapes
  345. const auto &output_desc = output_desc_list[i];
  346. auto parent_output_desc = task_context.MutableOutputDesc(parent_output_index);
  347. GE_CHECK_NOTNULL(parent_output_desc);
  348. GELOGD("[%s] Updating output shape[%d] from [%s] to [%s]",
  349. graph_item_->GetName().c_str(),
  350. parent_output_index,
  351. parent_output_desc->MutableShape().ToString().c_str(),
  352. output_desc->GetShape().ToString().c_str());
  353. parent_output_desc->SetShape(output_desc->GetShape());
  354. GELOGD("[%s] Updating output original shape[%d] from [%s] to [%s]",
  355. graph_item_->GetName().c_str(),
  356. parent_output_index,
  357. parent_output_desc->GetOriginShape().ToString().c_str(),
  358. output_desc->GetOriginShape().ToString().c_str());
  359. parent_output_desc->SetOriginShape(output_desc->GetOriginShape());
  360. }
  361. return SUCCESS;
  362. }
  363. } // namespace hybrid
  364. } // namespace ge

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