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.

switch_to_stream_switch_pass.cc 33 kB

5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /**
  2. * Copyright 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 "graph/passes/switch_to_stream_switch_pass.h"
  17. #include <stack>
  18. #include "common/ge/ge_util.h"
  19. #include "ge/ge_api_types.h"
  20. #include "graph/common/omg_util.h"
  21. #include "graph/ge_context.h"
  22. #include "graph/utils/type_utils.h"
  23. namespace ge {
  24. Status SwitchToStreamSwitchPass::Run(ComputeGraphPtr graph) {
  25. GELOGD("SwitchToStreamSwitchPass Enter");
  26. GE_CHK_STATUS_RET(CheckCycleDependence(graph), "Check cyclic dependence failed.");
  27. for (const auto &switch_node : switch_nodes_) {
  28. GE_CHK_STATUS_RET(ReplaceSwitchNode(graph, switch_node), "Replace Switch by StreamSwitch failed.");
  29. }
  30. GE_CHK_STATUS_RET(CombineSwitchNode(graph), "Combine StreamSwitch nodes failed.");
  31. for (const auto &node : bypass_nodes_) {
  32. GE_CHK_BOOL_EXEC(graph->IsolateNode(node) == GRAPH_SUCCESS, return FAILED, "Isolate node failed.");
  33. GE_CHK_BOOL_EXEC(GraphUtils::RemoveNodeWithoutRelink(graph, node) == GRAPH_SUCCESS, return FAILED,
  34. "Remove switch node failed.");
  35. }
  36. GELOGD("SwitchToStreamSwitchPass Leave");
  37. return SUCCESS;
  38. }
  39. ///
  40. /// @brief Clear Status
  41. /// @return
  42. ///
  43. Status SwitchToStreamSwitchPass::ClearStatus() {
  44. switch_nodes_.clear();
  45. switch_cyclic_map_.clear();
  46. bypass_nodes_.clear();
  47. stream_switch_nodes_.clear();
  48. cond_node_map_.clear();
  49. switch_node_map_.clear();
  50. node_num_map_.clear();
  51. return SUCCESS;
  52. }
  53. ///
  54. /// @brief Check cyclic dependence
  55. /// @param [in] graph
  56. /// @return Status
  57. ///
  58. Status SwitchToStreamSwitchPass::CheckCycleDependence(const ComputeGraphPtr &graph) {
  59. std::string type;
  60. std::unordered_map<NodePtr, std::vector<NodePtr>> cond_switch_map;
  61. for (const NodePtr &node : graph->GetDirectNode()) {
  62. GE_CHK_STATUS_RET(GetOriginalType(node, type), "Get node type failed.");
  63. if ((type != SWITCH) && (type != REFSWITCH)) {
  64. continue;
  65. }
  66. InDataAnchorPtr in_cond_anchor = node->GetInDataAnchor(SWITCH_PRED_INPUT);
  67. GE_CHECK_NOTNULL(in_cond_anchor);
  68. OutDataAnchorPtr peer_out_anchor = in_cond_anchor->GetPeerOutAnchor();
  69. GE_CHECK_NOTNULL(peer_out_anchor);
  70. if (FindSwitchCondInput(peer_out_anchor) != SUCCESS) {
  71. GELOGE(FAILED, "Find pred_input for switch_node %s failed.", node->GetName().c_str());
  72. return FAILED;
  73. }
  74. NodePtr cond_node = peer_out_anchor->GetOwnerNode();
  75. auto iter = cond_switch_map.find(cond_node);
  76. if (iter == cond_switch_map.end()) {
  77. cond_switch_map[cond_node] = { node };
  78. } else {
  79. iter->second.emplace_back(node);
  80. }
  81. switch_nodes_.emplace_back(node);
  82. }
  83. MarkCycleDependence(cond_switch_map);
  84. return SUCCESS;
  85. }
  86. ///
  87. /// @brief Mark cyclic dependence
  88. /// @param [in] graph
  89. /// @param [in] cond_switch_map
  90. /// @return void
  91. ///
  92. void SwitchToStreamSwitchPass::MarkCycleDependence(
  93. const std::unordered_map<NodePtr, std::vector<NodePtr>> &cond_switch_map) {
  94. std::stack<NodePtr> out_nodes;
  95. NodePtr tmp_node = nullptr;
  96. std::unordered_set<NodePtr> visited;
  97. for (const auto &iter : cond_switch_map) {
  98. std::set<NodePtr> switch_nodes(iter.second.begin(), iter.second.end());
  99. for (const auto &switch_node : switch_nodes) {
  100. GELOGD("MarkCycleDependence: cond_node=%s, switch=%s.", iter.first->GetName().c_str(),
  101. switch_node->GetName().c_str());
  102. for (const auto &node : switch_node->GetOutAllNodes()) {
  103. out_nodes.push(node);
  104. }
  105. }
  106. visited.clear();
  107. while (!out_nodes.empty()) {
  108. tmp_node = out_nodes.top();
  109. out_nodes.pop();
  110. if (visited.count(tmp_node) > 0) {
  111. continue;
  112. }
  113. for (const NodePtr &out_node : tmp_node->GetOutAllNodes()) {
  114. if (switch_nodes.find(out_node) == switch_nodes.end()) {
  115. out_nodes.push(out_node);
  116. continue;
  117. }
  118. GELOGD("MarkCycleDependence: tmp_node=%s, switch_node=%s.",
  119. tmp_node->GetName().c_str(), out_node->GetName().c_str());
  120. GE_IF_BOOL_EXEC(SetCyclicDependenceFlag(out_node) != SUCCESS,
  121. GELOGW("set cyclic dependence attr failed."); return );
  122. auto map_iter = switch_cyclic_map_.find(out_node);
  123. if (map_iter == switch_cyclic_map_.end()) {
  124. switch_cyclic_map_[out_node] = {tmp_node->GetName()};
  125. } else {
  126. map_iter->second.insert(tmp_node->GetName());
  127. }
  128. }
  129. visited.insert(tmp_node);
  130. }
  131. }
  132. return;
  133. }
  134. ///
  135. /// @brief Replace Switch Op
  136. /// @param [in] graph
  137. /// @param [in] switch_node
  138. /// @return Status
  139. ///
  140. Status SwitchToStreamSwitchPass::ReplaceSwitchNode(const ComputeGraphPtr &graph, const NodePtr &switch_node) {
  141. OutDataAnchorPtr peer_data_anchor = nullptr;
  142. OutDataAnchorPtr peer_cond_anchor = nullptr;
  143. GE_CHK_BOOL_EXEC(BypassSwitchNode(switch_node, peer_data_anchor, peer_cond_anchor) == SUCCESS, return FAILED,
  144. "Bypass switch node %s failed.", switch_node->GetName().c_str());
  145. GE_CHECK_NOTNULL(peer_data_anchor);
  146. GE_CHECK_NOTNULL(peer_cond_anchor);
  147. OpDescPtr cond_desc = peer_cond_anchor->GetOwnerNode()->GetOpDesc();
  148. GE_CHECK_NOTNULL(cond_desc);
  149. DataType cond_data_type = cond_desc->GetOutputDesc(peer_cond_anchor->GetIdx()).GetDataType();
  150. GE_CHK_BOOL_EXEC(cond_data_type == DT_BOOL, return FAILED,
  151. "pred_input of Switch only support DT_BOOL data_type, but %s exactly.",
  152. TypeUtils::DataTypeToSerialString(cond_data_type).c_str());
  153. OpDescPtr switch_desc = switch_node->GetOpDesc();
  154. GE_CHECK_NOTNULL(switch_desc);
  155. bool cyclic_flag = switch_desc->HasAttr(ATTR_NAME_CYCLIC_DEPENDENCE_FLAG);
  156. std::set<std::string> out_node_list;
  157. for (const auto &out_data_anchor : switch_node->GetAllOutDataAnchors()) {
  158. bool true_branch_flag = (static_cast<uint32_t>(out_data_anchor->GetIdx()) == SWITCH_TRUE_OUTPUT);
  159. NodePtr stream_switch = nullptr;
  160. out_node_list.clear();
  161. for (const auto &peer_in_anchor : out_data_anchor->GetPeerAnchors()) {
  162. GE_IF_BOOL_EXEC(stream_switch == nullptr, {
  163. stream_switch = CreateStreamSwitchNode(graph, switch_node, true_branch_flag ? "_t" : "_f", peer_cond_anchor);
  164. GE_CHK_BOOL_EXEC(stream_switch != nullptr, return FAILED, "Create stream_switch node failed.");
  165. if (SetSwitchTrueBranchFlag(stream_switch, true_branch_flag) != SUCCESS) {
  166. GELOGE(FAILED, "SetSwitchTrueBranchFlag for node %s failed.", stream_switch->GetName().c_str());
  167. return FAILED;
  168. }
  169. if (MarkBranches(peer_cond_anchor, stream_switch, true_branch_flag) != SUCCESS) {
  170. GELOGE(FAILED, "Mark branches for stream_switch %s failed.", stream_switch->GetName().c_str());
  171. return FAILED;
  172. }
  173. if (!cyclic_flag) {
  174. GE_CHK_STATUS(GraphUtils::AddEdge(peer_data_anchor->GetOwnerNode()->GetOutControlAnchor(),
  175. stream_switch->GetInControlAnchor()),
  176. "StreamSwitch node add ctl edge failed.");
  177. }
  178. });
  179. GE_CHK_STATUS(GraphUtils::RemoveEdge(out_data_anchor, peer_in_anchor), "Remove Switch data output failed.");
  180. NodePtr out_node = peer_in_anchor->GetOwnerNode();
  181. GE_CHK_STATUS(GraphUtils::AddEdge(peer_data_anchor, peer_in_anchor), "StreamSwitch node add edge failed.");
  182. GE_CHK_STATUS(GraphUtils::AddEdge(stream_switch->GetOutControlAnchor(), out_node->GetInControlAnchor()),
  183. "StreamSwitch node add ctl edge failed.");
  184. out_node_list.insert(out_node->GetName());
  185. }
  186. GE_IF_BOOL_EXEC(stream_switch != nullptr, {
  187. MoveCtrlEdges(switch_node, stream_switch);
  188. switch_node_map_[stream_switch] = out_node_list;
  189. if (SetOriginalNodeName(stream_switch, switch_node->GetName()) != SUCCESS) {
  190. GELOGE(FAILED, "SetOriginalNodeName for node %s failed.", stream_switch->GetName().c_str());
  191. return FAILED;
  192. }
  193. });
  194. }
  195. (void)bypass_nodes_.insert(switch_node);
  196. return SUCCESS;
  197. }
  198. ///
  199. /// @brief Bypass Switch Node
  200. /// @param [in] switch_node
  201. /// @param [out] peer_data_anchor
  202. /// @param [out] peer_cond_anchor
  203. /// @return Status
  204. ///
  205. Status SwitchToStreamSwitchPass::BypassSwitchNode(const NodePtr &switch_node, OutDataAnchorPtr &peer_data_anchor,
  206. OutDataAnchorPtr &peer_cond_anchor) {
  207. for (uint32_t idx = 0; idx < SWITCH_INPUT_NUM; ++idx) {
  208. InDataAnchorPtr in_data_anchor = switch_node->GetInDataAnchor(idx);
  209. GE_CHECK_NOTNULL(in_data_anchor);
  210. OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  211. GE_CHECK_NOTNULL(peer_out_anchor);
  212. // Remove Switch data input.
  213. if (GraphUtils::RemoveEdge(peer_out_anchor, in_data_anchor) != GRAPH_SUCCESS) {
  214. GELOGE(FAILED, "Remove data edge %s->%s failed.", peer_out_anchor->GetOwnerNode()->GetName().c_str(),
  215. switch_node->GetName().c_str());
  216. return FAILED;
  217. }
  218. if (idx == SWITCH_DATA_INPUT) {
  219. peer_data_anchor = peer_out_anchor;
  220. } else {
  221. peer_cond_anchor = peer_out_anchor;
  222. }
  223. }
  224. return SUCCESS;
  225. }
  226. ///
  227. /// @brief Find Switch cond input
  228. /// @param [out] peer_cond_anchor
  229. /// @return Status
  230. ///
  231. Status SwitchToStreamSwitchPass::FindSwitchCondInput(OutDataAnchorPtr &peer_cond_anchor) {
  232. NodePtr tmp_node = nullptr;
  233. std::string type;
  234. bool pass_flag = true;
  235. while (pass_flag) {
  236. if (tmp_node == nullptr) {
  237. tmp_node = peer_cond_anchor->GetOwnerNode();
  238. } else {
  239. InDataAnchorPtr in_data_anchor = tmp_node->GetInDataAnchor(SWITCH_DATA_INPUT);
  240. GE_CHECK_NOTNULL(in_data_anchor);
  241. peer_cond_anchor = in_data_anchor->GetPeerOutAnchor();
  242. GE_CHECK_NOTNULL(peer_cond_anchor);
  243. tmp_node = peer_cond_anchor->GetOwnerNode();
  244. }
  245. GE_CHK_STATUS_RET(GetOriginalType(tmp_node, type), "Get node type failed.");
  246. pass_flag = ((type == SWITCH) || (type == REFSWITCH));
  247. }
  248. return SUCCESS;
  249. }
  250. ///
  251. /// @brief Create StreamSwitch Node
  252. /// @param [in] graph
  253. /// @param [in] switch_node
  254. /// @param [in] suffix
  255. /// @param [in] peer_cond_anchor
  256. /// @return ge::NodePtr
  257. ///
  258. NodePtr SwitchToStreamSwitchPass::CreateStreamSwitchNode(const ComputeGraphPtr &graph, const NodePtr &switch_node,
  259. const std::string &suffix,
  260. const OutDataAnchorPtr &peer_cond_anchor) {
  261. OpDescPtr switch_op_desc = switch_node->GetOpDesc();
  262. GE_CHK_BOOL_EXEC(switch_op_desc != nullptr, return nullptr, "OpDesc of Switch node is invalid.");
  263. GE_IF_BOOL_EXEC(switch_op_desc->GetInputsSize() != SWITCH_INPUT_NUM, {
  264. GELOGE(FAILED, "Switch input param invalid, input_size=%lu, should be %u.", switch_op_desc->GetInputsSize(),
  265. SWITCH_INPUT_NUM);
  266. return nullptr;
  267. });
  268. const std::string &node_name = switch_node->GetName() + "_" + STREAMSWITCH + suffix;
  269. GELOGI("Create StreamSwitch, name=%s.", node_name.c_str());
  270. OpDescPtr op_desc = MakeShared<OpDesc>(node_name, STREAMSWITCH);
  271. if (op_desc == nullptr) {
  272. GELOGE(FAILED, "Create op_desc failed, StreamSwitch:%s.", node_name.c_str());
  273. return nullptr;
  274. }
  275. // mark hccl group id
  276. std::string hccl_group_id;
  277. if (AttrUtils::GetStr(switch_node->GetOpDesc(), ATTR_NAME_HCCL_FUSED_GROUP, hccl_group_id)) {
  278. (void)AttrUtils::SetStr(op_desc, ATTR_NAME_HCCL_FUSED_GROUP, hccl_group_id);
  279. GELOGD("Set attr ATTR_NAME_HCCL_FUSED_GROUP for Stream_Switch %s, value is %s.", node_name.c_str(),
  280. hccl_group_id.c_str());
  281. }
  282. int64_t switch_type;
  283. if (AttrUtils::GetInt(switch_node->GetOpDesc(), ATTR_NAME_STREAM_SWITCH_TYPE, switch_type)) {
  284. (void)AttrUtils::SetInt(op_desc, ATTR_NAME_STREAM_SWITCH_TYPE, switch_type);
  285. GELOGD("Set attr ATTR_NAME_STREAM_SWITCH_TYPE for Stream_Switch %s, value is %ld.", node_name.c_str(),
  286. switch_type);
  287. }
  288. if (!AttrUtils::SetInt(op_desc, ATTR_NAME_SWITCH_DATA_TYPE, RT_SWITCH_INT32) ||
  289. !AttrUtils::SetInt(op_desc, ATTR_NAME_STREAM_SWITCH_COND, (int64_t)RT_EQUAL)) {
  290. GELOGE(INTERNAL_ERROR, "set int failed");
  291. return nullptr;
  292. }
  293. // Already checked, first input is Variable will passed, second is condition will checked.
  294. GeTensorDesc cond_input_desc = switch_op_desc->GetInputDesc(SWITCH_PRED_INPUT);
  295. GeTensorDesc input_desc(GeShape(cond_input_desc.GetShape().GetDims()), cond_input_desc.GetFormat(), DT_INT32);
  296. GE_CHK_BOOL_EXEC(op_desc->AddInputDesc(input_desc) == GRAPH_SUCCESS, return nullptr,
  297. "Create StreamSwitch node: add input desc failed.");
  298. GE_CHK_BOOL_EXEC(op_desc->AddInputDesc(input_desc) == GRAPH_SUCCESS, return nullptr,
  299. "Create StreamSwitch node: add input desc failed.");
  300. NodePtr stream_switch = graph->AddNode(op_desc);
  301. GE_CHK_BOOL_EXEC(stream_switch != nullptr, return nullptr, "Insert StreamSwitch node failed.");
  302. GE_CHK_STATUS(GraphUtils::AddEdge(peer_cond_anchor, stream_switch->GetInDataAnchor(0)),
  303. "StreamSwitch node add cond edge failed.");
  304. return stream_switch;
  305. }
  306. ///
  307. /// @brief Mark Switch Branch
  308. /// @param [in] peer_cond_anchor
  309. /// @param [in] stream_switch
  310. /// @param [in] true_branch_flag
  311. /// @return Status
  312. ///
  313. Status SwitchToStreamSwitchPass::MarkBranches(const OutDataAnchorPtr &peer_cond_anchor, const NodePtr &stream_switch,
  314. bool true_branch_flag) {
  315. uint32_t index = true_branch_flag ? SWITCH_TRUE_OUTPUT : SWITCH_FALSE_OUTPUT;
  316. auto it = cond_node_map_.find(peer_cond_anchor);
  317. if (it != cond_node_map_.end()) {
  318. int64_t switch_group_id = GetGroupId(stream_switch);
  319. auto switch_group_it = it->second.find(switch_group_id);
  320. if (switch_group_it == it->second.end()) {
  321. std::list<NodePtr> false_node_list;
  322. std::list<NodePtr> true_node_list;
  323. std::list<NodePtr> &node_list = true_branch_flag ? true_node_list : false_node_list;
  324. node_list.emplace_back(stream_switch);
  325. std::vector<std::list<NodePtr>> switch_list;
  326. switch_list.emplace_back(false_node_list);
  327. switch_list.emplace_back(true_node_list);
  328. it->second[switch_group_id] = switch_list;
  329. } else {
  330. GE_IF_BOOL_EXEC(switch_group_it->second.size() != SWITCH_OUTPUT_NUM, {
  331. GELOGE(INTERNAL_ERROR, "Check size failed, node: %s", stream_switch->GetName().c_str());
  332. return FAILED;
  333. });
  334. switch_group_it->second[index].emplace_back(stream_switch);
  335. }
  336. } else {
  337. int64_t switch_group_id = GetGroupId(stream_switch);
  338. std::map<int64_t, std::vector<std::list<NodePtr>>> switch_group_map;
  339. std::list<NodePtr> false_node_list;
  340. std::list<NodePtr> true_node_list;
  341. std::list<NodePtr> &node_list = true_branch_flag ? true_node_list : false_node_list;
  342. node_list.emplace_back(stream_switch);
  343. std::vector<std::list<NodePtr>> switch_list;
  344. switch_list.emplace_back(false_node_list);
  345. switch_list.emplace_back(true_node_list);
  346. switch_group_map[switch_group_id] = switch_list;
  347. cond_node_map_[peer_cond_anchor] = switch_group_map;
  348. }
  349. return SUCCESS;
  350. }
  351. ///
  352. /// @brief Get group_id for switch_node
  353. /// @param [in] node
  354. /// @return group_id
  355. ///
  356. int64_t SwitchToStreamSwitchPass::GetGroupId(const NodePtr &node) {
  357. std::string tailing_optimization_option;
  358. bool is_tailing_optimization = false;
  359. if (GetContext().GetOption(OPTION_EXEC_ENABLE_TAILING_OPTIMIZATION, tailing_optimization_option) == GRAPH_SUCCESS) {
  360. // "1" means it's True from frontend option
  361. is_tailing_optimization = (tailing_optimization_option == "1");
  362. GELOGI("Option ge.exec.isTailingOptimization is %s", tailing_optimization_option.c_str());
  363. }
  364. if (!is_tailing_optimization) {
  365. return 0;
  366. }
  367. std::string hccl_group_id;
  368. if (!AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_HCCL_FUSED_GROUP, hccl_group_id)) {
  369. GELOGI("Node %s can not find hccl group id.", node->GetName().c_str());
  370. return 0;
  371. }
  372. auto key_index = hccl_group_id.find_last_of('_');
  373. auto key_num = hccl_group_id.substr(key_index + 1, hccl_group_id.length() - key_index);
  374. GELOGI("Node:%s, hccl_group_id=%s, key_num=%s", node->GetName().c_str(), hccl_group_id.c_str(), key_num.c_str());
  375. int64_t num = atoi(key_num.c_str());
  376. if (num == 0) {
  377. return 0;
  378. }
  379. GELOGI("Hccl_group_id is %s, group_id is %ld", hccl_group_id.c_str(), num);
  380. return num;
  381. }
  382. ///
  383. /// @brief Combine switch nodes link to same cond
  384. /// @param [in] graph
  385. /// @return Status
  386. ///
  387. Status SwitchToStreamSwitchPass::CombineSwitchNode(const ComputeGraphPtr &graph) {
  388. for (auto iter = cond_node_map_.begin(); iter != cond_node_map_.end(); ++iter) {
  389. for (auto group_iter = iter->second.begin(); group_iter != iter->second.end(); ++group_iter) {
  390. std::list<NodePtr> false_switch_list = group_iter->second[SWITCH_FALSE_OUTPUT];
  391. std::list<NodePtr> true_switch_list = group_iter->second[SWITCH_TRUE_OUTPUT];
  392. std::set<NodePtr> same_cond_switch;
  393. same_cond_switch.insert(false_switch_list.begin(), false_switch_list.end());
  394. same_cond_switch.insert(true_switch_list.begin(), true_switch_list.end());
  395. OutDataAnchorPtr peer_cond_anchor = iter->first;
  396. GE_CHECK_NOTNULL(peer_cond_anchor);
  397. NodePtr cond_node = peer_cond_anchor->GetOwnerNode();
  398. GELOGI("CombineSwitchNode: cond_node=%s.", cond_node->GetName().c_str());
  399. NodePtr cast_node = CreateCastOp(graph, peer_cond_anchor);
  400. GE_CHK_BOOL_EXEC(cast_node != nullptr, return FAILED, "Create cast_node failed.");
  401. NodePtr active_node = CreateActiveNode(graph, cond_node);
  402. GE_CHK_BOOL_EXEC(active_node != nullptr, return FAILED, "Create StreamActive node failed.");
  403. GE_CHK_STATUS(GraphUtils::AddEdge(cast_node->GetOutControlAnchor(), active_node->GetInControlAnchor()),
  404. "StreamActive add ctl edge failed.");
  405. if (SetActiveLabelList(active_node, { cast_node->GetName() }) != SUCCESS) {
  406. GELOGE(FAILED, "Set active_label_list attr for node %s failed.", active_node->GetName().c_str());
  407. return FAILED;
  408. }
  409. const std::string &cond_group = cond_node->GetName();
  410. for (uint32_t i = 0; i < SWITCH_OUTPUT_NUM; ++i) {
  411. bool true_branch_flag = (i == SWITCH_TRUE_OUTPUT);
  412. std::list<NodePtr> &switch_list = (true_branch_flag ? true_switch_list : false_switch_list);
  413. GE_IF_BOOL_EXEC(switch_list.empty(), continue);
  414. // select first stream_switch
  415. NodePtr stream_switch = switch_list.front();
  416. // set stream_label
  417. GE_CHK_STATUS_RET(SetStreamLabel(stream_switch, cast_node->GetName()), "Set stream label failed.");
  418. OpDescPtr switch_desc = stream_switch->GetOpDesc();
  419. GE_CHECK_NOTNULL(switch_desc);
  420. switch_desc->SetName(CheckDuplicateName(cond_group + "/" + STREAMSWITCH + (true_branch_flag ? "_t" : "_f")));
  421. stream_switch_nodes_.emplace_back(stream_switch);
  422. // 0_input: original pred input, 1_input: constant node
  423. GE_CHK_STATUS_RET(AddConstNode(graph, stream_switch), "Add const node failed.");
  424. GE_CHK_STATUS(GraphUtils::RemoveEdge(peer_cond_anchor, stream_switch->GetInDataAnchor(0)),
  425. "StreamSwitch remove data edge failed.");
  426. GE_CHK_STATUS(GraphUtils::AddEdge(cast_node->GetOutDataAnchor(0), stream_switch->GetInDataAnchor(0)),
  427. "Cast add data edge failed.");
  428. for (const NodePtr &node : switch_list) {
  429. GE_IF_BOOL_EXEC(node != stream_switch, {
  430. GE_CHK_STATUS(GraphUtils::RemoveEdge(peer_cond_anchor, node->GetInDataAnchor(0)),
  431. "StreamSwitch remove data edge failed.");
  432. });
  433. GE_CHK_STATUS(ModifySwitchInCtlEdges(node, cast_node, same_cond_switch), "ModifySwitchInCtlEdges failed.");
  434. GE_CHK_STATUS(ModifySwitchOutCtlEdges(node, stream_switch, active_node), "ModifySwitchOutCtlEdges failed.");
  435. }
  436. GE_CHK_STATUS(GraphUtils::AddEdge(active_node->GetOutControlAnchor(), stream_switch->GetInControlAnchor()),
  437. "StreamActive add ctl edge failed.");
  438. }
  439. }
  440. }
  441. return SUCCESS;
  442. }
  443. ///
  444. /// @brief Create Active Op
  445. /// @param [in] graph
  446. /// @param [in] cond_node
  447. /// @return ge::NodePtr
  448. ///
  449. NodePtr SwitchToStreamSwitchPass::CreateActiveNode(const ComputeGraphPtr &graph, const NodePtr &node) {
  450. const std::string &node_name = CheckDuplicateName(node->GetName() + "_" + STREAMACTIVE);
  451. GELOGI("Create StreamActive op:%s.", node_name.c_str());
  452. OpDescPtr op_desc = MakeShared<OpDesc>(node_name, STREAMACTIVE);
  453. if (op_desc == nullptr) {
  454. GELOGE(FAILED, "Create op_desc failed, StreamActive:%s.", node_name.c_str());
  455. return nullptr;
  456. }
  457. NodePtr active_node = graph->AddNode(op_desc);
  458. GE_CHK_BOOL_EXEC(active_node != nullptr, return nullptr, "Create StreamActive node failed.");
  459. GE_IF_BOOL_EXEC(GraphUtils::AddEdge(node->GetOutControlAnchor(), active_node->GetInControlAnchor()) != SUCCESS,
  460. GELOGE(INTERNAL_ERROR, "add edge failed");
  461. return nullptr);
  462. GE_IF_BOOL_EXEC(SetSwitchBranchNodeLabel(active_node, node_name) != SUCCESS,
  463. GELOGE(INTERNAL_ERROR, "set switch branch node label failed");
  464. return nullptr);
  465. return active_node;
  466. }
  467. ///
  468. /// @brief Create cast node
  469. /// @param [in] graph
  470. /// @param [in] peer_cond_anchor
  471. /// @return NodePtr
  472. ///
  473. NodePtr SwitchToStreamSwitchPass::CreateCastOp(const ComputeGraphPtr &graph, const OutDataAnchorPtr &peer_cond_anchor) {
  474. OpDescPtr cond_desc = peer_cond_anchor->GetOwnerNode()->GetOpDesc();
  475. GE_CHK_BOOL_EXEC(cond_desc != nullptr, return nullptr, "Get cond_desc failed.");
  476. const std::string &cast_name = CheckDuplicateName(cond_desc->GetName() + "_" + CAST);
  477. GELOGI("Create cast_node: %s, input datatype:DT_BOOL, out datatype:DT_INT32", cast_name.c_str());
  478. OpDescPtr cast_desc = MakeShared<OpDesc>(cast_name, CAST);
  479. if (cast_desc == nullptr) {
  480. GELOGE(FAILED, "Create op_desc failed, Cast:%s.", cast_name.c_str());
  481. return nullptr;
  482. }
  483. if (!(AttrUtils::SetInt(cast_desc, CAST_ATTR_SRCT, (int64_t)DT_BOOL) &&
  484. AttrUtils::SetInt(cast_desc, CAST_ATTR_DSTT, (int64_t)DT_INT32) &&
  485. AttrUtils::SetInt(cast_desc, CAST_ATTR_DST_TYPE, (int64_t)DT_INT32) &&
  486. AttrUtils::SetBool(cast_desc, CAST_ATTR_TRUNCATE, false))) {
  487. GELOGE(FAILED, "Set CAST_ATTR_SRCT or CAST_ATTR_DSTT or CAST_ATTR_DST_TYPE or CAST_ATTR_TRUNCATE failed, node: %s.",
  488. cast_name.c_str());
  489. return nullptr;
  490. }
  491. GeTensorDesc tensor_desc = cond_desc->GetOutputDesc(peer_cond_anchor->GetIdx());
  492. tensor_desc.SetDataType(DT_BOOL);
  493. GE_CHK_BOOL_EXEC(cast_desc->AddInputDesc(tensor_desc) == SUCCESS, return nullptr,
  494. "Cast_node add input desc failed.");
  495. tensor_desc.SetDataType(DT_INT32);
  496. GE_CHK_BOOL_EXEC(cast_desc->AddOutputDesc(tensor_desc) == SUCCESS, return nullptr,
  497. "Cast_node add output desc failed.");
  498. NodePtr cast_node = graph->AddNode(cast_desc);
  499. GE_CHK_BOOL_EXEC(cast_node != nullptr, return nullptr, "Create cast_node failed.");
  500. // Cast node has and only has one input
  501. GE_CHK_STATUS(GraphUtils::AddEdge(peer_cond_anchor, cast_node->GetInDataAnchor(0)), "Cast add data edge failed.");
  502. return cast_node;
  503. }
  504. ///
  505. /// @brief Add const node as switch input1
  506. /// @param [in] graph
  507. /// @param [in] stream_switch
  508. /// @return Status
  509. ///
  510. Status SwitchToStreamSwitchPass::AddConstNode(const ComputeGraphPtr &graph, const NodePtr &stream_switch) {
  511. OpDescPtr op_desc = stream_switch->GetOpDesc();
  512. GE_CHECK_NOTNULL(op_desc);
  513. bool value = false;
  514. GE_CHK_BOOL_EXEC(AttrUtils::GetBool(op_desc, ATTR_NAME_SWITCH_TRUE_BRANCH_FLAG, value), return FAILED,
  515. "StreamSwitch get attr TRUE_BRANCH_STREAM failed.");
  516. const std::string &const_node_name = op_desc->GetName() + "_Constant_" + (value ? "t" : "f");
  517. GELOGI("Create const op: %s", const_node_name.c_str());
  518. OpDescPtr const_op_desc = MakeShared<OpDesc>(const_node_name, CONSTANT);
  519. if (const_op_desc == nullptr) {
  520. GELOGE(FAILED, "Create op_desc failed, Constant:%s.", const_node_name.c_str());
  521. return FAILED;
  522. }
  523. auto resize_value = (int32_t)value;
  524. GeTensorDesc data_desc = op_desc->GetInputDesc(1);
  525. GeTensorPtr const_value =
  526. MakeShared<GeTensor>(data_desc, reinterpret_cast<uint8_t *>(&resize_value), sizeof(int32_t));
  527. if (const_value == nullptr) {
  528. GELOGE(FAILED, "Create tensor failed.");
  529. return FAILED;
  530. }
  531. GE_CHK_BOOL_EXEC(AttrUtils::SetTensor(const_op_desc, ATTR_NAME_WEIGHTS, const_value), return FAILED);
  532. GE_CHK_BOOL_EXEC(const_op_desc->AddOutputDesc(data_desc) == GRAPH_SUCCESS, return FAILED,
  533. "Create Const op: add output desc failed.");
  534. NodePtr const_node = graph->AddNode(const_op_desc);
  535. GE_CHK_BOOL_EXEC(const_node != nullptr, return FAILED, "Insert Const node failed.");
  536. GE_CHK_STATUS(GraphUtils::AddEdge(const_node->GetOutDataAnchor(0), stream_switch->GetInDataAnchor(1)),
  537. "StreamSwitch node add ctl edge failed.");
  538. return SUCCESS;
  539. }
  540. ///
  541. /// @brief Modify in ctl edge for switch_node
  542. /// @param [in] switch_node
  543. /// @param [in] cast_node
  544. /// @param [in] same_cond_switch
  545. /// @return Status
  546. ///
  547. Status SwitchToStreamSwitchPass::ModifySwitchInCtlEdges(const NodePtr &switch_node, const NodePtr &cast_node,
  548. const std::set<NodePtr> &same_cond_switch) {
  549. GELOGD("ModifySwitchInCtlEdges: switch_node=%s, cast_node=%s", switch_node->GetName().c_str(),
  550. cast_node->GetName().c_str());
  551. std::string orig_switch_name = switch_node->GetName();
  552. OpDescPtr switch_desc = switch_node->GetOpDesc();
  553. GE_CHECK_NOTNULL(switch_desc);
  554. if (!AttrUtils::GetStr(switch_desc, ATTR_NAME_ORIG_NODE_NAME, orig_switch_name) || orig_switch_name.empty()) {
  555. GELOGE(INTERNAL_ERROR, "Get attr ATTR_NAME_ORIG_NODE_NAME failed, node: %s", switch_desc->GetName().c_str());
  556. return INTERNAL_ERROR;
  557. }
  558. for (const NodePtr &in_ctrl_node : switch_node->GetInControlNodes()) {
  559. GE_CHK_STATUS(GraphUtils::RemoveEdge(in_ctrl_node->GetOutControlAnchor(), switch_node->GetInControlAnchor()),
  560. "Remove ctl edge failed.");
  561. GE_IF_BOOL_EXEC(!in_ctrl_node->GetOutControlAnchor()->IsLinkedWith(cast_node->GetInControlAnchor()), {
  562. GE_CHK_STATUS(GraphUtils::AddEdge(in_ctrl_node->GetOutControlAnchor(), cast_node->GetInControlAnchor()),
  563. "Add ctl edge failed.");
  564. });
  565. GE_IF_BOOL_EXEC(in_ctrl_node->GetType() != STREAMSWITCH, continue);
  566. if (same_cond_switch.count(in_ctrl_node) > 0) {
  567. GE_CHK_STATUS(GraphUtils::RemoveEdge(in_ctrl_node->GetOutControlAnchor(), cast_node->GetInControlAnchor()),
  568. "Remove ctl edge failed.");
  569. continue;
  570. }
  571. auto find_res1 = switch_node_map_.find(in_ctrl_node);
  572. GE_IF_BOOL_EXEC(find_res1 == switch_node_map_.end(), {
  573. GELOGE(INTERNAL_ERROR, "StreamSwitch node %s not found in switch_node_map_.", in_ctrl_node->GetName().c_str());
  574. return INTERNAL_ERROR;
  575. });
  576. auto find_res2 = find_res1->second.find(orig_switch_name);
  577. auto find_res3 = find_res1->second.find(cast_node->GetName());
  578. GE_IF_BOOL_EXEC((find_res2 != find_res1->second.end()) && (find_res3 == find_res1->second.end()), {
  579. find_res1->second.erase(find_res2);
  580. find_res1->second.insert(cast_node->GetName());
  581. continue;
  582. });
  583. }
  584. return SUCCESS;
  585. }
  586. ///
  587. /// @brief Modify out ctl edge for switch_node
  588. /// @param [in] switch_node
  589. /// @param [in] stream_switch
  590. /// @param [in] active_node
  591. /// @return Status
  592. ///
  593. Status SwitchToStreamSwitchPass::ModifySwitchOutCtlEdges(const NodePtr &switch_node, const NodePtr &stream_switch,
  594. const NodePtr &active_node) {
  595. GELOGD("ModifySwitchOutCtlEdges: switch_node=%s, stream_switch=%s, active_node=%s", switch_node->GetName().c_str(),
  596. stream_switch->GetName().c_str(), active_node->GetName().c_str());
  597. auto find_res = switch_node_map_.find(switch_node);
  598. GE_IF_BOOL_EXEC(find_res == switch_node_map_.end(), {
  599. GELOGE(INTERNAL_ERROR, "StreamSwitch node %s not found in switch_node_map_.", switch_node->GetName().c_str());
  600. return INTERNAL_ERROR;
  601. });
  602. GE_IF_BOOL_EXEC(find_res->second.empty(), {
  603. GELOGE(INTERNAL_ERROR, "true_nodes of StreamSwitch node %s is empty.", switch_node->GetName().c_str());
  604. return INTERNAL_ERROR;
  605. });
  606. for (const NodePtr &node : switch_node->GetOutControlNodes()) {
  607. GE_CHK_STATUS(GraphUtils::RemoveEdge(switch_node->GetOutControlAnchor(), node->GetInControlAnchor()),
  608. "Remove ctl edge failed.");
  609. OpDescPtr op_desc = node->GetOpDesc();
  610. GE_CHECK_NOTNULL(op_desc);
  611. std::string orig_name = op_desc->GetName();
  612. GE_IF_BOOL_EXEC(op_desc->HasAttr(ATTR_NAME_ORIG_NODE_NAME), {
  613. if (!AttrUtils::GetStr(op_desc, ATTR_NAME_ORIG_NODE_NAME, orig_name) || orig_name.empty()) {
  614. GELOGE(INTERNAL_ERROR, "Get attr ATTR_NAME_ORIG_NODE_NAME failed, node: %s.", op_desc->GetName().c_str());
  615. return INTERNAL_ERROR;
  616. }
  617. });
  618. if (find_res->second.find(orig_name) == find_res->second.end()) {
  619. auto active_out_ctrl_anchor = active_node->GetOutControlAnchor();
  620. GE_CHECK_NOTNULL(active_out_ctrl_anchor);
  621. GE_IF_BOOL_EXEC(!active_out_ctrl_anchor->IsLinkedWith(node->GetInControlAnchor()), {
  622. GE_CHK_STATUS(GraphUtils::AddEdge(active_out_ctrl_anchor, node->GetInControlAnchor()), "Add ctl edge failed.");
  623. });
  624. } else {
  625. auto switch_out_ctrl_anchor = stream_switch->GetOutControlAnchor();
  626. GE_CHECK_NOTNULL(switch_out_ctrl_anchor);
  627. GE_IF_BOOL_EXEC(!switch_out_ctrl_anchor->IsLinkedWith(node->GetInControlAnchor()), {
  628. GE_CHK_STATUS(GraphUtils::AddEdge(switch_out_ctrl_anchor, node->GetInControlAnchor()), "Add ctl edge failed.");
  629. });
  630. }
  631. }
  632. GE_IF_BOOL_EXEC(switch_node != stream_switch, (void)bypass_nodes_.insert(switch_node));
  633. return SUCCESS;
  634. }
  635. ///
  636. /// @brief Check duplicate node_name
  637. /// @param [in] node_name
  638. /// @return std::string
  639. ///
  640. std::string SwitchToStreamSwitchPass::CheckDuplicateName(const std::string &node_name) {
  641. std::string tmp_name = node_name;
  642. auto iter = node_num_map_.find(tmp_name);
  643. if (iter != node_num_map_.end()) {
  644. tmp_name = tmp_name + "_" + std::to_string(iter->second);
  645. (iter->second)++;
  646. } else {
  647. node_num_map_[tmp_name] = 1;
  648. }
  649. return tmp_name;
  650. }
  651. ///
  652. /// @brief Move Control Edges
  653. /// @param [in] old_node
  654. /// @param [in] new_node
  655. /// @return void
  656. ///
  657. void SwitchToStreamSwitchPass::MoveCtrlEdges(const NodePtr &old_node, const NodePtr &new_node) {
  658. GE_IF_BOOL_EXEC(old_node == new_node, return );
  659. auto iter = switch_cyclic_map_.find(old_node);
  660. bool check_flag = (iter != switch_cyclic_map_.end());
  661. for (const NodePtr &in_node : old_node->GetInControlNodes()) {
  662. auto out_ctrl_anchor = in_node->GetOutControlAnchor();
  663. GE_CHECK_NOTNULL_JUST_RETURN(out_ctrl_anchor);
  664. if (check_flag && (iter->second.count(in_node->GetName()) > 0)) {
  665. for (const auto &out_node : old_node->GetOutAllNodes()) {
  666. GE_IF_BOOL_EXEC(!out_ctrl_anchor->IsLinkedWith(out_node->GetInControlAnchor()), {
  667. GE_CHK_STATUS(GraphUtils::AddEdge(out_ctrl_anchor, out_node->GetInControlAnchor()),
  668. "Add in ctrl edge failed.");
  669. });
  670. }
  671. } else {
  672. GE_IF_BOOL_EXEC(!out_ctrl_anchor->IsLinkedWith(new_node->GetInControlAnchor()), {
  673. GE_CHK_STATUS(GraphUtils::AddEdge(out_ctrl_anchor, new_node->GetInControlAnchor()),
  674. "Add in ctrl edge failed.");
  675. });
  676. }
  677. GE_CHK_STATUS(GraphUtils::RemoveEdge(out_ctrl_anchor, old_node->GetInControlAnchor()),
  678. "Remove in ctrl edge failed.");
  679. }
  680. for (const NodePtr &out_node : old_node->GetOutControlNodes()) {
  681. GE_IF_BOOL_EXEC(!new_node->GetOutControlAnchor()->IsLinkedWith(out_node->GetInControlAnchor()), {
  682. GE_CHK_STATUS(GraphUtils::AddEdge(new_node->GetOutControlAnchor(), out_node->GetInControlAnchor()),
  683. "Add out ctrl edge failed.");
  684. });
  685. GE_CHK_STATUS(GraphUtils::RemoveEdge(old_node->GetOutControlAnchor(), out_node->GetInControlAnchor()),
  686. "Remove out ctrl edge failed.");
  687. }
  688. }
  689. } // namespace ge

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