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 32 kB

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

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