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 31 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 kDefaultQueueSize = 16;
  26. constexpr int kDataInputIndex = 0;
  27. }
  28. SubgraphExecutor::SubgraphExecutor(const GraphItem *graph_item, GraphExecutionContext *context, bool force_infer_shape)
  29. : graph_item_(graph_item),
  30. context_(context),
  31. force_infer_shape_(force_infer_shape),
  32. pre_run_pool_(kDefaultThreadNum),
  33. ready_queue_(kDefaultQueueSize) {
  34. }
  35. SubgraphExecutor::~SubgraphExecutor() {
  36. GELOGD("[%s] SubgraphExecutor destroyed.", graph_item_->GetName().c_str());
  37. }
  38. Status SubgraphExecutor::Init(const std::vector<TensorValue> &inputs,
  39. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  40. subgraph_context_.reset(new(std::nothrow)SubgraphContext(graph_item_, context_));
  41. GE_CHECK_NOTNULL(subgraph_context_);
  42. GE_CHK_STATUS_RET(subgraph_context_->Init(),
  43. "[Init][SubgraphContext][%s] Failed to init subgraph context.", graph_item_->GetName().c_str());
  44. shape_inference_engine_.reset(new(std::nothrow) ShapeInferenceEngine(context_, subgraph_context_.get()));
  45. GE_CHECK_NOTNULL(shape_inference_engine_);
  46. if (graph_item_->IsDynamic()) {
  47. GE_CHK_STATUS_RET(InitInputsForUnknownShape(inputs, input_desc),
  48. "[%s] Failed to set inputs.",
  49. graph_item_->GetName().c_str());
  50. } else {
  51. GE_CHK_STATUS_RET(InitInputsForKnownShape(inputs),
  52. "[Invoke][InitInputsForKnownShape][%s] Failed to init subgraph executor for known shape subgraph.",
  53. graph_item_->GetName().c_str());
  54. }
  55. return SUCCESS;
  56. }
  57. Status SubgraphExecutor::InitInputsForUnknownShape(const std::vector<TensorValue> &inputs,
  58. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  59. // Number of inputs of parent node should be greater or equal than that of subgraph
  60. auto input_nodes = graph_item_->GetInputNodes();
  61. if (inputs.size() < input_nodes.size()) {
  62. GELOGE(INTERNAL_ERROR,
  63. "[Check][Size][%s] Number of inputs [%zu] is not sufficient for subgraph which needs [%zu] inputs.",
  64. graph_item_->GetName().c_str(), inputs.size(), input_nodes.size());
  65. REPORT_INNER_ERROR("E19999",
  66. "[%s] Number of inputs [%zu] is not sufficient for subgraph which needs [%zu] inputs.",
  67. graph_item_->GetName().c_str(), inputs.size(), input_nodes.size());
  68. return INTERNAL_ERROR;
  69. }
  70. for (size_t i = 0; i < input_nodes.size(); ++i) {
  71. auto &input_node = input_nodes[i];
  72. if (input_node == nullptr) {
  73. GELOGD("[%s] Input[%zu] is not needed by subgraph, skip it.", graph_item_->GetName().c_str(), i);
  74. continue;
  75. }
  76. auto &input_tensor = inputs[i];
  77. GELOGD("[%s] Set input tensor[%zu] to inputs with index = %d, tensor = %s",
  78. graph_item_->GetName().c_str(),
  79. i,
  80. input_node->input_start,
  81. input_tensor.DebugString().c_str());
  82. GE_CHK_STATUS_RET(subgraph_context_->SetInput(*input_node, kDataInputIndex, input_tensor),
  83. "[Invoke][SetInput] failed for grap_item[%s] input tensor[%zu]",
  84. graph_item_->GetName().c_str(), i);
  85. if (force_infer_shape_ || input_node->is_dynamic) {
  86. GELOGD("[%s] Start to update input[%zu] for subgraph data node.", graph_item_->GetName().c_str(), i);
  87. GE_CHECK_LE(i + 1, input_desc.size());
  88. const auto &tensor_desc = input_desc[i];
  89. GE_CHECK_NOTNULL(tensor_desc);
  90. auto node_state = subgraph_context_->GetOrCreateNodeState(input_node);
  91. GE_CHECK_NOTNULL(node_state);
  92. node_state->GetShapeInferenceState().UpdateInputShape(0, *tensor_desc);
  93. auto op_desc = input_node->GetOpDesc();
  94. GE_CHECK_NOTNULL(op_desc);
  95. auto output_desc = op_desc->MutableOutputDesc(kDataInputIndex);
  96. GE_CHECK_NOTNULL(output_desc);
  97. output_desc->SetShape(tensor_desc->GetShape());
  98. output_desc->SetOriginShape(tensor_desc->GetOriginShape());
  99. output_desc->SetDataType(tensor_desc->GetDataType());
  100. node_state->SetSkipInferShape(true);
  101. }
  102. }
  103. GELOGD("[%s] Done setting inputs.", graph_item_->GetName().c_str());
  104. return SUCCESS;
  105. }
  106. Status SubgraphExecutor::InitInputsForKnownShape(const std::vector<TensorValue> &inputs) {
  107. auto &input_index_mapping = graph_item_->GetInputIndexMapping();
  108. for (size_t i = 0; i < input_index_mapping.size(); ++i) {
  109. auto &parent_input_index = input_index_mapping[i];
  110. if (static_cast<size_t>(parent_input_index) >= inputs.size()) {
  111. GELOGE(INTERNAL_ERROR, "[Check][Size][%s] Number of inputs [%zu] is not sufficient for subgraph"
  112. "which needs at lease [%d] inputs", graph_item_->GetName().c_str(), inputs.size(),
  113. parent_input_index + 1);
  114. REPORT_INNER_ERROR("E19999", "[%s] Number of inputs [%zu] is not sufficient for subgraph"
  115. "which needs at lease [%d] inputs",
  116. graph_item_->GetName().c_str(), inputs.size(), parent_input_index + 1);
  117. return INTERNAL_ERROR;
  118. }
  119. auto &input_tensor = inputs[parent_input_index];
  120. subgraph_context_->SetInput(static_cast<int>(i), input_tensor);
  121. GELOGD("[%s] Set input tensor[%zu] with inputs with index = %d, tensor = %s",
  122. graph_item_->GetName().c_str(),
  123. i,
  124. parent_input_index,
  125. input_tensor.DebugString().c_str());
  126. }
  127. return SUCCESS;
  128. }
  129. Status SubgraphExecutor::ExecuteAsync(const std::vector<TensorValue> &inputs,
  130. const std::vector<ConstGeTensorDescPtr> &input_desc,
  131. const std::vector<TensorValue> &outputs) {
  132. GELOGD("[%s] is dynamic = %s", graph_item_->GetName().c_str(), graph_item_->IsDynamic() ? "true" : "false");
  133. GE_CHK_STATUS_RET(Init(inputs, input_desc), "[Invoke][Init]failed for [%s].", graph_item_->GetName().c_str());
  134. if (!outputs.empty()) {
  135. GE_CHK_STATUS_RET(EnableOutputZeroCopy(outputs),
  136. "[Invoke][EnableOutputZeroCopy] Failed by user provided outputs.");
  137. }
  138. if (!graph_item_->IsDynamic()) {
  139. return ExecuteAsyncForKnownShape(inputs);
  140. }
  141. HYBRID_CHK_STATUS_RET(ScheduleTasks(), "[%s] Failed to execute tasks.", graph_item_->GetName().c_str());
  142. GELOGD("[%s] Done executing subgraph successfully.", graph_item_->GetName().c_str());
  143. return SUCCESS;
  144. }
  145. Status SubgraphExecutor::ExecuteAsync(const std::vector<TensorValue> &inputs,
  146. const std::vector<ConstGeTensorDescPtr> &input_desc) {
  147. return ExecuteAsync(inputs, input_desc, {});
  148. }
  149. Status SubgraphExecutor::ExecuteAsyncForKnownShape(const std::vector<TensorValue> &inputs) {
  150. GELOGD("[%s] subgraph is not dynamic.", graph_item_->GetName().c_str());
  151. if (graph_item_->GetAllNodes().size() != 1) {
  152. REPORT_INNER_ERROR("E19999", "[%s] Invalid known shape subgraph. node size = %zu",
  153. graph_item_->GetName().c_str(), graph_item_->GetAllNodes().size());
  154. GELOGE(INTERNAL_ERROR, "[Check][Size][%s] Invalid known shape subgraph. node size = %zu",
  155. graph_item_->GetName().c_str(), graph_item_->GetAllNodes().size());
  156. return INTERNAL_ERROR;
  157. }
  158. auto node_item = graph_item_->GetAllNodes()[0];
  159. GE_CHECK_NOTNULL(node_item);
  160. auto node_state = subgraph_context_->GetOrCreateNodeState(node_item);
  161. GE_CHECK_NOTNULL(node_state);
  162. node_state->SetKernelTask(node_item->kernel_task);
  163. std::function<void()> callback;
  164. GE_CHK_STATUS_RET_NOLOG(InitCallback(node_state.get(), callback));
  165. HYBRID_CHK_STATUS_RET(ExecutionEngine::ExecuteAsync(*node_state, node_state->GetTaskContext(), *context_, callback),
  166. "[%s] Failed to execute node [%s] for known subgraph.",
  167. graph_item_->GetName().c_str(),
  168. node_state->GetName().c_str());
  169. GELOGD("[%s] Done execute non-dynamic subgraph successfully.", graph_item_->GetName().c_str());
  170. return SUCCESS;
  171. }
  172. Status SubgraphExecutor::ExecuteAsync(TaskContext &task_context) {
  173. std::vector<TensorValue> inputs;
  174. std::vector<ConstGeTensorDescPtr> input_desc;
  175. for (int i = 0; i < task_context.NumInputs(); ++i) {
  176. auto tensor = task_context.GetInput(i);
  177. GE_CHECK_NOTNULL(tensor);
  178. inputs.emplace_back(*tensor);
  179. input_desc.emplace_back(task_context.GetInputDesc(i));
  180. }
  181. GE_CHK_STATUS_RET(ExecuteAsync(inputs, input_desc), "[Invoke][ExecuteAsync] failed for [%s].",
  182. graph_item_->GetName().c_str());
  183. GE_CHK_STATUS_RET(SetOutputsToParentNode(task_context),
  184. "[Invoke][SetOutputsToParentNode][%s] Failed to set output shapes to parent node.",
  185. graph_item_->GetName().c_str());
  186. return SUCCESS;
  187. }
  188. BlockingQueue<const NodeItem *> &SubgraphExecutor::GetPrepareQueue(int group) {
  189. std::lock_guard<std::mutex> lk(mu_);
  190. return prepare_queues_[group];
  191. }
  192. Status SubgraphExecutor::NodeEnqueue(NodeState *node_state) {
  193. if (!ready_queue_.Push(node_state)) {
  194. if (context_->is_eos_) {
  195. GELOGD("Got end of sequence");
  196. return SUCCESS;
  197. }
  198. GELOGE(INTERNAL_ERROR, "[Check][State][%s] Error occurs while launching tasks. quit from preparing nodes.",
  199. graph_item_->GetName().c_str());
  200. REPORT_INNER_ERROR("E19999", "[%s] Error occurs while launching tasks. quit from preparing nodes.",
  201. graph_item_->GetName().c_str());
  202. return INTERNAL_ERROR;
  203. }
  204. GELOGD("[%s] Push node [%s] to queue.", graph_item_->GetName().c_str(), node_state->GetName().c_str());
  205. return SUCCESS;
  206. }
  207. Status SubgraphExecutor::PrepareNode(const NodeItem &node_item, int group) {
  208. GELOGD("[%s] Start to prepare node [%s].", graph_item_->GetName().c_str(), node_item.NodeName().c_str());
  209. // for while op
  210. if (force_infer_shape_ && !node_item.is_dynamic) {
  211. GELOGD("[%s] Force infer shape is set, updating node to dynamic.", node_item.NodeName().c_str());
  212. auto &mutable_node_item = const_cast<NodeItem &>(node_item);
  213. mutable_node_item.SetToDynamic();
  214. }
  215. auto node_state = subgraph_context_->GetOrCreateNodeState(&node_item);
  216. GE_CHECK_NOTNULL(node_state);
  217. auto p_node_state = node_state.get();
  218. if (node_item.node_type == NETOUTPUT) {
  219. GE_CHK_STATUS_RET_NOLOG(NodeEnqueue(p_node_state));
  220. return AfterPrepared(p_node_state);
  221. }
  222. // only do shape inference and compilation for nodes with dynamic shapes.
  223. if (node_item.is_dynamic) {
  224. auto prepare_future = pre_run_pool_.commit([this, p_node_state]() -> Status {
  225. GetContext().SetSessionId(context_->session_id);
  226. GetContext().SetContextId(context_->context_id);
  227. GE_CHK_STATUS_RET_NOLOG(InferShape(shape_inference_engine_.get(), *p_node_state));
  228. GE_CHK_STATUS_RET_NOLOG(PrepareForExecution(context_, *p_node_state));
  229. return AfterPrepared(p_node_state);
  230. });
  231. p_node_state->SetPrepareFuture(std::move(prepare_future));
  232. return NodeEnqueue(p_node_state);
  233. } else {
  234. GELOGD("[%s] Skipping shape inference and compilation for node with static shape.",
  235. node_item.NodeName().c_str());
  236. if (node_item.kernel_task == nullptr) {
  237. GELOGW("[%s] Node of static shape got no task.", node_item.NodeName().c_str());
  238. GE_CHK_STATUS_RET(TaskCompileEngine::Compile(*p_node_state, context_),
  239. "[Invoke][Compile] failed for [%s].", p_node_state->GetName().c_str());
  240. } else {
  241. node_state->SetKernelTask(node_item.kernel_task);
  242. }
  243. const auto &task = node_state->GetKernelTask();
  244. if (task == nullptr) {
  245. GELOGE(INTERNAL_ERROR, "[Get][KernelTask] failed for[%s], NodeTask is null.", node_state->GetName().c_str());
  246. REPORT_CALL_ERROR("E19999", "GetKernelTask failed for %s, nodetask is null.", node_state->GetName().c_str());
  247. return INTERNAL_ERROR;
  248. }
  249. GE_CHK_STATUS_RET_NOLOG(NodeEnqueue(p_node_state));
  250. return AfterPrepared(p_node_state);
  251. }
  252. }
  253. Status SubgraphExecutor::PrepareNodes(int group) {
  254. const size_t node_size = graph_item_->GetNodeSize(group);
  255. GELOGD("[%s] Start to prepare nodes. group = %d, size = %zu", graph_item_->GetName().c_str(), group, node_size);
  256. if (!graph_item_->HasCtrlFlowOp()) {
  257. for (const auto &node_item : graph_item_->GetAllNodes(group)) {
  258. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] Start");
  259. GE_CHK_STATUS_RET(PrepareNode(*node_item, group), "[%s] failed to prepare task.", node_item->NodeName().c_str());
  260. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] End");
  261. }
  262. GELOGD("[%s] Done preparing nodes successfully.", graph_item_->GetName().c_str());
  263. return SUCCESS;
  264. }
  265. // Initialize the ready queue
  266. size_t node_count = 0;
  267. bool node_complete = false;
  268. for (const auto &node_item : graph_item_->GetRootNodes(group)) {
  269. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] Start");
  270. GE_CHK_STATUS_RET(PrepareNode(*node_item, group), "[%s] failed to prepare task.", node_item->NodeName().c_str());
  271. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] End");
  272. node_complete = node_item->NodeType() == NETOUTPUT;
  273. node_count++;
  274. }
  275. GELOGD("[%s] Done preparing root nodes.", graph_item_->GetName().c_str());
  276. BlockingQueue<const NodeItem *> &prepare_queue = GetPrepareQueue(group);
  277. while (((group != -1) && (node_count < node_size)) || ((group == -1) && !node_complete)) {
  278. const NodeItem *node_item = nullptr;
  279. if (!prepare_queue.Pop(node_item)) {
  280. if (context_->is_eos_) {
  281. GELOGD("[%s] Got end of sequence.", graph_item_->GetName().c_str());
  282. break;
  283. }
  284. if (context_->GetStatus() != SUCCESS) {
  285. GELOGD("[%s] Graph execution Got failed.", graph_item_->GetName().c_str());
  286. return SUCCESS;
  287. }
  288. GELOGE(INTERNAL_ERROR, "[%s] failed to pop node.", graph_item_->GetName().c_str());
  289. return INTERNAL_ERROR;
  290. }
  291. if (node_item == nullptr) {
  292. GELOGD("[%s] Got EOF from queue.", graph_item_->GetName().c_str());
  293. break;
  294. }
  295. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] Start");
  296. GE_CHK_STATUS_RET(PrepareNode(*node_item, group), "[%s] failed to prepare task.", node_item->NodeName().c_str());
  297. RECORD_EXECUTION_EVENT(context_, node_item->NodeName().c_str(), "[PrepareNode] End");
  298. node_complete = node_item->NodeType() == NETOUTPUT;
  299. node_count++;
  300. }
  301. GELOGD("[%s] Done preparing nodes successfully.", graph_item_->GetName().c_str());
  302. return SUCCESS;
  303. }
  304. Status SubgraphExecutor::NodeScheduled(NodeState *node_state) {
  305. GELOGD("Graph[%s] After [%s] scheduled, data size: %zu, ctrl size: %zu, switch index: %d, merge index: %d",
  306. graph_item_->GetName().c_str(), node_state->GetName().c_str(),
  307. node_state->GetNodeItem()->data_send_.size(), node_state->GetNodeItem()->ctrl_send_.size(),
  308. node_state->GetSwitchIndex(), node_state->GetMergeIndex());
  309. auto future = pre_run_pool_.commit([this, node_state]() -> Status {
  310. RECORD_CALLBACK_EVENT(context_, node_state->GetName().c_str(), "[NodeScheduled] Start");
  311. std::function<void(const NodeItem *)> callback = [&](const NodeItem *node_item) {
  312. const auto &node_name = node_item->node_name;
  313. int group = (node_state->GetGroup() != -1) ? node_item->group : -1;
  314. GELOGI("After [%s] scheduled, [%s] is ready for prepare.", node_state->GetName().c_str(), node_name.c_str());
  315. BlockingQueue<const NodeItem *> &prepare_queue = GetPrepareQueue(group);
  316. if (!prepare_queue.Push(node_item)) {
  317. if (!context_->is_eos_) {
  318. GELOGE(INTERNAL_ERROR, "[Check][State][%s] error occurs when push to queue.", graph_item_->GetName().c_str());
  319. REPORT_INNER_ERROR("E19999", "[%s] error occurs when push to queue.", graph_item_->GetName().c_str());
  320. }
  321. }
  322. };
  323. GE_CHK_STATUS_RET_NOLOG(node_state->NodeScheduled(callback));
  324. RECORD_CALLBACK_EVENT(context_, node_state->GetName().c_str(), "[NodeScheduled] End");
  325. return SUCCESS;
  326. });
  327. node_state->SetScheduleFuture(std::move(future));
  328. if (schedule_queue_.Push(node_state)) {
  329. return SUCCESS;
  330. }
  331. if (context_->is_eos_) {
  332. GELOGD("[%s] Got end of sequence", graph_item_->GetName().c_str());
  333. return SUCCESS;
  334. }
  335. GELOGE(INTERNAL_ERROR, "[Check][State][%s] error occurs when push to queue.", graph_item_->GetName().c_str());
  336. REPORT_INNER_ERROR("E19999", "[%s] error occurs when push to queue.", graph_item_->GetName().c_str());
  337. return INTERNAL_ERROR;
  338. }
  339. Status SubgraphExecutor::AfterPrepared(NodeState *node_state) {
  340. if (!graph_item_->HasCtrlFlowOp()) {
  341. return SUCCESS;
  342. }
  343. if (node_state->IsShapeDependence()) {
  344. return SUCCESS;
  345. }
  346. // Not control flow node, propagate state.
  347. return NodeScheduled(node_state);
  348. }
  349. void SubgraphExecutor::AfterExecuted(NodeState *node_state) {
  350. if (!node_state->IsShapeDependence()) {
  351. return;
  352. }
  353. // For control flow node, propagate state.
  354. auto error = NodeScheduled(node_state);
  355. if (error != SUCCESS) {
  356. auto task_context = node_state->GetTaskContext();
  357. task_context->OnError(error);
  358. }
  359. }
  360. void SubgraphExecutor::OnNodeDone(NodeState *node_state) {
  361. auto task_context = node_state->GetTaskContext();
  362. NodeDoneCallback cb(context_, task_context);
  363. auto error = cb.OnNodeDone();
  364. if (error != SUCCESS) {
  365. task_context->OnError(error);
  366. }
  367. if (node_state->IsShapeDependence() && graph_item_->HasCtrlFlowOp()) {
  368. AfterExecuted(node_state);
  369. }
  370. }
  371. Status SubgraphExecutor::InitCallback(NodeState *node_state, std::function<void()> &callback) {
  372. auto task_context = node_state->GetTaskContext();
  373. GE_CHECK_NOTNULL(task_context);
  374. if (task_context->NeedCallback()) {
  375. callback = std::bind(&SubgraphExecutor::OnNodeDone, this, node_state);
  376. } else if (node_state->IsShapeDependence() && graph_item_->HasCtrlFlowOp()) {
  377. callback = std::bind(&SubgraphExecutor::AfterExecuted, this, node_state);
  378. }
  379. return SUCCESS;
  380. }
  381. Status SubgraphExecutor::ScheduleNodes() {
  382. GELOGD("[%s] Start to schedule nodes.", graph_item_->GetName().c_str());
  383. while (true) {
  384. NodeState *node_state = nullptr;
  385. if (!schedule_queue_.Pop(node_state)) {
  386. if (context_->is_eos_) {
  387. GELOGD("[%s] Got end of sequence.", graph_item_->GetName().c_str());
  388. break;
  389. }
  390. if (context_->GetStatus() != SUCCESS) {
  391. GELOGD("[%s] Graph execution Got failed.", graph_item_->GetName().c_str());
  392. return SUCCESS;
  393. }
  394. GELOGE(INTERNAL_ERROR, "[%s] failed to pop node.", graph_item_->GetName().c_str());
  395. return INTERNAL_ERROR;
  396. }
  397. if (node_state == nullptr) {
  398. GELOGD("[%s] Got EOF from queue.", graph_item_->GetName().c_str());
  399. break;
  400. }
  401. GE_CHK_STATUS_RET_NOLOG(node_state->WaitForScheduleDone());
  402. }
  403. GELOGD("[%s] Done schedule nodes successfully.", graph_item_->GetName().c_str());
  404. return SUCCESS;
  405. }
  406. Status SubgraphExecutor::InferShape(ShapeInferenceEngine *shape_inference_engine, NodeState &node_state) const {
  407. HYBRID_CHK_STATUS_RET(shape_inference_engine->InferShape(node_state),
  408. "[Invoke][InferShape] failed for [%s].", node_state.GetName().c_str());
  409. HYBRID_CHK_STATUS_RET(shape_inference_engine->PropagateOutputShapes(node_state),
  410. "[Invoke][PropagateOutputShapes] failed for [%s].", node_state.GetName().c_str());
  411. return SUCCESS;
  412. }
  413. Status SubgraphExecutor::PrepareForExecution(GraphExecutionContext *ctx, NodeState &node_state) {
  414. auto &node_item = *node_state.GetNodeItem();
  415. if (node_item.kernel_task == nullptr) {
  416. GE_CHK_STATUS_RET(TaskCompileEngine::Compile(node_state, ctx),
  417. "[Invoke][Compile] Failed for node[%s]", node_state.GetName().c_str());
  418. } else {
  419. node_state.SetKernelTask(node_item.kernel_task);
  420. }
  421. const auto &task = node_state.GetKernelTask();
  422. if (task == nullptr) {
  423. GELOGE(INTERNAL_ERROR, "[Invoke][GetKernelTask] failed for[%s], NodeTask is null.", node_state.GetName().c_str());
  424. REPORT_CALL_ERROR("E19999", "invoke GetKernelTask failed for %s, NodeTask is null.", node_state.GetName().c_str());
  425. return INTERNAL_ERROR;
  426. }
  427. GE_CHK_RT_RET(rtCtxSetCurrent(ctx->rt_context));
  428. RECORD_COMPILE_EVENT(ctx, node_item.NodeName().c_str(), "[UpdateTilingData] start");
  429. GE_CHK_STATUS_RET_NOLOG(task->UpdateTilingData(*node_state.GetTaskContext())); // update op_desc before alloc ws
  430. RECORD_COMPILE_EVENT(ctx, node_item.NodeName().c_str(), "[UpdateTilingData] end");
  431. return SUCCESS;
  432. }
  433. Status SubgraphExecutor::LaunchTasks() {
  434. while (true) {
  435. NodeState *node_state = nullptr;
  436. if (!ready_queue_.Pop(node_state)) {
  437. GELOGE(INTERNAL_ERROR, "[Invoke][Pop] failed for [%s].", graph_item_->GetName().c_str());
  438. REPORT_CALL_ERROR("E19999", "invoke pop failed for %s.", graph_item_->GetName().c_str());
  439. return INTERNAL_ERROR;
  440. }
  441. if (node_state == nullptr) {
  442. GELOGD("[%s] Got EOF from queue.", graph_item_->GetName().c_str());
  443. return SUCCESS;
  444. }
  445. if (node_state->GetType() == NETOUTPUT) {
  446. // Wait for all inputs become valid
  447. // after PrepareNodes returned. all output tensors and shapes are valid
  448. GE_CHK_STATUS_RET_NOLOG(node_state->GetShapeInferenceState().AwaitShapesReady(*context_));
  449. GE_CHK_STATUS_RET_NOLOG(node_state->AwaitInputTensors(*context_));
  450. GELOGD("[%s] Done executing node successfully.", node_state->GetName().c_str());
  451. continue;
  452. }
  453. GE_CHK_STATUS_RET_NOLOG(node_state->WaitForPrepareDone());
  454. GELOGD("[%s] Start to execute.", node_state->GetName().c_str());
  455. auto shared_task_context = node_state->GetTaskContext();
  456. GE_CHECK_NOTNULL(shared_task_context);
  457. shared_task_context->SetForceInferShape(force_infer_shape_);
  458. std::function<void()> callback;
  459. GE_CHK_STATUS_RET_NOLOG(InitCallback(node_state, callback));
  460. HYBRID_CHK_STATUS_RET(ExecutionEngine::ExecuteAsync(*node_state, shared_task_context, *context_, callback),
  461. "[Invoke][ExecuteAsync] failed for [%s].", node_state->GetName().c_str());
  462. GELOGD("[%s] Done executing node successfully.", node_state->GetName().c_str());
  463. }
  464. }
  465. Status SubgraphExecutor::ScheduleTasks(int group) {
  466. GELOGD("[%s] Start to schedule prepare workers.", graph_item_->GetName().c_str());
  467. subgraph_context_->SetGroup(group);
  468. auto prepare_future = std::async(std::launch::async, [&]() -> Status {
  469. GetContext().SetSessionId(context_->session_id);
  470. GetContext().SetContextId(context_->context_id);
  471. auto ret = PrepareNodes(group);
  472. ready_queue_.Push(nullptr);
  473. schedule_queue_.Push(nullptr);
  474. for (auto &item : prepare_queues_) {
  475. item.second.Push(nullptr);
  476. }
  477. return ret;
  478. });
  479. auto schedule_future = std::async(std::launch::async, [&]() -> Status {
  480. return ScheduleNodes();
  481. });
  482. GELOGD("[%s] Start to execute subgraph.", graph_item_->GetName().c_str());
  483. auto ret = LaunchTasks();
  484. if (ret != SUCCESS) {
  485. subgraph_context_->OnError(ret);
  486. context_->SetErrorCode(ret);
  487. ready_queue_.Stop();
  488. schedule_queue_.Stop();
  489. for (auto &item : prepare_queues_) {
  490. item.second.Stop();
  491. }
  492. prepare_future.wait();
  493. schedule_future.wait();
  494. return ret;
  495. }
  496. GE_CHK_STATUS_RET(prepare_future.get(), "[Invoke][get] [%s] Error occurred in task preparation.",
  497. graph_item_->GetName().c_str());
  498. GE_CHK_STATUS_RET(schedule_future.get(), "[Invoke][get] [%s] Error occurred in task preparation.",
  499. graph_item_->GetName().c_str());
  500. GELOGD("[%s] Done launching all tasks successfully.", graph_item_->GetName().c_str());
  501. return SUCCESS;
  502. }
  503. Status SubgraphExecutor::GetOutputs(vector<TensorValue> &outputs) {
  504. return subgraph_context_->GetOutputs(outputs);
  505. }
  506. Status SubgraphExecutor::GetOutputs(vector<TensorValue> &outputs, std::vector<ConstGeTensorDescPtr> &output_desc) {
  507. GE_CHK_STATUS_RET(GetOutputs(outputs), "[Invoke][GetOutputs] failed for [%s].", graph_item_->GetName().c_str());
  508. // copy output data from op to designated position
  509. GE_CHK_STATUS_RET(graph_item_->GetOutputDescList(output_desc),
  510. "[Invoke][GetOutputDescList][%s] Failed to get output tensor desc.",
  511. graph_item_->GetName().c_str());
  512. if (outputs.size() != output_desc.size()) {
  513. GELOGE(INTERNAL_ERROR, "[Check][Size]Number of outputs(%zu) mismatch number of output_desc(%zu).",
  514. outputs.size(), output_desc.size());
  515. REPORT_INNER_ERROR("E19999", "Number of outputs(%zu) mismatch number of output_desc(%zu).",
  516. outputs.size(), output_desc.size());
  517. return INTERNAL_ERROR;
  518. }
  519. return SUCCESS;
  520. }
  521. Status SubgraphExecutor::Synchronize() {
  522. GELOGD("[%s] Synchronize start.", graph_item_->GetName().c_str());
  523. GE_CHK_STATUS_RET_NOLOG(context_->Synchronize(context_->stream));
  524. GELOGD("[%s] Done synchronizing successfully.", graph_item_->GetName().c_str());
  525. return SUCCESS;
  526. }
  527. Status SubgraphExecutor::SetOutputsToParentNode(TaskContext &task_context) {
  528. // get output tensors and tensor desc list
  529. std::vector<TensorValue> outputs;
  530. std::vector<ConstGeTensorDescPtr> output_desc_list;
  531. GE_CHK_STATUS_RET(subgraph_context_->GetOutputs(outputs), "[Invoke][GetOutputs][%s] Failed to get output tensors.",
  532. graph_item_->GetName().c_str());
  533. GE_CHK_STATUS_RET(graph_item_->GetOutputDescList(output_desc_list),
  534. "[Invoke][GetOutputDescList][%s] Failed to get output tensor desc.",
  535. graph_item_->GetName().c_str());
  536. if (outputs.size() != output_desc_list.size()) {
  537. GELOGE(INTERNAL_ERROR, "[Check][Size][%s] num of output tensors = %zu, num of output tensor desc = %zu not equal",
  538. graph_item_->GetName().c_str(), outputs.size(), output_desc_list.size());
  539. REPORT_INNER_ERROR("E19999", "%s num of output tensors = %zu, num of output tensor desc = %zu not equal",
  540. graph_item_->GetName().c_str(), outputs.size(), output_desc_list.size());
  541. return INTERNAL_ERROR;
  542. }
  543. // mapping to parent task context
  544. for (size_t i = 0; i < outputs.size(); ++i) {
  545. int parent_output_index = graph_item_->GetParentOutputIndex(i);
  546. GE_CHECK_GE(parent_output_index, 0);
  547. // update tensor
  548. GELOGD("[%s] Updating output[%zu] to parent output[%d]",
  549. graph_item_->GetName().c_str(),
  550. i,
  551. parent_output_index);
  552. GELOGD("[%s] Updating output tensor, index = %d, tensor = %s",
  553. graph_item_->GetName().c_str(),
  554. parent_output_index,
  555. outputs[i].DebugString().c_str());
  556. GE_CHK_STATUS_RET(task_context.SetOutput(parent_output_index, outputs[i]));
  557. // updating shapes. dynamic format/dtype is not supported.
  558. // It should be noted that even the subgraph is of known shape, it is also necessary to update parent output desc,
  559. // for instance, IfOp may have two known-shaped subgraphs of different output shapes
  560. const auto &output_desc = output_desc_list[i];
  561. auto parent_output_desc = task_context.MutableOutputDesc(parent_output_index);
  562. GE_CHECK_NOTNULL(parent_output_desc);
  563. GELOGD("[%s] Updating output shape[%d] from [%s] to [%s]",
  564. graph_item_->GetName().c_str(),
  565. parent_output_index,
  566. parent_output_desc->MutableShape().ToString().c_str(),
  567. output_desc->GetShape().ToString().c_str());
  568. parent_output_desc->SetShape(output_desc->GetShape());
  569. GELOGD("[%s] Updating output original shape[%d] from [%s] to [%s]",
  570. graph_item_->GetName().c_str(),
  571. parent_output_index,
  572. parent_output_desc->GetOriginShape().ToString().c_str(),
  573. output_desc->GetOriginShape().ToString().c_str());
  574. parent_output_desc->SetOriginShape(output_desc->GetOriginShape());
  575. }
  576. return SUCCESS;
  577. }
  578. Status SubgraphExecutor::EnableOutputZeroCopy(const vector<TensorValue> &outputs) {
  579. GELOGD("To enable zero copy, output number = %zu", outputs.size());
  580. const auto &output_edges = graph_item_->GetOutputEdges();
  581. // Op -> MetOutput, set the output tensor of Op that output to the NetOutput node
  582. if (outputs.size() != output_edges.size()) {
  583. GELOGE(PARAM_INVALID, "[Check][Size]Output number mismatches, expect = %zu, but given = %zu",
  584. output_edges.size(), outputs.size());
  585. REPORT_INNER_ERROR("E19999", "Output number mismatches, expect = %zu, but given = %zu",
  586. output_edges.size(), outputs.size());
  587. return PARAM_INVALID;
  588. }
  589. for (size_t i = 0; i < outputs.size(); ++i) {
  590. auto &output_tensor = outputs[i];
  591. auto &output_node = output_edges[i].first;
  592. int output_idx = output_edges[i].second;
  593. GELOGD("[%s] Set output tensor[%zu] to [%s]'s output[%d], tensor = %s",
  594. graph_item_->GetName().c_str(),
  595. i,
  596. output_node->NodeName().c_str(),
  597. output_idx,
  598. output_tensor.DebugString().c_str());
  599. GE_CHK_STATUS_RET(subgraph_context_->SetOutput(*output_node, output_idx, output_tensor),
  600. "[Invoke][SetOutput][%s] Failed to set input tensor[%zu]",
  601. graph_item_->GetName().c_str(), i);
  602. }
  603. GELOGD("Done enabling zero copy for outputs successfully.");
  604. return SUCCESS;
  605. }
  606. Status SubgraphExecutor::PartialExecuteAsync(int task_group) {
  607. return ScheduleTasks(task_group);
  608. }
  609. Status SubgraphExecutor::InitForPartialExecution(const vector<TensorValue> &inputs,
  610. const vector<ConstGeTensorDescPtr> &input_desc) {
  611. if (subgraph_context_ == nullptr) {
  612. return Init(inputs, input_desc);
  613. }
  614. subgraph_context_->Reset();
  615. if (graph_item_->IsDynamic()) {
  616. GE_CHK_STATUS_RET(InitInputsForUnknownShape(inputs, input_desc),
  617. "[%s] Failed to set inputs.",
  618. graph_item_->GetName().c_str());
  619. } else {
  620. GE_CHK_STATUS_RET(InitInputsForKnownShape(inputs),
  621. "[Invoke][InitInputsForKnownShape][%s] Failed to init subgraph executor for known shape subgraph",
  622. graph_item_->GetName().c_str());
  623. }
  624. return SUCCESS;
  625. }
  626. } // namespace hybrid
  627. } // namespace ge

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