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