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.

branch_culling.cc 27 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "optimizer/irpass/branch_culling.h"
  17. #include <memory>
  18. #include <utility>
  19. #include <unordered_map>
  20. #include "ir/func_graph.h"
  21. #include "ir/func_graph_cloner.h"
  22. #include "operator/ops.h"
  23. namespace mindspore {
  24. namespace opt {
  25. namespace irpass {
  26. namespace internal {
  27. AnfNodePtr GenerateSwitchNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data,
  28. int switch_idx) {
  29. auto switch_node = prim::GetPythonOps("geswitch", "mindspore.ops.functional")->cast<PrimitivePtr>();
  30. std::vector<AnfNodePtr> switch_nodes{NewValueNode(switch_node), data, cond};
  31. auto switch_apply = graph->NewCNode(switch_nodes);
  32. std::vector<AnfNodePtr> tuple_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), switch_apply,
  33. NewValueNode(MakeValue(switch_idx))};
  34. return graph->NewCNode(tuple_getitem_nodes);
  35. }
  36. AnfNodePtr GenerateSwitchTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  37. return GenerateSwitchNode(graph, cond, data, 1);
  38. }
  39. AnfNodePtr GenerateSwitchFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  40. return GenerateSwitchNode(graph, cond, data, 0);
  41. }
  42. bool InConvertWhiteList(const AnfNodePtr &node, size_t index) {
  43. // The CNode inputs of the following Primitive with index in std::vector<size_t> should not be guarded by geswitch
  44. // node because it is attribute or ge specific reason.
  45. // Example : when convert CNode(kPrimReduceSum, x, axis), node of index 2 in CNode->inputs is axis which should not be
  46. // converted to switch guarded.
  47. std::vector<std::pair<PrimitivePtr, std::vector<size_t>>> white_list(
  48. {{prim::kPrimApplyMomentum, {1, 2}}, {prim::kPrimMomentum, {2, 3}}, {prim::kPrimStateSetItem, {1}},
  49. {prim::kPrimEnvGetItem, {1}}, {prim::kPrimEnvSetItem, {1}}, {prim::kPrimReduceSum, {2}},
  50. {prim::kPrimReduceMean, {2}}, {prim::kPrimReduceAll, {2}}, {prim::kPrimCast, {2}},
  51. {prim::kPrimTranspose, {2}}, {prim::kPrimOneHot, {2}}, {prim::kPrimGatherV2, {3}},
  52. {prim::kPrimReshape, {2}}, {prim::kPrimAssign, {1}}, {prim::kPrimAssignAdd, {1}},
  53. {prim::kPrimAssignSub, {1}}, {prim::kPrimTensorSummary, {1}}, {prim::kPrimImageSummary, {1}},
  54. {prim::kPrimScalarSummary, {1}}, {prim::kPrimHistogramSummary, {1}}});
  55. for (auto &item : white_list) {
  56. auto matched = std::any_of(item.second.begin(), item.second.end(), [&item, &node, &index](size_t idx) {
  57. return IsPrimitiveCNode(node, item.first) && idx == index;
  58. });
  59. if (matched) {
  60. return true;
  61. }
  62. }
  63. std::vector<PrimitivePtr> adapter_convert_ops = {prim::kPrimDepend, prim::kPrimControlDepend};
  64. for (auto &item : adapter_convert_ops) {
  65. if (IsPrimitiveCNode(node, item)) {
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71. using NodeInputReplMap = std::unordered_map<std::pair<AnfNodePtr, size_t>, AnfNodePtr, PairHasher>;
  72. // replace the nodes which should be changed
  73. void RunSwitchNodeReplace(const FuncGraphManagerPtr &manager, std::vector<std::pair<CNodePtr, CNodePtr>> nodes_changed,
  74. std::unordered_map<AnfNodePtr, AnfNodePtr> repl_node, NodeInputReplMap repl_node_inputs) {
  75. for (auto &node_pair : nodes_changed) {
  76. CNodePtr old_node = node_pair.first;
  77. CNodePtr new_node = node_pair.second;
  78. MS_EXCEPTION_IF_NULL(old_node);
  79. MS_EXCEPTION_IF_NULL(new_node);
  80. for (size_t i = 0; i < old_node->size(); i++) {
  81. auto input = old_node->input(i);
  82. if (repl_node.count(input) != 0) {
  83. new_node->add_input(repl_node[input]);
  84. } else if (repl_node_inputs.count(std::pair<AnfNodePtr, size_t>(old_node, i)) != 0) {
  85. new_node->add_input(repl_node_inputs[std::pair<AnfNodePtr, size_t>(old_node, i)]);
  86. } else {
  87. new_node->add_input(input);
  88. }
  89. }
  90. }
  91. for (auto &item : repl_node) {
  92. if (!manager->Replace(item.first, item.second)) {
  93. MS_LOG(EXCEPTION) << "TransformGraphDependNode replace node failed original:" << item.first->DebugString()
  94. << " to new: " << item.second->DebugString();
  95. }
  96. }
  97. }
  98. // trace the node that should add switch and replace them with new nodes in the graph
  99. FuncGraphPtr TransformGraphCondBranchNodes(
  100. const FuncGraphPtr &graph, const AnfNodePtr &cond,
  101. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func) {
  102. auto manager = graph->manager();
  103. MS_EXCEPTION_IF_NULL(manager);
  104. // record the node that has been changed
  105. std::vector<std::pair<CNodePtr, CNodePtr>> nodes_changed;
  106. // record the node to be replaced
  107. std::unordered_map<AnfNodePtr, AnfNodePtr> repl_node;
  108. // record the node input to be replaced
  109. NodeInputReplMap repl_node_inputs;
  110. const AnfNodeSet &nodes = manager->nodes()[graph];
  111. for (auto &node : nodes) {
  112. MS_EXCEPTION_IF_NULL(node);
  113. if (!node->isa<CNode>()) {
  114. continue;
  115. }
  116. auto inputs = node->cast<CNodePtr>()->inputs();
  117. bool should_replace = false;
  118. // if the apply input does not belong to graph, insert a switch node
  119. for (size_t index = 0; index < inputs.size(); index++) {
  120. auto input_node = inputs[index];
  121. MS_EXCEPTION_IF_NULL(input_node);
  122. // for some ops input should not guard it with switch
  123. if (InConvertWhiteList(node, index)) {
  124. continue;
  125. }
  126. // If the input for node is not the graph belonged, or it is an ValueNode.
  127. // Bypass the Primitive node which is inputs[0].
  128. if ((index >= 1 && inputs[index]->func_graph() != nullptr && inputs[index]->func_graph() != graph) ||
  129. ((index >= 1 && inputs[index]->isa<ValueNode>()))) {
  130. input_node = generate_func(graph, cond, inputs[index]);
  131. repl_node_inputs[std::pair<AnfNodePtr, size_t>(node, index)] = input_node;
  132. should_replace = true;
  133. }
  134. if (input_node == nullptr) {
  135. MS_LOG(EXCEPTION) << "generate switch node failed";
  136. }
  137. }
  138. if (should_replace) {
  139. auto new_node = graph->NewCNode();
  140. repl_node[node] = new_node;
  141. nodes_changed.emplace_back(node->cast<CNodePtr>(), new_node);
  142. }
  143. }
  144. RunSwitchNodeReplace(manager, nodes_changed, repl_node, repl_node_inputs);
  145. return graph;
  146. }
  147. struct SharedOp {
  148. tensor::TensorPtr const_data;
  149. CNodePtr square_ops[2];
  150. CNodePtr merge_ops[2];
  151. } MergeNetOutput;
  152. inline tensor::TensorPtr GetConstData() { return MergeNetOutput.const_data; }
  153. inline void SetConstData(const tensor::TensorPtr &const_value) { MergeNetOutput.const_data = const_value; }
  154. inline CNodePtr GetSquareOp(int switch_idx) { return MergeNetOutput.square_ops[switch_idx]; }
  155. inline void SetSquareOp(int switch_idx, const CNodePtr &op) { MergeNetOutput.square_ops[switch_idx] = op; }
  156. inline CNodePtr GetMergeOp(int switch_idx) { return MergeNetOutput.merge_ops[switch_idx]; }
  157. inline void SetMergeOp(int switch_idx, const CNodePtr &op) { MergeNetOutput.merge_ops[switch_idx] = op; }
  158. inline void ResetSharedOp() {
  159. SetConstData(nullptr);
  160. SetSquareOp(0, nullptr);
  161. SetSquareOp(1, nullptr);
  162. SetMergeOp(0, nullptr);
  163. SetMergeOp(1, nullptr);
  164. }
  165. tensor::TensorPtr ConstData() {
  166. std::vector<int> shp = {1};
  167. tensor::TensorPtr const_data = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  168. auto *val = static_cast<int32_t *>(const_data->data_c(true));
  169. *val = 0;
  170. return const_data;
  171. }
  172. CNodePtr SquareOp(const FuncGraphPtr &graph, const AnfNodePtr &cond, int switch_idx,
  173. const tensor::TensorPtr &const_data) {
  174. auto PrimSquare = prim::GetPythonOps("square", "mindspore.ops.functional")->cast<PrimitivePtr>();
  175. // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
  176. // the other use the opposite
  177. auto ctrl_data = NewValueNode(const_data);
  178. auto ctrl_node = GenerateSwitchNode(graph, cond, ctrl_data, switch_idx);
  179. std::vector<AnfNodePtr> square_nodes{NewValueNode(PrimSquare), ctrl_node};
  180. auto square_op = graph->NewCNode(square_nodes);
  181. return square_op;
  182. }
  183. CNodePtr MergeNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, int switch_idx,
  184. const tensor::TensorPtr &const_data, const CNodePtr &square_op) {
  185. // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
  186. // the other use the opposite
  187. auto oppsite_ctrl_data = NewValueNode(const_data);
  188. auto opposite_ctrl_node = GenerateSwitchNode(graph, cond, oppsite_ctrl_data, 1 - switch_idx);
  189. std::vector<AnfNodePtr> merge_nodes;
  190. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  191. merge_nodes.push_back(NewValueNode(PrimMerge));
  192. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), square_op, opposite_ctrl_node};
  193. merge_nodes.push_back(graph->NewCNode(make_tuple_nodes));
  194. auto merge_op = graph->NewCNode(merge_nodes);
  195. return merge_op;
  196. }
  197. // construct a depend node with merge output node, merge(square_op(switch(ctrl_data)), switch(opposite_ctrl_data))
  198. // control_depend(output_node, square_op)
  199. AnfNodePtr GenerateSwitchDependNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &output_node,
  200. int switch_idx) {
  201. tensor::TensorPtr const_data = GetConstData();
  202. if (const_data == nullptr) {
  203. const_data = ConstData();
  204. SetConstData(const_data);
  205. }
  206. CNodePtr square_op = GetSquareOp(switch_idx);
  207. if (square_op == nullptr) {
  208. square_op = SquareOp(graph, cond, switch_idx, const_data);
  209. SetSquareOp(switch_idx, square_op);
  210. }
  211. CNodePtr merge_op = GetMergeOp(switch_idx);
  212. if (merge_op == nullptr) {
  213. merge_op = MergeNode(graph, cond, switch_idx, const_data, square_op);
  214. SetMergeOp(switch_idx, merge_op);
  215. }
  216. std::vector<AnfNodePtr> control_depend_nodes{NewValueNode(prim::kPrimControlDepend), output_node, square_op};
  217. auto control_depend_op = graph->NewCNode(control_depend_nodes);
  218. std::vector<AnfNodePtr> depend_nodes{NewValueNode(prim::kPrimDepend), merge_op, control_depend_op};
  219. auto depend_op = graph->NewCNode(depend_nodes);
  220. return depend_op;
  221. }
  222. // construct a merge output and add dependency with the netoutput node from control_depend
  223. // we need to reserve the control_depend node, besides the generated merge node and control_depend node
  224. CNodePtr GenerateSwitchControlDependNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  225. const AnfNodePtr &ctrl_dep_node, const AnfNodePtr &ctrl_depend_dst,
  226. int switch_idx) {
  227. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  228. auto PrimSquare = prim::GetPythonOps("square", "mindspore.ops.functional")->cast<PrimitivePtr>();
  229. std::vector<int> shp = {1};
  230. tensor::TensorPtr const_data = std::make_shared<tensor::Tensor>(kInt32->type_id(), shp);
  231. auto *val = static_cast<int32_t *>(const_data->data_c(true));
  232. *val = 0;
  233. // for the control_depend netoutput node , add two const data to merge the flow ,one for depended node with same
  234. // switch the other use the opposite
  235. auto ctrl_data = NewValueNode(const_data);
  236. auto oppsite_ctrl_data = NewValueNode(const_data);
  237. auto ctrl_node = GenerateSwitchNode(graph, cond, ctrl_data, switch_idx);
  238. auto opposite_ctrl_node = GenerateSwitchNode(graph, cond, oppsite_ctrl_data, 1 - switch_idx);
  239. std::vector<AnfNodePtr> square_nodes{NewValueNode(PrimSquare), ctrl_node};
  240. auto square_op = graph->NewCNode(square_nodes);
  241. std::vector<AnfNodePtr> merge_nodes;
  242. merge_nodes.push_back(NewValueNode(PrimMerge));
  243. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), square_op, opposite_ctrl_node};
  244. merge_nodes.push_back(graph->NewCNode(make_tuple_nodes));
  245. auto merge_output = graph->NewCNode(merge_nodes);
  246. std::vector<AnfNodePtr> control_depend_nodes{NewValueNode(prim::kPrimControlDepend), ctrl_depend_dst, square_op};
  247. auto cond_dep_output = graph->NewCNode(control_depend_nodes);
  248. std::vector<AnfNodePtr> depended_make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), ctrl_dep_node, merge_output,
  249. cond_dep_output};
  250. return graph->NewCNode(depended_make_tuple_nodes);
  251. }
  252. // generate switch nodes for true graph node inputs
  253. AnfNodePtr GenerateSwitchDependTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  254. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  255. return GenerateSwitchDependNode(graph, cond, data, 1);
  256. }
  257. // generate switch nodes for false graph node inputs
  258. AnfNodePtr GenerateSwitchDependFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  259. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  260. return GenerateSwitchDependNode(graph, cond, data, 0);
  261. }
  262. // generate switch nodes for true graph node inputs
  263. CNodePtr GenerateSwitchControlDependTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  264. const AnfNodePtr &con_input, const AnfNodePtr &output) {
  265. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  266. return GenerateSwitchControlDependNode(graph, cond, con_input, output, 1);
  267. }
  268. // generate switch nodes for false graph node inputs
  269. CNodePtr GenerateSwitchControlDependFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  270. const AnfNodePtr &con_input, const AnfNodePtr &output) {
  271. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  272. return GenerateSwitchControlDependNode(graph, cond, con_input, output, 0);
  273. }
  274. // to judge if the node used in ControlDepend is a net output node
  275. bool IsNetOutputNode(const FuncGraphManagerPtr &manager, const AnfNodePtr &node) {
  276. auto uses = manager->node_users()[node];
  277. bool is_output_node = true;
  278. for (auto &item : uses) {
  279. if (IsPrimitiveCNode(item.first, prim::kPrimControlDepend) || IsPrimitiveCNode(item.first, prim::kPrimDepend)) {
  280. continue;
  281. }
  282. is_output_node = false;
  283. break;
  284. }
  285. return is_output_node;
  286. }
  287. // generate node for Depended MakeTuple
  288. void GenerateReplNodeForDependMakeTuple(
  289. const AnfNodePtr &depended_node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
  290. const std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> &repl_node,
  291. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func,
  292. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  293. MS_EXCEPTION_IF_NULL(graph->manager());
  294. auto make_tuple_inputs = depended_node->cast<CNodePtr>()->inputs();
  295. const size_t make_tuple_begin_idx = 1;
  296. std::vector<AnfNodePtr> new_make_tuple_nodes;
  297. bool replace_make_tuple = false;
  298. new_make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
  299. for (size_t idx = make_tuple_begin_idx; idx < make_tuple_inputs.size(); idx++) {
  300. auto depended_tuple_input_node = make_tuple_inputs[idx];
  301. if (IsPrimitiveCNode(depended_tuple_input_node->cast<CNodePtr>(), prim::kPrimDepend)) {
  302. new_make_tuple_nodes.push_back(depended_tuple_input_node);
  303. continue;
  304. }
  305. if (IsPrimitiveCNode(depended_tuple_input_node->cast<CNodePtr>(), prim::kPrimControlDepend)) {
  306. // only when the control depend input is not square op (the op to use as merge output)
  307. auto control_inputs = depended_tuple_input_node->cast<CNodePtr>()->inputs();
  308. if (control_inputs.size() != 3) {
  309. MS_LOG(EXCEPTION) << "controldepend input size != 3, got " << control_inputs.size();
  310. }
  311. // control inputs: primitive, src, dst
  312. auto dst_node = control_inputs[2];
  313. if (!IsPrimitiveCNode(dst_node, prim::kPrimSquare) && IsNetOutputNode(graph->manager(), dst_node)) {
  314. auto gen_node = gen_ctl_depd_func(graph, cond, make_tuple_inputs[idx], dst_node);
  315. MS_EXCEPTION_IF_NULL(gen_node);
  316. auto tuple_inputs = gen_node->inputs();
  317. // add depended tuple inputs to new_make_tuple directly
  318. for (size_t i = 1; i < tuple_inputs.size(); i++) {
  319. new_make_tuple_nodes.push_back(tuple_inputs[i]);
  320. }
  321. }
  322. replace_make_tuple = true;
  323. continue;
  324. }
  325. if (graph->manager()->node_users()[depended_tuple_input_node].size() == 1) {
  326. auto gen_node = generate_func(graph, cond, depended_tuple_input_node);
  327. new_make_tuple_nodes.push_back(gen_node);
  328. replace_make_tuple = true;
  329. continue;
  330. }
  331. MS_LOG(WARNING) << "depended node being used by others, ";
  332. }
  333. if (replace_make_tuple) {
  334. auto make_tuple_op = graph->NewCNode(new_make_tuple_nodes);
  335. (*repl_node)[depended_node] = make_tuple_op;
  336. }
  337. }
  338. // generate a replace depend node for a single network output node
  339. void GenerateRepDepend(
  340. const CNodePtr &node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
  341. const std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> &repl_node,
  342. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func,
  343. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  344. auto inputs = node->inputs();
  345. if (inputs.size() != 3) {
  346. MS_LOG(EXCEPTION) << "Inputs should be [depend, actual_value, depended_node].";
  347. }
  348. std::vector<AnfNodePtr> new_depened_inputs;
  349. // Inputs should be [depend, actual_value, depended_node]
  350. auto depended_node = inputs[2];
  351. new_depened_inputs.push_back(inputs[0]);
  352. new_depened_inputs.push_back(inputs[1]);
  353. // depended node should be make_tuple or a single depended node
  354. if (IsPrimitiveCNode(depended_node, prim::kPrimMakeTuple)) {
  355. GenerateReplNodeForDependMakeTuple(depended_node, graph, cond, repl_node, generate_func, gen_ctl_depd_func);
  356. } else if (IsPrimitiveCNode(depended_node, prim::kPrimControlDepend)) {
  357. // only when the control depend input is not square op (the op to use as merge output)
  358. auto control_inputs = depended_node->cast<CNodePtr>()->inputs();
  359. // control inputs: primitive, src, dst
  360. if (control_inputs.size() != 3) {
  361. MS_LOG(EXCEPTION) << "controldepend input size != 3, got " << control_inputs.size();
  362. }
  363. auto dst_node = control_inputs[2];
  364. if (!IsPrimitiveCNode(dst_node, prim::kPrimSquare) && IsNetOutputNode(graph->manager(), dst_node)) {
  365. auto gen_node = gen_ctl_depd_func(graph, cond, depended_node, dst_node);
  366. (*repl_node)[depended_node] = gen_node;
  367. }
  368. } else {
  369. // Check if there is only single user for depend_node.
  370. if (graph->manager()->node_users()[depended_node].size() == 1) {
  371. auto gen_node = generate_func(graph, cond, depended_node);
  372. (*repl_node)[depended_node] = gen_node;
  373. } else {
  374. MS_LOG(WARNING) << "depended node being used by others";
  375. }
  376. }
  377. }
  378. // generate depend node for netoutput node, to resolve the stream synchronize problem of ge
  379. // traverse all nodes of depend node, find the graph output node , generaete a merge node of (square, const)
  380. // and add control_depend of graph output node and square node.
  381. FuncGraphPtr TransformGraphDependNode(
  382. const FuncGraphPtr &graph, const AnfNodePtr &cond,
  383. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &gen_depend_func,
  384. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  385. auto manager = graph->manager();
  386. MS_EXCEPTION_IF_NULL(manager);
  387. ResetSharedOp();
  388. std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> repl_node =
  389. std::make_shared<std::unordered_map<AnfNodePtr, AnfNodePtr>>(); // record the node to be replaced
  390. const AnfNodeSet &nodes = manager->nodes()[graph];
  391. for (auto &node : nodes) {
  392. MS_EXCEPTION_IF_NULL(node);
  393. if (!node->isa<CNode>()) {
  394. continue;
  395. }
  396. if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  397. auto cnode = node->cast<CNodePtr>();
  398. if (cnode->size() != 3) {
  399. MS_LOG(EXCEPTION) << "Dependnode input size != 3";
  400. }
  401. auto depended_node = cnode->input(2);
  402. MS_EXCEPTION_IF_NULL(depended_node);
  403. if (!depended_node->isa<CNode>()) {
  404. continue;
  405. }
  406. if (IsPrimitiveCNode(depended_node, prim::kPrimDepend)) {
  407. continue;
  408. }
  409. GenerateRepDepend(cnode, graph, cond, repl_node, gen_depend_func, gen_ctl_depd_func);
  410. }
  411. }
  412. ResetSharedOp();
  413. for (auto &item : *repl_node) {
  414. if (!manager->Replace(item.first, item.second)) {
  415. MS_LOG(EXCEPTION) << "TransformGraphDependNode replace node failed";
  416. }
  417. }
  418. return graph;
  419. }
  420. FuncGraphPtr TransformGraphCondTrueBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
  421. (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchTrueNode);
  422. return TransformGraphDependNode(graph, cond, GenerateSwitchDependTrueNode, GenerateSwitchControlDependTrueNode);
  423. }
  424. FuncGraphPtr TransformGraphCondFalseBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
  425. (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchFalseNode);
  426. return TransformGraphDependNode(graph, cond, GenerateSwitchDependFalseNode, GenerateSwitchControlDependFalseNode);
  427. }
  428. // judge if the true and false graph output is compatible(they shall have same tuple size)
  429. bool GraphOutputCompatible(const AbstractBasePtr &true_branch_abs, const AbstractBasePtr &false_branch_abs) {
  430. MS_EXCEPTION_IF_NULL(true_branch_abs);
  431. MS_EXCEPTION_IF_NULL(false_branch_abs);
  432. if (true_branch_abs->isa<abstract::AbstractTuple>() && false_branch_abs->isa<abstract::AbstractTuple>()) {
  433. abstract::AbstractTuplePtr true_branch_tuple = true_branch_abs->cast<abstract::AbstractTuplePtr>();
  434. abstract::AbstractTuplePtr false_branch_tuple = false_branch_abs->cast<abstract::AbstractTuplePtr>();
  435. if (true_branch_tuple->elements().size() != false_branch_tuple->elements().size()) {
  436. MS_LOG(ERROR) << "true branch size:" << true_branch_tuple->elements().size()
  437. << ", not equal to false banch size:" << false_branch_tuple->elements().size() << " ";
  438. return false;
  439. }
  440. bool all_compatible = true;
  441. for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
  442. all_compatible =
  443. all_compatible && GraphOutputCompatible(true_branch_tuple->elements()[i], false_branch_tuple->elements()[i]);
  444. }
  445. return all_compatible;
  446. }
  447. TypePtr true_branch_type = true_branch_abs->BuildType();
  448. TypePtr false_branch_type = false_branch_abs->BuildType();
  449. MS_LOG(DEBUG) << "branch output Type equal?" << (*true_branch_type == *false_branch_type)
  450. << " true:" << true_branch_type->ToString() << " false:" << false_branch_type->ToString();
  451. return (*true_branch_type == *false_branch_type);
  452. }
  453. AnfNodePtr GenerateMergeNodes(const AnfNodePtr &true_output_node, const AnfNodePtr &false_output_node,
  454. const AbstractBasePtr &true_graph_output_abs,
  455. const AbstractBasePtr &false_graph_output_abs, const AnfNodePtr &cond) {
  456. MS_EXCEPTION_IF_NULL(true_graph_output_abs);
  457. MS_EXCEPTION_IF_NULL(false_graph_output_abs);
  458. MS_EXCEPTION_IF_NULL(cond);
  459. MS_EXCEPTION_IF_NULL(cond->func_graph());
  460. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  461. MS_EXCEPTION_IF_NULL(PrimMerge);
  462. if (!true_graph_output_abs->isa<abstract::AbstractTuple>()) {
  463. std::vector<AnfNodePtr> merge_nodes;
  464. merge_nodes.push_back(NewValueNode(PrimMerge));
  465. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), true_output_node, false_output_node};
  466. merge_nodes.push_back(cond->func_graph()->NewCNode(make_tuple_nodes));
  467. std::vector<AnfNodePtr> tuple_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem),
  468. cond->func_graph()->NewCNode(merge_nodes), NewValueNode(MakeValue(0))};
  469. return cond->func_graph()->NewCNode(tuple_getitem_nodes);
  470. } else {
  471. abstract::AbstractTuplePtr true_branch_tuple = true_graph_output_abs->cast<abstract::AbstractTuplePtr>();
  472. abstract::AbstractTuplePtr false_branch_tuple = false_graph_output_abs->cast<abstract::AbstractTuplePtr>();
  473. std::vector<AnfNodePtr> make_tuple_nodes;
  474. make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
  475. for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
  476. std::vector<AnfNodePtr> true_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), true_output_node,
  477. NewValueNode(MakeValue(SizeToInt(i)))};
  478. auto true_node = cond->func_graph()->NewCNode(true_getitem_nodes);
  479. std::vector<AnfNodePtr> false_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), false_output_node,
  480. NewValueNode(MakeValue(SizeToInt(i)))};
  481. auto false_node = cond->func_graph()->NewCNode(false_getitem_nodes);
  482. auto merge_node = GenerateMergeNodes(true_node, false_node, true_branch_tuple->elements()[i],
  483. false_branch_tuple->elements()[i], cond);
  484. make_tuple_nodes.push_back(merge_node);
  485. }
  486. return cond->func_graph()->NewCNode(make_tuple_nodes);
  487. }
  488. }
  489. AnfNodePtr TransformMergeBranches(const AnfNodePtr &true_output_node, const AnfNodePtr &false_output_node,
  490. const AbstractBasePtr &true_graph_output_abs,
  491. const AbstractBasePtr &false_graph_output_abs, const AnfNodePtr &cond) {
  492. if (!GraphOutputCompatible(true_graph_output_abs, false_graph_output_abs)) {
  493. MS_LOG(EXCEPTION) << "Switch output branch not compatible, true:" << true_graph_output_abs->ToString()
  494. << ", false:" << false_graph_output_abs->ToString();
  495. }
  496. return GenerateMergeNodes(true_output_node, false_output_node, true_graph_output_abs, false_graph_output_abs, cond);
  497. }
  498. } // namespace internal
  499. } // namespace irpass
  500. } // namespace opt
  501. } // namespace mindspore