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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. int64_t 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::kPrimGather, {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, prim::kPrimLoad};
  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. if (HasAbstractMonad(input_node)) {
  141. // Do not guard with switch for monad inputs.
  142. continue;
  143. }
  144. MS_EXCEPTION_IF_NULL(input_node);
  145. // for some ops input should not guard it with switch
  146. if (InConvertWhiteList(node, index)) {
  147. continue;
  148. }
  149. // If the input for node is not the graph belonged, or it is an ValueNode.
  150. // Bypass the Primitive node which is inputs[0].
  151. if ((index >= 1 && inputs[index]->func_graph() != nullptr && inputs[index]->func_graph() != graph) ||
  152. ((index >= 1 && inputs[index]->isa<ValueNode>()))) {
  153. input_node = generate_func(graph, cond, inputs[index]);
  154. repl_node_inputs[std::pair<AnfNodePtr, size_t>(node, index)] = input_node;
  155. should_replace = true;
  156. }
  157. if (input_node == nullptr) {
  158. MS_LOG(EXCEPTION) << "generate switch node failed";
  159. }
  160. }
  161. if (should_replace) {
  162. auto new_node = graph->NewCNode();
  163. repl_node[node] = new_node;
  164. nodes_changed.emplace_back(node->cast<CNodePtr>(), new_node);
  165. }
  166. }
  167. RunSwitchNodeReplace(manager, nodes_changed, repl_node, repl_node_inputs, graph);
  168. return graph;
  169. }
  170. struct SharedOp {
  171. tensor::TensorPtr const_data;
  172. CNodePtr square_ops[2];
  173. CNodePtr merge_ops[2];
  174. } MergeNetOutput;
  175. inline tensor::TensorPtr GetConstData() { return MergeNetOutput.const_data; }
  176. inline void SetConstData(const tensor::TensorPtr &const_value) { MergeNetOutput.const_data = const_value; }
  177. inline CNodePtr GetSquareOp(int64_t switch_idx) { return MergeNetOutput.square_ops[switch_idx]; }
  178. inline void SetSquareOp(int64_t switch_idx, const CNodePtr &op) { MergeNetOutput.square_ops[switch_idx] = op; }
  179. inline CNodePtr GetMergeOp(int64_t switch_idx) { return MergeNetOutput.merge_ops[switch_idx]; }
  180. inline void SetMergeOp(int64_t switch_idx, const CNodePtr &op) { MergeNetOutput.merge_ops[switch_idx] = op; }
  181. inline void ResetSharedOp() {
  182. SetConstData(nullptr);
  183. SetSquareOp(0, nullptr);
  184. SetSquareOp(1, nullptr);
  185. SetMergeOp(0, nullptr);
  186. SetMergeOp(1, nullptr);
  187. }
  188. tensor::TensorPtr ConstData() {
  189. std::vector<int64_t> shp = {1};
  190. tensor::TensorPtr const_data = std::make_shared<tensor::Tensor>(kInt64->type_id(), shp);
  191. auto *val = static_cast<int64_t *>(const_data->data_c());
  192. *val = 0;
  193. return const_data;
  194. }
  195. CNodePtr SquareOp(const FuncGraphPtr &graph, const AnfNodePtr &cond, int64_t switch_idx,
  196. const tensor::TensorPtr &const_data) {
  197. auto PrimSquare = prim::GetPythonOps("square", "mindspore.ops.functional")->cast<PrimitivePtr>();
  198. // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
  199. // the other use the opposite
  200. auto ctrl_data = NewValueNode(const_data);
  201. auto ctrl_node = GenerateSwitchNode(graph, cond, ctrl_data, switch_idx);
  202. std::vector<AnfNodePtr> square_nodes{NewValueNode(PrimSquare), ctrl_node};
  203. auto square_op = graph->NewCNode(square_nodes);
  204. return square_op;
  205. }
  206. CNodePtr MergeNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, int64_t switch_idx,
  207. const tensor::TensorPtr &const_data, const CNodePtr &square_op) {
  208. // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
  209. // the other use the opposite
  210. auto oppsite_ctrl_data = NewValueNode(const_data);
  211. auto opposite_ctrl_node = GenerateSwitchNode(graph, cond, oppsite_ctrl_data, 1 - switch_idx);
  212. std::vector<AnfNodePtr> merge_nodes;
  213. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  214. merge_nodes.push_back(NewValueNode(PrimMerge));
  215. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), square_op, opposite_ctrl_node};
  216. merge_nodes.push_back(graph->NewCNode(make_tuple_nodes));
  217. auto merge_op = graph->NewCNode(merge_nodes);
  218. return merge_op;
  219. }
  220. // construct a depend node with merge output node, merge(square_op(switch(ctrl_data)), switch(opposite_ctrl_data))
  221. // control_depend(output_node, square_op)
  222. AnfNodePtr GenerateSwitchDependNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &output_node,
  223. int64_t switch_idx) {
  224. tensor::TensorPtr const_data = GetConstData();
  225. if (const_data == nullptr) {
  226. const_data = ConstData();
  227. SetConstData(const_data);
  228. }
  229. CNodePtr square_op = GetSquareOp(switch_idx);
  230. if (square_op == nullptr) {
  231. square_op = SquareOp(graph, cond, switch_idx, const_data);
  232. SetSquareOp(switch_idx, square_op);
  233. }
  234. CNodePtr merge_op = GetMergeOp(switch_idx);
  235. if (merge_op == nullptr) {
  236. merge_op = MergeNode(graph, cond, switch_idx, const_data, square_op);
  237. SetMergeOp(switch_idx, merge_op);
  238. }
  239. std::vector<AnfNodePtr> control_depend_nodes{NewValueNode(prim::kPrimControlDepend), output_node, square_op};
  240. auto control_depend_op = graph->NewCNode(control_depend_nodes);
  241. std::vector<AnfNodePtr> depend_nodes{NewValueNode(prim::kPrimDepend), merge_op, control_depend_op};
  242. auto depend_op = graph->NewCNode(depend_nodes);
  243. return depend_op;
  244. }
  245. // construct a merge output and add dependency with the netoutput node from control_depend
  246. // we need to reserve the control_depend node, besides the generated merge node and control_depend node
  247. CNodePtr GenerateSwitchControlDependNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  248. const AnfNodePtr &ctrl_dep_node, const AnfNodePtr &ctrl_depend_dst,
  249. int64_t switch_idx) {
  250. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  251. auto PrimSquare = prim::GetPythonOps("square", "mindspore.ops.functional")->cast<PrimitivePtr>();
  252. std::vector<int64_t> shp = {1};
  253. tensor::TensorPtr const_data = std::make_shared<tensor::Tensor>(kInt64->type_id(), shp);
  254. auto *val = static_cast<int64_t *>(const_data->data_c());
  255. *val = 0;
  256. // for the control_depend netoutput node , add two const data to merge the flow ,one for depended node with same
  257. // switch the other use the opposite
  258. auto ctrl_data = NewValueNode(const_data);
  259. auto oppsite_ctrl_data = NewValueNode(const_data);
  260. auto ctrl_node = GenerateSwitchNode(graph, cond, ctrl_data, switch_idx);
  261. auto opposite_ctrl_node = GenerateSwitchNode(graph, cond, oppsite_ctrl_data, 1 - switch_idx);
  262. std::vector<AnfNodePtr> square_nodes{NewValueNode(PrimSquare), ctrl_node};
  263. auto square_op = graph->NewCNode(square_nodes);
  264. std::vector<AnfNodePtr> merge_nodes;
  265. merge_nodes.push_back(NewValueNode(PrimMerge));
  266. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), square_op, opposite_ctrl_node};
  267. merge_nodes.push_back(graph->NewCNode(make_tuple_nodes));
  268. auto merge_output = graph->NewCNode(merge_nodes);
  269. std::vector<AnfNodePtr> control_depend_nodes{NewValueNode(prim::kPrimControlDepend), ctrl_depend_dst, square_op};
  270. auto cond_dep_output = graph->NewCNode(control_depend_nodes);
  271. std::vector<AnfNodePtr> depended_make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), ctrl_dep_node, merge_output,
  272. cond_dep_output};
  273. return graph->NewCNode(depended_make_tuple_nodes);
  274. }
  275. // generate switch nodes for true graph node inputs
  276. AnfNodePtr GenerateSwitchDependTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  277. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  278. return GenerateSwitchDependNode(graph, cond, data, 1);
  279. }
  280. // generate switch nodes for false graph node inputs
  281. AnfNodePtr GenerateSwitchDependFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
  282. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  283. return GenerateSwitchDependNode(graph, cond, data, 0);
  284. }
  285. // generate switch nodes for true graph node inputs
  286. CNodePtr GenerateSwitchControlDependTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  287. const AnfNodePtr &con_input, const AnfNodePtr &output) {
  288. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  289. return GenerateSwitchControlDependNode(graph, cond, con_input, output, 1);
  290. }
  291. // generate switch nodes for false graph node inputs
  292. CNodePtr GenerateSwitchControlDependFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond,
  293. const AnfNodePtr &con_input, const AnfNodePtr &output) {
  294. // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
  295. return GenerateSwitchControlDependNode(graph, cond, con_input, output, 0);
  296. }
  297. // to judge if the node used in ControlDepend is a net output node
  298. bool IsNetOutputNode(const FuncGraphManagerPtr &manager, const AnfNodePtr &node) {
  299. auto uses = manager->node_users()[node];
  300. bool is_output_node = true;
  301. for (auto &item : uses) {
  302. if (IsPrimitiveCNode(item.first, prim::kPrimControlDepend) || IsPrimitiveCNode(item.first, prim::kPrimDepend)) {
  303. continue;
  304. }
  305. is_output_node = false;
  306. break;
  307. }
  308. return is_output_node;
  309. }
  310. // generate node for Depended MakeTuple
  311. void GenerateReplNodeForDependMakeTuple(
  312. const AnfNodePtr &depended_node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
  313. const std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> &repl_node,
  314. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func,
  315. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  316. MS_EXCEPTION_IF_NULL(graph->manager());
  317. auto make_tuple_inputs = depended_node->cast<CNodePtr>()->inputs();
  318. const size_t make_tuple_begin_idx = 1;
  319. std::vector<AnfNodePtr> new_make_tuple_nodes;
  320. bool replace_make_tuple = false;
  321. new_make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
  322. for (size_t idx = make_tuple_begin_idx; idx < make_tuple_inputs.size(); idx++) {
  323. auto depended_tuple_input_node = make_tuple_inputs[idx];
  324. if (IsPrimitiveCNode(depended_tuple_input_node->cast<CNodePtr>(), prim::kPrimDepend)) {
  325. new_make_tuple_nodes.push_back(depended_tuple_input_node);
  326. continue;
  327. }
  328. if (IsPrimitiveCNode(depended_tuple_input_node->cast<CNodePtr>(), prim::kPrimControlDepend)) {
  329. // only when the control depend input is not square op (the op to use as merge output)
  330. auto control_inputs = depended_tuple_input_node->cast<CNodePtr>()->inputs();
  331. if (control_inputs.size() != 3) {
  332. MS_LOG(EXCEPTION) << "controldepend input size != 3, got " << control_inputs.size();
  333. }
  334. // control inputs: primitive, src, dst
  335. auto dst_node = control_inputs[2];
  336. if (!IsPrimitiveCNode(dst_node, prim::kPrimSquare) && IsNetOutputNode(graph->manager(), dst_node)) {
  337. auto gen_node = gen_ctl_depd_func(graph, cond, make_tuple_inputs[idx], dst_node);
  338. MS_EXCEPTION_IF_NULL(gen_node);
  339. auto tuple_inputs = gen_node->inputs();
  340. // add depended tuple inputs to new_make_tuple directly
  341. for (size_t i = 1; i < tuple_inputs.size(); i++) {
  342. new_make_tuple_nodes.push_back(tuple_inputs[i]);
  343. }
  344. }
  345. replace_make_tuple = true;
  346. continue;
  347. }
  348. if (graph->manager()->node_users()[depended_tuple_input_node].size() == 1) {
  349. auto gen_node = generate_func(graph, cond, depended_tuple_input_node);
  350. new_make_tuple_nodes.push_back(gen_node);
  351. replace_make_tuple = true;
  352. continue;
  353. }
  354. MS_LOG(WARNING) << "depended node being used by others, ";
  355. }
  356. if (replace_make_tuple) {
  357. auto make_tuple_op = graph->NewCNode(new_make_tuple_nodes);
  358. (*repl_node)[depended_node] = make_tuple_op;
  359. }
  360. }
  361. // generate a replace depend node for a single network output node
  362. void GenerateRepDepend(
  363. const CNodePtr &node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
  364. const std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> &repl_node,
  365. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func,
  366. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  367. auto inputs = node->inputs();
  368. if (inputs.size() != 3) {
  369. MS_LOG(EXCEPTION) << "Inputs should be [depend, actual_value, depended_node].";
  370. }
  371. std::vector<AnfNodePtr> new_depened_inputs;
  372. // Inputs should be [depend, actual_value, depended_node]
  373. auto depended_node = inputs[2];
  374. new_depened_inputs.push_back(inputs[0]);
  375. new_depened_inputs.push_back(inputs[1]);
  376. // depended node should be make_tuple or a single depended node
  377. if (IsPrimitiveCNode(depended_node, prim::kPrimMakeTuple)) {
  378. GenerateReplNodeForDependMakeTuple(depended_node, graph, cond, repl_node, generate_func, gen_ctl_depd_func);
  379. } else if (IsPrimitiveCNode(depended_node, prim::kPrimControlDepend)) {
  380. // only when the control depend input is not square op (the op to use as merge output)
  381. auto control_inputs = depended_node->cast<CNodePtr>()->inputs();
  382. // control inputs: primitive, src, dst
  383. if (control_inputs.size() != 3) {
  384. MS_LOG(EXCEPTION) << "controldepend input size != 3, got " << control_inputs.size();
  385. }
  386. auto dst_node = control_inputs[2];
  387. if (!IsPrimitiveCNode(dst_node, prim::kPrimSquare) && IsNetOutputNode(graph->manager(), dst_node)) {
  388. auto gen_node = gen_ctl_depd_func(graph, cond, depended_node, dst_node);
  389. (*repl_node)[depended_node] = gen_node;
  390. }
  391. } else {
  392. // Check if there is only single user for depend_node.
  393. if (graph->manager()->node_users()[depended_node].size() == 1) {
  394. auto gen_node = generate_func(graph, cond, depended_node);
  395. (*repl_node)[depended_node] = gen_node;
  396. } else {
  397. MS_LOG(WARNING) << "depended node being used by others";
  398. }
  399. }
  400. }
  401. // generate depend node for netoutput node, to resolve the stream synchronize problem of ge
  402. // traverse all nodes of depend node, find the graph output node , generaete a merge node of (square, const)
  403. // and add control_depend of graph output node and square node.
  404. FuncGraphPtr TransformGraphDependNode(
  405. const FuncGraphPtr &graph, const AnfNodePtr &cond,
  406. const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &gen_depend_func,
  407. const std::function<CNodePtr(FuncGraphPtr, AnfNodePtr, AnfNodePtr, AnfNodePtr)> &gen_ctl_depd_func) {
  408. auto manager = graph->manager();
  409. MS_EXCEPTION_IF_NULL(manager);
  410. ResetSharedOp();
  411. std::shared_ptr<std::unordered_map<AnfNodePtr, AnfNodePtr>> repl_node =
  412. std::make_shared<std::unordered_map<AnfNodePtr, AnfNodePtr>>(); // record the node to be replaced
  413. const AnfNodeSet &nodes = graph->nodes();
  414. for (auto &node : nodes) {
  415. MS_EXCEPTION_IF_NULL(node);
  416. if (!node->isa<CNode>()) {
  417. continue;
  418. }
  419. if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  420. auto cnode = node->cast<CNodePtr>();
  421. if (cnode->size() != 3) {
  422. MS_LOG(EXCEPTION) << "Dependnode input size != 3";
  423. }
  424. auto depended_node = cnode->input(2);
  425. MS_EXCEPTION_IF_NULL(depended_node);
  426. if (!depended_node->isa<CNode>()) {
  427. continue;
  428. }
  429. if (IsPrimitiveCNode(depended_node, prim::kPrimDepend)) {
  430. continue;
  431. }
  432. GenerateRepDepend(cnode, graph, cond, repl_node, gen_depend_func, gen_ctl_depd_func);
  433. }
  434. }
  435. ResetSharedOp();
  436. for (auto &item : *repl_node) {
  437. if (!manager->Replace(item.first, item.second)) {
  438. MS_LOG(EXCEPTION) << "TransformGraphDependNode replace node failed";
  439. }
  440. }
  441. return graph;
  442. }
  443. FuncGraphPtr TransformGraphCondTrueBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
  444. (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchTrueNode);
  445. return TransformGraphDependNode(graph, cond, GenerateSwitchDependTrueNode, GenerateSwitchControlDependTrueNode);
  446. }
  447. FuncGraphPtr TransformGraphCondFalseBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
  448. (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchFalseNode);
  449. return TransformGraphDependNode(graph, cond, GenerateSwitchDependFalseNode, GenerateSwitchControlDependFalseNode);
  450. }
  451. // judge if the true and false graph output is compatible(they shall have same tuple size)
  452. bool GraphOutputCompatible(const AbstractBasePtr &true_branch_abs, const AbstractBasePtr &false_branch_abs) {
  453. MS_EXCEPTION_IF_NULL(true_branch_abs);
  454. MS_EXCEPTION_IF_NULL(false_branch_abs);
  455. if (true_branch_abs->isa<abstract::AbstractTuple>() && false_branch_abs->isa<abstract::AbstractTuple>()) {
  456. abstract::AbstractTuplePtr true_branch_tuple = true_branch_abs->cast<abstract::AbstractTuplePtr>();
  457. abstract::AbstractTuplePtr false_branch_tuple = false_branch_abs->cast<abstract::AbstractTuplePtr>();
  458. if (true_branch_tuple->elements().size() != false_branch_tuple->elements().size()) {
  459. MS_LOG(ERROR) << "true branch size:" << true_branch_tuple->elements().size()
  460. << ", not equal to false branch size:" << false_branch_tuple->elements().size() << " ";
  461. return false;
  462. }
  463. bool all_compatible = true;
  464. for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
  465. all_compatible =
  466. all_compatible && GraphOutputCompatible(true_branch_tuple->elements()[i], false_branch_tuple->elements()[i]);
  467. }
  468. return all_compatible;
  469. }
  470. TypePtr true_branch_type = true_branch_abs->BuildType();
  471. TypePtr false_branch_type = false_branch_abs->BuildType();
  472. MS_LOG(DEBUG) << "branch output Type equal?" << (*true_branch_type == *false_branch_type)
  473. << " true:" << true_branch_type->ToString() << " false:" << false_branch_type->ToString();
  474. return (*true_branch_type == *false_branch_type);
  475. }
  476. AnfNodePtr GenerateMergeNodes(const AnfNodePtr &true_output_node, const AnfNodePtr &false_output_node,
  477. const AbstractBasePtr &true_graph_output_abs,
  478. const AbstractBasePtr &false_graph_output_abs, const FuncGraphPtr &switch_graph,
  479. const AnfNodePtr &cond) {
  480. MS_EXCEPTION_IF_NULL(true_graph_output_abs);
  481. MS_EXCEPTION_IF_NULL(false_graph_output_abs);
  482. MS_EXCEPTION_IF_NULL(cond);
  483. MS_EXCEPTION_IF_NULL(switch_graph);
  484. auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
  485. MS_EXCEPTION_IF_NULL(PrimMerge);
  486. if (!true_graph_output_abs->isa<abstract::AbstractTuple>()) {
  487. std::vector<AnfNodePtr> merge_nodes;
  488. merge_nodes.push_back(NewValueNode(PrimMerge));
  489. std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), true_output_node, false_output_node};
  490. merge_nodes.push_back(switch_graph->NewCNode(make_tuple_nodes));
  491. std::vector<AnfNodePtr> tuple_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem),
  492. switch_graph->NewCNode(merge_nodes),
  493. NewValueNode(MakeValue(static_cast<int64_t>(0)))};
  494. return switch_graph->NewCNode(tuple_getitem_nodes);
  495. } else {
  496. abstract::AbstractTuplePtr true_branch_tuple = true_graph_output_abs->cast<abstract::AbstractTuplePtr>();
  497. abstract::AbstractTuplePtr false_branch_tuple = false_graph_output_abs->cast<abstract::AbstractTuplePtr>();
  498. std::vector<AnfNodePtr> make_tuple_nodes;
  499. make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
  500. for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
  501. std::vector<AnfNodePtr> true_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), true_output_node,
  502. NewValueNode(MakeValue(SizeToLong(i)))};
  503. auto true_node = switch_graph->NewCNode(true_getitem_nodes);
  504. std::vector<AnfNodePtr> false_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), false_output_node,
  505. NewValueNode(MakeValue(SizeToLong(i)))};
  506. auto false_node = switch_graph->NewCNode(false_getitem_nodes);
  507. auto merge_node = GenerateMergeNodes(true_node, false_node, true_branch_tuple->elements()[i],
  508. false_branch_tuple->elements()[i], switch_graph, cond);
  509. make_tuple_nodes.push_back(merge_node);
  510. }
  511. return switch_graph->NewCNode(make_tuple_nodes);
  512. }
  513. }
  514. AnfNodePtr TransformMergeBranches(const AnfNodePtr &true_output_node, const AnfNodePtr &false_output_node,
  515. const AbstractBasePtr &true_graph_output_abs,
  516. const AbstractBasePtr &false_graph_output_abs, const AnfNodePtr &cond,
  517. const FuncGraphPtr &switch_graph) {
  518. if (!GraphOutputCompatible(true_graph_output_abs, false_graph_output_abs)) {
  519. MS_LOG(EXCEPTION) << "Switch output branch not compatible, true:" << true_graph_output_abs->ToString()
  520. << ", false:" << false_graph_output_abs->ToString();
  521. }
  522. return GenerateMergeNodes(true_output_node, false_output_node, true_graph_output_abs, false_graph_output_abs,
  523. switch_graph, cond);
  524. }
  525. } // namespace internal
  526. } // namespace irpass
  527. } // namespace opt
  528. } // namespace mindspore