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

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

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