• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2020-2021 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 
17 #include "frontend/optimizer/irpass/branch_culling.h"
18 
19 #include <memory>
20 #include <utility>
21 #include <queue>
22 
23 #include "mindspore/core/ops/structure_ops.h"
24 #include "mindspore/core/ops/sequence_ops.h"
25 #include "mindspore/core/ops/nn_optimizer_ops.h"
26 #include "mindspore/core/ops/nn_ops.h"
27 #include "mindspore/core/ops/math_ops.h"
28 #include "mindspore/core/ops/array_ops.h"
29 #include "mindspore/core/ops/framework_ops.h"
30 #include "ops/auto_generate/gen_ops_primitive.h"
31 #include "utils/hash_map.h"
32 #include "ir/func_graph.h"
33 #include "frontend/operator/ops.h"
34 #include "include/common/utils/convert_utils.h"
35 
36 namespace mindspore {
37 namespace opt {
38 namespace irpass {
39 constexpr size_t kCondIndex = 1;
40 constexpr size_t kTrueBranchIndex = 2;
41 constexpr size_t kFalseBranchIndex = 3;
42 namespace internal {
GenerateSwitchNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & data,int64_t switch_idx)43 AnfNodePtr GenerateSwitchNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data,
44                               int64_t switch_idx) {
45   auto switch_node = prim::GetPythonOps("geswitch", "mindspore.ops.functional")->cast<PrimitivePtr>();
46   std::vector<AnfNodePtr> switch_nodes{NewValueNode(switch_node), data, cond};
47   auto switch_apply = graph->NewCNode(switch_nodes);
48   std::vector<AnfNodePtr> tuple_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), switch_apply,
49                                               NewValueNode(MakeValue(switch_idx))};
50   return graph->NewCNode(tuple_getitem_nodes);
51 }
52 
GenerateSwitchTrueNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & data)53 AnfNodePtr GenerateSwitchTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
54   return GenerateSwitchNode(graph, cond, data, 1);
55 }
56 
GenerateSwitchFalseNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & data)57 AnfNodePtr GenerateSwitchFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
58   return GenerateSwitchNode(graph, cond, data, 0);
59 }
60 
InConvertWhiteList(const AnfNodePtr & node,size_t index)61 bool InConvertWhiteList(const AnfNodePtr &node, size_t index) {
62   // The CNode inputs of the following Primitive with index in std::vector<size_t> should not be guarded by geswitch
63   // node because it is attribute or ge specific reason.
64   // Example : when convert CNode(kPrimReduceSum, x, axis), node of index 2 in CNode->inputs is axis which should not be
65   // converted to switch guarded.
66 #ifndef ENABLE_SECURITY
67   std::vector<std::pair<PrimitivePtr, std::vector<size_t>>> white_list({{prim::kPrimApplyMomentum, {1, 2}},
68                                                                         {prim::kPrimMomentum, {2, 3}},
69                                                                         {prim::kPrimStateSetItem, {1}},
70                                                                         {prim::kPrimTupleGetItem, {2}},
71                                                                         {prim::kPrimEnvironGet, {1}},
72                                                                         {prim::kPrimEnvironSet, {1}},
73                                                                         {prim::kPrimReduceSum, {2}},
74                                                                         {prim::kPrimReduceMean, {2}},
75                                                                         {prim::kPrimReduceAll, {2}},
76                                                                         {prim::kPrimCast, {2}},
77                                                                         {prim::kPrimTranspose, {2}},
78                                                                         {prim::kPrimOneHot, {2}},
79                                                                         {prim::kPrimGather, {3}},
80                                                                         {prim::kPrimReshape, {2}},
81                                                                         {prim::kPrimAssign, {1}},
82                                                                         {prim::kPrimAssignAdd, {1}},
83                                                                         {prim::kPrimAssignSub, {1}},
84                                                                         {prim::kPrimTensorSummary, {1}},
85                                                                         {prim::kPrimImageSummary, {1}},
86                                                                         {prim::kPrimScalarSummary, {1}},
87                                                                         {prim::kPrimApplyRMSProp, {6, 7, 8}},
88                                                                         {prim::kPrimCumSum, {2}},
89                                                                         {prim::kPrimTile, {2}},
90                                                                         {prim::kPrimExpandDims, {2}},
91                                                                         {prim::kPrimHistogramSummary, {1}}});
92 #else
93   std::vector<std::pair<PrimitivePtr, std::vector<size_t>>> white_list(
94     {{prim::kPrimApplyMomentum, {1, 2}}, {prim::kPrimMomentum, {2, 3}},
95      {prim::kPrimStateSetItem, {1}},     {prim::kPrimTupleGetItem, {2}},
96      {prim::kPrimEnvironGet, {1}},       {prim::kPrimEnvironSet, {1}},
97      {prim::kPrimReduceSum, {2}},        {prim::kPrimReduceMean, {2}},
98      {prim::kPrimReduceAll, {2}},        {prim::kPrimCast, {2}},
99      {prim::kPrimTranspose, {2}},        {prim::kPrimOneHot, {2}},
100      {prim::kPrimGather, {3}},           {prim::kPrimReshape, {2}},
101      {prim::kPrimAssign, {1}},           {prim::kPrimAssignAdd, {1}},
102      {prim::kPrimAssignSub, {1}},        {prim::kPrimApplyRMSProp, {6, 7, 8}},
103      {prim::kPrimCumSum, {2}},           {prim::kPrimTile, {2}},
104      {prim::kPrimExpandDims, {2}}});
105 #endif
106   for (auto &item : white_list) {
107     auto matched = std::any_of(item.second.begin(), item.second.end(), [&item, &node, &index](size_t idx) {
108       return IsPrimitiveCNode(node, item.first) && idx == index;
109     });
110     if (matched) {
111       return true;
112     }
113   }
114 
115   std::vector<PrimitivePtr> adapter_convert_ops = {prim::kPrimDepend, prim::kPrimLoad};
116   for (auto &item : adapter_convert_ops) {
117     if (IsPrimitiveCNode(node, item)) {
118       return true;
119     }
120   }
121   return false;
122 }
123 
124 using NodeInputReplMap = mindspore::HashMap<std::pair<AnfNodePtr, size_t>, AnfNodePtr, PairHasher>;
125 // replace the nodes which should be changed
RunSwitchNodeReplace(const FuncGraphManagerPtr & manager,std::vector<std::pair<CNodePtr,CNodePtr>> nodes_changed,mindspore::HashMap<AnfNodePtr,AnfNodePtr> repl_node,NodeInputReplMap repl_node_inputs,const FuncGraphPtr & func_graph)126 void RunSwitchNodeReplace(const FuncGraphManagerPtr &manager, std::vector<std::pair<CNodePtr, CNodePtr>> nodes_changed,
127                           mindspore::HashMap<AnfNodePtr, AnfNodePtr> repl_node, NodeInputReplMap repl_node_inputs,
128                           const FuncGraphPtr &func_graph) {
129   for (auto &node_pair : nodes_changed) {
130     CNodePtr old_node = node_pair.first;
131     CNodePtr new_node = node_pair.second;
132     MS_EXCEPTION_IF_NULL(old_node);
133     MS_EXCEPTION_IF_NULL(new_node);
134     for (size_t i = 0; i < old_node->size(); i++) {
135       auto input = old_node->input(i);
136       if (repl_node.count(input) != 0) {
137         new_node->add_input(repl_node[input]);
138       } else if (repl_node_inputs.count(std::pair<AnfNodePtr, size_t>(old_node, i)) != 0) {
139         new_node->add_input(repl_node_inputs[std::pair<AnfNodePtr, size_t>(old_node, i)]);
140       } else {
141         new_node->add_input(input);
142       }
143     }
144   }
145 
146   for (auto &item : repl_node) {
147     if (IsPrimitiveCNode(item.second, prim::kPrimReturn)) {
148       func_graph->set_output(item.second->cast<CNodePtr>()->input(1));
149     } else if (!manager->Replace(item.first, item.second)) {
150       constexpr auto kDebugStrDepth = 2;
151       MS_LOG(INTERNAL_EXCEPTION) << "TransformGraphDependNode replace node failed original:"
152                                  << item.first->DebugString(kDebugStrDepth)
153                                  << " to new: " << item.second->DebugString(kDebugStrDepth);
154     }
155   }
156 }
157 
HasDependencyOnSubGraph(const FuncGraphPtr & graph,const AnfNodePtr & state)158 bool HasDependencyOnSubGraph(const FuncGraphPtr &graph, const AnfNodePtr &state) {
159   std::queue<AnfNodePtr> nodes;
160   nodes.push(state);
161   while (!nodes.empty()) {
162     auto cur_node = nodes.front();
163     MS_EXCEPTION_IF_NULL(cur_node);
164     nodes.pop();
165     if (cur_node->isa<Parameter>() || cur_node->isa<ValueNode>()) {
166       continue;
167     }
168     if (cur_node->func_graph() == graph) {
169       return true;
170     }
171     auto cur_cnode = cur_node->cast<CNodePtr>();
172     MS_EXCEPTION_IF_NULL(cur_cnode);
173     for (size_t i = 1; i < cur_cnode->size(); i++) {
174       nodes.push(cur_cnode->input(i));
175     }
176   }
177   return false;
178 }
179 
180 // trace the node that should add switch and replace them with new nodes in the graph
TransformGraphCondBranchNodes(const FuncGraphPtr & graph,const AnfNodePtr & cond,const std::function<AnfNodePtr (FuncGraphPtr graph,AnfNodePtr cond,AnfNodePtr data)> & generate_func)181 FuncGraphPtr TransformGraphCondBranchNodes(
182   const FuncGraphPtr &graph, const AnfNodePtr &cond,
183   const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func) {
184   auto manager = graph->manager();
185   MS_EXCEPTION_IF_NULL(manager);
186 
187   // record the node that has been changed
188   std::vector<std::pair<CNodePtr, CNodePtr>> nodes_changed;
189   // record the node to be replaced
190   mindspore::HashMap<AnfNodePtr, AnfNodePtr> repl_node;
191   // record the node input to be replaced
192   NodeInputReplMap repl_node_inputs;
193   const AnfNodeSet &nodes = graph->nodes();
194   for (auto &node : nodes) {
195     MS_EXCEPTION_IF_NULL(node);
196     if (!node->isa<CNode>()) {
197       continue;
198     }
199     auto inputs = node->cast<CNodePtr>()->inputs();
200     bool should_replace = false;
201     // if the apply input does not belong to graph, insert a switch node
202     for (size_t index = 0; index < inputs.size(); index++) {
203       auto input_node = inputs[index];
204       MS_EXCEPTION_IF_NULL(input_node);
205       if (HasAbstractMonad(input_node)) {
206         // Do not guard with switch for monad inputs.
207         continue;
208       }
209       // for some ops input should not guard it with switch
210       if (InConvertWhiteList(node, index)) {
211         continue;
212       }
213 
214       // If the input for node is not the graph belonged, or it is an ValueNode.
215       // Bypass the Primitive node which is inputs[0].
216       if ((index >= 1 && input_node->func_graph() != nullptr && input_node->func_graph() != graph) ||
217           ((index >= 1 && input_node->isa<ValueNode>()))) {
218         input_node = generate_func(graph, cond, input_node);
219         repl_node_inputs[std::pair<AnfNodePtr, size_t>(node, index)] = input_node;
220         should_replace = true;
221       }
222       // Insert GeSwitch after load
223       if (IsPrimitiveCNode(input_node, prim::kPrimLoad)) {
224         auto cnode_load = input_node->cast<CNodePtr>();
225         MS_EXCEPTION_IF_NULL(cnode_load);
226         auto load_real_input = cnode_load->inputs()[kLoadRealInput];
227         MS_EXCEPTION_IF_NULL(load_real_input);
228         auto load_state_input = cnode_load->inputs()[kLoadStateInput];
229         MS_EXCEPTION_IF_NULL(load_state_input);
230         if ((load_real_input->func_graph() != nullptr && load_real_input->func_graph() != graph) &&
231             !HasDependencyOnSubGraph(graph, load_state_input)) {
232           input_node = generate_func(graph, cond, input_node);
233           repl_node_inputs[std::pair<AnfNodePtr, size_t>(node, index)] = input_node;
234           should_replace = true;
235         }
236       }
237 
238       if (input_node == nullptr) {
239         MS_LOG(INTERNAL_EXCEPTION) << "generate switch node failed";
240       }
241     }
242     if (should_replace) {
243       auto new_node = graph->NewCNode({});
244       repl_node[node] = new_node;
245       (void)nodes_changed.emplace_back(node->cast<CNodePtr>(), new_node);
246     }
247   }
248   RunSwitchNodeReplace(manager, nodes_changed, repl_node, repl_node_inputs, graph);
249   return graph;
250 }
251 
252 struct SharedOp {
253   tensor::TensorPtr const_data;
254   CNodePtr square_ops[2];
255   CNodePtr merge_ops[2];
256 } MergeNetOutput;
257 
GetConstData()258 inline tensor::TensorPtr GetConstData() { return MergeNetOutput.const_data; }
SetConstData(const tensor::TensorPtr & const_value)259 inline void SetConstData(const tensor::TensorPtr &const_value) { MergeNetOutput.const_data = const_value; }
260 
GetSquareOp(int64_t switch_idx)261 inline CNodePtr GetSquareOp(int64_t switch_idx) { return MergeNetOutput.square_ops[switch_idx]; }
SetSquareOp(int64_t switch_idx,const CNodePtr & op)262 inline void SetSquareOp(int64_t switch_idx, const CNodePtr &op) { MergeNetOutput.square_ops[switch_idx] = op; }
263 
GetMergeOp(int64_t switch_idx)264 inline CNodePtr GetMergeOp(int64_t switch_idx) { return MergeNetOutput.merge_ops[switch_idx]; }
SetMergeOp(int64_t switch_idx,const CNodePtr & op)265 inline void SetMergeOp(int64_t switch_idx, const CNodePtr &op) { MergeNetOutput.merge_ops[switch_idx] = op; }
266 
ResetSharedOp()267 inline void ResetSharedOp() {
268   SetConstData(nullptr);
269   SetSquareOp(0, nullptr);
270   SetSquareOp(1, nullptr);
271   SetMergeOp(0, nullptr);
272   SetMergeOp(1, nullptr);
273 }
274 
ConstData()275 tensor::TensorPtr ConstData() {
276   std::vector<int64_t> shp = {1};
277   tensor::TensorPtr const_data = std::make_shared<tensor::Tensor>(kInt64->type_id(), shp);
278   auto *val = static_cast<int64_t *>(const_data->data_c());
279   *val = 0;
280   return const_data;
281 }
282 
SquareOp(const FuncGraphPtr & graph,const AnfNodePtr & cond,int64_t switch_idx,const tensor::TensorPtr & const_data)283 CNodePtr SquareOp(const FuncGraphPtr &graph, const AnfNodePtr &cond, int64_t switch_idx,
284                   const tensor::TensorPtr &const_data) {
285   auto prim_square = prim::kPrimSquare;
286   // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
287   // the other use the opposite
288   auto ctrl_data = NewValueNode(const_data);
289   auto ctrl_node = GenerateSwitchNode(graph, cond, ctrl_data, switch_idx);
290 
291   std::vector<AnfNodePtr> square_nodes{NewValueNode(prim_square), ctrl_node};
292   auto square_op = graph->NewCNode(square_nodes);
293 
294   return square_op;
295 }
296 
MergeNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,int64_t switch_idx,const tensor::TensorPtr & const_data,const CNodePtr & square_op)297 CNodePtr MergeNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, int64_t switch_idx,
298                    const tensor::TensorPtr &const_data, const CNodePtr &square_op) {
299   // for the depended node , add two const data to merge the flow ,one for depended node with same switch,
300   // the other use the opposite
301   auto oppsite_ctrl_data = NewValueNode(const_data);
302   auto opposite_ctrl_node = GenerateSwitchNode(graph, cond, oppsite_ctrl_data, 1 - switch_idx);
303 
304   std::vector<AnfNodePtr> merge_nodes;
305   auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
306   merge_nodes.push_back(NewValueNode(PrimMerge));
307   std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), square_op, opposite_ctrl_node};
308   merge_nodes.push_back(graph->NewCNode(make_tuple_nodes));
309   auto merge_op = graph->NewCNode(merge_nodes);
310 
311   return merge_op;
312 }
313 
314 // merge(square_op(switch(ctrl_data)), switch(opposite_ctrl_data))
GenerateSwitchDependNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & output_node,int64_t switch_idx)315 AnfNodePtr GenerateSwitchDependNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &output_node,
316                                     int64_t switch_idx) {
317   tensor::TensorPtr const_data = GetConstData();
318   if (const_data == nullptr) {
319     const_data = ConstData();
320     SetConstData(const_data);
321   }
322 
323   CNodePtr square_op = GetSquareOp(switch_idx);
324   if (square_op == nullptr) {
325     square_op = SquareOp(graph, cond, switch_idx, const_data);
326     SetSquareOp(switch_idx, square_op);
327   }
328 
329   auto manager = graph->manager();
330   MS_EXCEPTION_IF_NULL(manager);
331   AnfNodePtrList inputs = {NewValueNode(prim::kPrimDepend), square_op, output_node};
332   auto depend_cnode = graph->NewCNode(inputs);
333   if (!manager->Replace(square_op, depend_cnode)) {
334     MS_LOG(EXCEPTION) << square_op->DebugString() << ", replace node failed.";
335   }
336 
337   CNodePtr merge_op = GetMergeOp(switch_idx);
338   if (merge_op == nullptr) {
339     merge_op = MergeNode(graph, cond, switch_idx, const_data, square_op);
340     SetMergeOp(switch_idx, merge_op);
341   }
342 
343   return merge_op;
344 }
345 
346 // generate switch nodes for true graph node inputs
GenerateSwitchDependTrueNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & data)347 AnfNodePtr GenerateSwitchDependTrueNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
348   // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
349   return GenerateSwitchDependNode(graph, cond, data, 1);
350 }
351 
352 // generate switch nodes for false graph node inputs
GenerateSwitchDependFalseNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const AnfNodePtr & data)353 AnfNodePtr GenerateSwitchDependFalseNode(const FuncGraphPtr &graph, const AnfNodePtr &cond, const AnfNodePtr &data) {
354   // for switch op ,the output is a tuple ,0-th is false_branch, 1-th is true branch
355   return GenerateSwitchDependNode(graph, cond, data, 0);
356 }
357 
358 // to judge if the node used in Depend is a net output node
IsNetOutputNode(const FuncGraphManagerPtr & manager,const AnfNodePtr & node)359 bool IsNetOutputNode(const FuncGraphManagerPtr &manager, const AnfNodePtr &node) {
360   auto uses = manager->node_users()[node];
361   bool is_output_node = true;
362   for (auto &item : uses) {
363     if (IsPrimitiveCNode(item.first, prim::kPrimDepend)) {
364       continue;
365     }
366     is_output_node = false;
367     break;
368   }
369   return is_output_node;
370 }
371 
372 // generate node for Depended MakeTuple
GenerateReplNodeForDependMakeTuple(const AnfNodePtr & depended_node,const FuncGraphPtr & graph,const AnfNodePtr & cond,const std::shared_ptr<mindspore::HashMap<AnfNodePtr,AnfNodePtr>> & repl_node,const std::function<AnfNodePtr (FuncGraphPtr graph,AnfNodePtr cond,AnfNodePtr data)> & generate_func)373 void GenerateReplNodeForDependMakeTuple(
374   const AnfNodePtr &depended_node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
375   const std::shared_ptr<mindspore::HashMap<AnfNodePtr, AnfNodePtr>> &repl_node,
376   const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func) {
377   MS_EXCEPTION_IF_NULL(graph->manager());
378 
379   auto make_tuple_inputs = depended_node->cast<CNodePtr>()->inputs();
380   const size_t make_tuple_begin_idx = 1;
381   std::vector<AnfNodePtr> new_make_tuple_nodes;
382   bool replace_make_tuple = false;
383   new_make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
384   for (size_t idx = make_tuple_begin_idx; idx < make_tuple_inputs.size(); idx++) {
385     auto depended_tuple_input_node = make_tuple_inputs[idx];
386     if (IsPrimitiveCNode(depended_tuple_input_node->cast<CNodePtr>(), prim::kPrimDepend)) {
387       new_make_tuple_nodes.push_back(depended_tuple_input_node);
388       continue;
389     }
390 
391     if (graph->manager()->node_users()[depended_tuple_input_node].size() == 1) {
392       auto gen_node = generate_func(graph, cond, depended_tuple_input_node);
393       new_make_tuple_nodes.push_back(gen_node);
394       replace_make_tuple = true;
395       continue;
396     }
397 
398     MS_LOG(WARNING) << "depended node being used by others, ";
399   }
400   if (replace_make_tuple) {
401     auto make_tuple_op = graph->NewCNode(new_make_tuple_nodes);
402     (*repl_node)[depended_node] = make_tuple_op;
403   }
404 }
405 
406 // generate a replace depend node for a single network output node
GenerateRepDepend(const CNodePtr & node,const FuncGraphPtr & graph,const AnfNodePtr & cond,const std::shared_ptr<mindspore::HashMap<AnfNodePtr,AnfNodePtr>> & repl_node,const std::function<AnfNodePtr (FuncGraphPtr graph,AnfNodePtr cond,AnfNodePtr data)> & generate_func)407 void GenerateRepDepend(
408   const CNodePtr &node, const FuncGraphPtr &graph, const AnfNodePtr &cond,
409   const std::shared_ptr<mindspore::HashMap<AnfNodePtr, AnfNodePtr>> &repl_node,
410   const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &generate_func) {
411   MS_EXCEPTION_IF_NULL(graph->manager());
412 
413   auto inputs = node->inputs();
414   if (inputs.size() != kDependInputSize) {
415     MS_LOG(EXCEPTION) << "For 'Depend', the inputs should be [depend_prim, actual_value, depended_node].";
416   }
417 
418   std::vector<AnfNodePtr> new_depened_inputs;
419   // Inputs should be [depend, actual_value, depended_node]
420   auto depended_node = inputs[kDependAttachNodeIndex];
421   new_depened_inputs.push_back(inputs[0]);
422   new_depened_inputs.push_back(inputs[1]);
423   // depended node should be make_tuple or a single depended node
424   if (IsPrimitiveCNode(depended_node, prim::kPrimMakeTuple)) {
425     GenerateReplNodeForDependMakeTuple(depended_node, graph, cond, repl_node, generate_func);
426   } else {
427     // Check if there is only single user for depend_node.
428     if (graph->manager()->node_users()[depended_node].size() == 1) {
429       auto gen_node = generate_func(graph, cond, depended_node);
430       (*repl_node)[depended_node] = gen_node;
431     } else {
432       MS_LOG(WARNING) << "depended node being used by others";
433     }
434   }
435 }
436 
437 // generate depend node for netoutput node, to resolve the stream synchronize problem of ge
438 // traverse all nodes of depend node, find the graph output node , generaete a merge node of (square, const)
TransformGraphDependNode(const FuncGraphPtr & graph,const AnfNodePtr & cond,const std::function<AnfNodePtr (FuncGraphPtr graph,AnfNodePtr cond,AnfNodePtr data)> & gen_depend_func)439 FuncGraphPtr TransformGraphDependNode(
440   const FuncGraphPtr &graph, const AnfNodePtr &cond,
441   const std::function<AnfNodePtr(FuncGraphPtr graph, AnfNodePtr cond, AnfNodePtr data)> &gen_depend_func) {
442   auto manager = graph->manager();
443   MS_EXCEPTION_IF_NULL(manager);
444 
445   ResetSharedOp();
446   std::shared_ptr<mindspore::HashMap<AnfNodePtr, AnfNodePtr>> repl_node =
447     std::make_shared<mindspore::HashMap<AnfNodePtr, AnfNodePtr>>();  // record the node to be replaced
448   const AnfNodeSet &nodes = graph->nodes();
449   for (auto &node : nodes) {
450     MS_EXCEPTION_IF_NULL(node);
451     if (!node->isa<CNode>()) {
452       continue;
453     }
454     if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
455       auto cnode = node->cast<CNodePtr>();
456       if (cnode->size() != kDependInputSize) {
457         MS_LOG(EXCEPTION) << "For primitive 'Depend', the input size must be " << kDependInputSize << ", but got "
458                           << cnode->size();
459       }
460       auto depended_node = cnode->input(kDependAttachNodeIndex);
461       MS_EXCEPTION_IF_NULL(depended_node);
462       if (!depended_node->isa<CNode>()) {
463         continue;
464       }
465       if (IsPrimitiveCNode(depended_node, prim::kPrimDepend)) {
466         continue;
467       }
468       GenerateRepDepend(cnode, graph, cond, repl_node, gen_depend_func);
469     }
470   }
471   ResetSharedOp();
472 
473   for (auto &item : *repl_node) {
474     if (!manager->Replace(item.first, item.second)) {
475       MS_LOG(INTERNAL_EXCEPTION) << "TransformGraphDependNode replace node failed";
476     }
477   }
478 
479   return graph;
480 }
481 
TransformGraphCondTrueBranchNodes(const FuncGraphPtr & graph,const AnfNodePtr & cond)482 FuncGraphPtr TransformGraphCondTrueBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
483   (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchTrueNode);
484   return TransformGraphDependNode(graph, cond, GenerateSwitchDependTrueNode);
485 }
486 
TransformGraphCondFalseBranchNodes(const FuncGraphPtr & graph,const AnfNodePtr & cond)487 FuncGraphPtr TransformGraphCondFalseBranchNodes(const FuncGraphPtr &graph, const AnfNodePtr &cond) {
488   (void)TransformGraphCondBranchNodes(graph, cond, GenerateSwitchFalseNode);
489   return TransformGraphDependNode(graph, cond, GenerateSwitchDependFalseNode);
490 }
491 
492 // Judge if the true and false graph output is compatible(they shall have same tuple size)
GraphOutputCompatible(const AbstractBasePtr & true_branch_abs,const AbstractBasePtr & false_branch_abs)493 bool GraphOutputCompatible(const AbstractBasePtr &true_branch_abs, const AbstractBasePtr &false_branch_abs) {
494   MS_EXCEPTION_IF_NULL(true_branch_abs);
495   MS_EXCEPTION_IF_NULL(false_branch_abs);
496 
497   if (true_branch_abs->isa<abstract::AbstractTuple>() && false_branch_abs->isa<abstract::AbstractTuple>()) {
498     abstract::AbstractTuplePtr true_branch_tuple = true_branch_abs->cast<abstract::AbstractTuplePtr>();
499     abstract::AbstractTuplePtr false_branch_tuple = false_branch_abs->cast<abstract::AbstractTuplePtr>();
500     if (true_branch_tuple->elements().size() != false_branch_tuple->elements().size()) {
501       MS_LOG(ERROR) << "true branch size:" << true_branch_tuple->elements().size()
502                     << ", not equal to false branch size:" << false_branch_tuple->elements().size() << " ";
503       return false;
504     }
505     bool all_compatible = true;
506     for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
507       all_compatible =
508         all_compatible && GraphOutputCompatible(true_branch_tuple->elements()[i], false_branch_tuple->elements()[i]);
509     }
510     return all_compatible;
511   }
512   TypePtr true_branch_type = true_branch_abs->BuildType();
513   TypePtr false_branch_type = false_branch_abs->BuildType();
514   MS_LOG(DEBUG) << "branch output Type equal?" << (*true_branch_type == *false_branch_type)
515                 << " true:" << true_branch_type->ToString() << " false:" << false_branch_type->ToString();
516   return (*true_branch_type == *false_branch_type);
517 }
518 
519 // block_nodes[0]: condition node
520 // block_nodes[1]: true branch node
521 // block_nodes[2]: false branch node
522 // branch_output_abs[0]: true branch abstract
523 // branch_output_abs[1]: false branch abstract
GenerateMergeNodes(const std::vector<AnfNodePtr> & block_nodes,const std::vector<AbstractBasePtr> & branch_output_abs,const FuncGraphPtr & switch_graph)524 AnfNodePtr GenerateMergeNodes(const std::vector<AnfNodePtr> &block_nodes,
525                               const std::vector<AbstractBasePtr> &branch_output_abs, const FuncGraphPtr &switch_graph) {
526   MS_EXCEPTION_IF_NULL(branch_output_abs[0]);
527   MS_EXCEPTION_IF_NULL(branch_output_abs[1]);
528   MS_EXCEPTION_IF_NULL(block_nodes[0]);
529   MS_EXCEPTION_IF_NULL(switch_graph);
530   auto PrimMerge = prim::GetPythonOps("merge", "mindspore.ops.functional")->cast<PrimitivePtr>();
531   MS_EXCEPTION_IF_NULL(PrimMerge);
532 
533   if (!branch_output_abs[0]->isa<abstract::AbstractTuple>()) {
534     std::vector<AnfNodePtr> merge_nodes;
535     merge_nodes.push_back(NewValueNode(PrimMerge));
536     std::vector<AnfNodePtr> make_tuple_nodes{NewValueNode(prim::kPrimMakeTuple), block_nodes[1], block_nodes[2]};
537     merge_nodes.push_back(switch_graph->NewCNode(make_tuple_nodes));
538     std::vector<AnfNodePtr> tuple_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem),
539                                                 switch_graph->NewCNode(merge_nodes),
540                                                 NewValueNode(MakeValue(static_cast<int64_t>(0)))};
541     return switch_graph->NewCNode(tuple_getitem_nodes);
542   } else {
543     auto true_branch_tuple = branch_output_abs[0]->cast<abstract::AbstractTuplePtr>();
544     auto false_branch_tuple = branch_output_abs[1]->cast<abstract::AbstractTuplePtr>();
545 
546     std::vector<AnfNodePtr> make_tuple_nodes;
547     make_tuple_nodes.push_back(NewValueNode(prim::kPrimMakeTuple));
548     for (size_t i = 0; i < true_branch_tuple->elements().size(); i++) {
549       std::vector<AnfNodePtr> true_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), block_nodes[1],
550                                                  NewValueNode(MakeValue(SizeToLong(i)))};
551       auto true_node = switch_graph->NewCNode(true_getitem_nodes);
552       std::vector<AnfNodePtr> false_getitem_nodes{NewValueNode(prim::kPrimTupleGetItem), block_nodes[2],
553                                                   NewValueNode(MakeValue(SizeToLong(i)))};
554       auto false_node = switch_graph->NewCNode(false_getitem_nodes);
555 
556       auto merge_node = GenerateMergeNodes(
557         {
558           block_nodes[0],
559           true_node,
560           false_node,
561         },
562         {true_branch_tuple->elements()[i], false_branch_tuple->elements()[i]}, switch_graph);
563       make_tuple_nodes.push_back(merge_node);
564     }
565     return switch_graph->NewCNode(make_tuple_nodes);
566   }
567 }
568 
TransformMergeBranches(const std::vector<AnfNodePtr> & block_nodes,const std::vector<AbstractBasePtr> & branch_output_abs,const FuncGraphPtr & func_graph)569 AnfNodePtr TransformMergeBranches(const std::vector<AnfNodePtr> &block_nodes,
570                                   const std::vector<AbstractBasePtr> &branch_output_abs,
571                                   const FuncGraphPtr &func_graph) {
572   if (!GraphOutputCompatible(branch_output_abs[0], branch_output_abs[1])) {
573     MS_LOG(EXCEPTION) << "Switch output branch not compatible, true:" << branch_output_abs[0]->ToString()
574                       << ", false:" << branch_output_abs[1]->ToString();
575   }
576   return GenerateMergeNodes(block_nodes, branch_output_abs, func_graph);
577 }
578 }  // namespace internal
579 
CheckSwitchBranch(const AnfNodePtr & node) const580 bool ConvertSwitchReplacement::CheckSwitchBranch(const AnfNodePtr &node) const {
581   if (!IsValueNode<FuncGraph>(node)) {
582     return false;
583   }
584   // If graph contains FuncGraph, then ignore this node.
585   auto graph = GetValueNode<FuncGraphPtr>(node);
586   for (auto &item : graph->value_nodes()) {
587     auto value_node = item.first;
588     if (IsValueNode<FuncGraph>(value_node)) {
589       return false;
590     }
591   }
592   return true;
593 }
594 
CheckSwitchWrapNode(const AnfNodePtr & node) const595 bool ConvertSwitchReplacement::CheckSwitchWrapNode(const AnfNodePtr &node) const {
596   // {{prim::kPrimSwitch, X, G1, G2}, Xs}.
597   if (node->isa<CNode>()) {
598     auto inp0 = node->cast<CNodePtr>()->input(0);
599     if (IsPrimitiveCNode(inp0, prim::kPrimSwitch)) {
600       auto switch_node = inp0->cast<CNodePtr>();
601       // for switch replace method, only graphs without graph inside can be replaced
602       if (CheckSwitchBranch(switch_node->input(kTrueBranchIndex)) &&
603           CheckSwitchBranch(switch_node->input(kFalseBranchIndex))) {
604         return true;
605       }
606     }
607   }
608   return false;
609 }
610 
TransformSwitchBranchReplace(const AnfNodePtr & node) const611 void ConvertSwitchReplacement::TransformSwitchBranchReplace(const AnfNodePtr &node) const {
612   auto cnode = node->cast<CNodePtr>();
613   MS_EXCEPTION_IF_NULL(cnode);
614   constexpr size_t input_index = 0;
615   auto switch_cnode = cnode->input(input_index)->cast<CNodePtr>();
616   MS_EXCEPTION_IF_NULL(switch_cnode);
617   auto cond = switch_cnode->input(kCondIndex);
618   auto true_br = switch_cnode->input(kTrueBranchIndex);
619   auto false_br = switch_cnode->input(kFalseBranchIndex);
620 
621   auto g1 = GetValueNode<FuncGraphPtr>(true_br);
622   auto g2 = GetValueNode<FuncGraphPtr>(false_br);
623   auto true_output = g1->output()->abstract();
624   auto false_output = g2->output()->abstract();
625   auto trans_g1 = internal::TransformGraphCondTrueBranchNodes(g1, cond);
626   auto trans_g2 = internal::TransformGraphCondFalseBranchNodes(g2, cond);
627 
628   std::vector<AnfNodePtr> params;
629   if (cnode->size() > 1) {
630     // There are arguments for the call of switch result,
631     // usually these are monad states added by auto-monad.
632     for (size_t i = 1; i < cnode->size(); ++i) {
633       params.push_back(cnode->inputs().at(i));
634     }
635   }
636   auto fg = node->func_graph();
637   auto cloned_g1 = InlineClone(trans_g1, fg, params);
638   auto cloned_g2 = InlineClone(trans_g2, fg, params);
639   auto new_node = internal::TransformMergeBranches({cond, cloned_g1, cloned_g2}, {true_output, false_output}, fg);
640   (void)fg->manager()->Replace(node, new_node);
641 }
642 }  // namespace irpass
643 }  // namespace opt
644 }  // namespace mindspore
645