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

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