1 /**
2 * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
3 *
4 * Copyright 2019-2021 Huawei Technologies Co., Ltd
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "frontend/optimizer/cse.h"
20
21 #include <vector>
22 #include <set>
23 #include <unordered_map>
24
25 #include "abstract/abstract_function.h"
26 #include "utils/flags.h"
27 #include "utils/utils.h"
28
29 namespace mindspore {
30 /* namespace to support opt */
31 namespace opt {
32 using mindspore::abstract::AbstractBase;
33 using mindspore::abstract::AbstractFunction;
34 using mindspore::abstract::AbstractFunctionPtr;
35
WithRecomputedScope(const AnfNodePtr & node)36 bool WithRecomputedScope(const AnfNodePtr &node) {
37 MS_EXCEPTION_IF_NULL(node);
38 if (!node->isa<CNode>()) {
39 return false;
40 }
41 auto full_name_with_scope = node->fullname_with_scope();
42 return full_name_with_scope.find(kAttrRecompute) == 0;
43 }
44
IsSetRecomputed(const CNodePtr & a,const CNodePtr & b)45 bool IsSetRecomputed(const CNodePtr &a, const CNodePtr &b) {
46 return (WithRecomputedScope(a) && !a->HasAttr(kAttrNeedCseAfterRecompute)) ||
47 (WithRecomputedScope(b) && !b->HasAttr(kAttrNeedCseAfterRecompute));
48 }
49
AbsOf(const AnfNodePtr & node,bool ignore_fg_abs_tracking_id)50 BasePtr AbsOf(const AnfNodePtr &node, bool ignore_fg_abs_tracking_id) {
51 MS_EXCEPTION_IF_NULL(node);
52 auto node_abs = node->abstract();
53 // In testcase: TestOptOpt.CSE, node->abstract() is null.
54 if (node_abs == nullptr) {
55 return kAnyValue;
56 }
57 if (node_abs->isa<abstract::PrimitiveAbstractClosure>()) {
58 // Ignore the tracking_id and prim pointer hash.
59 auto prim_abs = node_abs->cast<abstract::PrimitiveAbstractClosurePtr>();
60 return prim_abs->prim();
61 } else if (ignore_fg_abs_tracking_id && node_abs->isa<abstract::FuncGraphAbstractClosure>()) {
62 // Ignore the tracking_id.
63 auto new_fg_abs = node_abs->cast<abstract::AbstractFunctionPtr>()->Copy();
64 new_fg_abs->set_tracking_id(nullptr);
65 return new_fg_abs;
66 }
67 return node_abs;
68 }
69
BuildOrderGroupAndDoReplaceForOneGraph(const FuncGraphPtr & fg,const FuncGraphManagerPtr & manager) const70 bool CSE::BuildOrderGroupAndDoReplaceForOneGraph(const FuncGraphPtr &fg, const FuncGraphManagerPtr &manager) const {
71 MS_EXCEPTION_IF_NULL(fg);
72 std::vector<std::size_t> order_group;
73 std::unordered_map<std::size_t, std::vector<AnfNodePtr>> groups;
74 std::unordered_map<AnfNodePtr, std::size_t> hashes;
75
76 std::vector<AnfNodePtr> toposet = TopoSort(fg->get_return());
77 for (auto node : toposet) {
78 MS_EXCEPTION_IF_NULL(node);
79 if (hashes.find(node) != hashes.end()) {
80 continue;
81 }
82
83 std::size_t h = 0;
84 if (node->isa<ValueNode>()) {
85 ValueNodePtr value_node = node->cast<ValueNodePtr>();
86 auto value = value_node->value();
87 MS_EXCEPTION_IF_NULL(value);
88 h = hash_combine(value->hash(), (AbsOf(value_node, true)->hash()));
89 } else if (node->isa<CNode>()) {
90 auto cnode = node->cast<CNodePtr>();
91 auto &inputs = cnode->inputs();
92 size_t init = 0;
93 h = std::accumulate(inputs.begin(), inputs.end(), init, [&hashes](std::size_t hash, const AnfNodePtr &node_in) {
94 return hash_combine(hash, hashes[node_in]);
95 });
96 } else if (node->isa<Parameter>()) {
97 h = node->hash();
98 } else {
99 MS_LOG(ERROR) << "Unknown node type";
100 }
101
102 hashes[node] = h;
103 if (groups.find(h) == groups.end()) {
104 std::vector<AnfNodePtr> innervec({node});
105 groups[h] = innervec;
106 order_group.emplace_back(h);
107 } else {
108 groups[h].push_back(node);
109 }
110 }
111 return DoReplace(manager, order_group, &groups);
112 }
113
BuildOrderGroupAndDoReplace(const FuncGraphManagerPtr manager) const114 bool CSE::BuildOrderGroupAndDoReplace(const FuncGraphManagerPtr manager) const {
115 bool changed = false;
116 for (FuncGraphPtr fg : manager->func_graphs()) {
117 changed = BuildOrderGroupAndDoReplaceForOneGraph(fg, manager) || changed;
118 }
119 return changed;
120 }
121
122 // The op like print, summary, or the op do not has true output, and always as a depend node input.
HasSideEffect(const AnfNodePtr & node)123 static bool HasSideEffect(const AnfNodePtr &node) {
124 auto prim = GetCNodePrimitive(node);
125 if (prim == nullptr) {
126 return false;
127 }
128 auto side_effect_v = prim->GetAttr(GRAPH_FLAG_SIDE_EFFECT);
129 if (side_effect_v != nullptr && side_effect_v->isa<BoolImm>()) {
130 return GetValue<bool>(side_effect_v);
131 }
132 return false;
133 }
134
135 // If true do not merge the node.
CheckRandomEffect(const AnfNodePtr & main,const AnfNodePtr & node) const136 bool CSE::CheckRandomEffect(const AnfNodePtr &main, const AnfNodePtr &node) const {
137 auto prim_main = GetCNodePrimitive(main);
138 auto prim_node = GetCNodePrimitive(node);
139 // if has random effect, when generate by different op (not same object), do not merge.
140 if (prim_main != nullptr) {
141 auto effect_val = prim_main->GetAttr(GRAPH_FLAG_RANDOM_EFFECT);
142 if (effect_val != nullptr && effect_val->isa<BoolImm>()) {
143 bool has_random_effect = GetValue<bool>(effect_val);
144 if (has_random_effect) {
145 return true;
146 }
147 }
148 if (prim_main->name() != prim_node->name()) {
149 return true;
150 }
151 }
152 return false;
153 }
154
CheckReplace(const AnfNodePtr & main,const AnfNodePtr & node,bool check_side_effect) const155 bool CSE::CheckReplace(const AnfNodePtr &main, const AnfNodePtr &node, bool check_side_effect) const {
156 MS_EXCEPTION_IF_NULL(main);
157 MS_EXCEPTION_IF_NULL(node);
158
159 if (main->isa<ValueNode>() && node->isa<ValueNode>()) {
160 auto main_value = GetValueNode(main);
161 auto node_value = GetValueNode(node);
162 return (AbsOf(main, true) == AbsOf(node, true)) && (*main_value == *node_value);
163 } else if (main->isa<CNode>() && node->isa<CNode>()) {
164 auto c_main = main->cast<CNodePtr>();
165 auto c_node = node->cast<CNodePtr>();
166 // Not do cse for the node set recompute before the recompute pass.
167 if (IsSetRecomputed(c_main, c_node)) {
168 return false;
169 }
170 // When appsame is true, check if has side effect, do not merge.
171 if (check_side_effect && HasSideEffect(main)) {
172 return false;
173 }
174 const auto &inp1 = c_main->inputs();
175 const auto &inp2 = c_node->inputs();
176 if (inp1.size() != inp2.size()) {
177 return false;
178 }
179 for (size_t j = 0; j < inp1.size(); j++) {
180 auto inp1_j = inp1[j];
181 auto inp2_j = inp2[j];
182 MS_EXCEPTION_IF_NULL(inp1_j);
183 MS_EXCEPTION_IF_NULL(inp2_j);
184 if (!(*inp1_j == *inp2_j)) {
185 // Handle the case of two different Tensor, but with the same value
186 if (IsValueNode<tensor::Tensor>(inp1_j) && IsValueNode<tensor::Tensor>(inp2_j)) {
187 auto tensor1 = GetValueNode<tensor::TensorPtr>(inp1_j);
188 auto tensor2 = GetValueNode<tensor::TensorPtr>(inp2_j);
189 if (tensor1->ValueEqual(*tensor2)) {
190 continue;
191 }
192 } else if (HasSideEffect(inp1_j) && HasSideEffect(inp2_j)) {
193 // When the same side effect node as another two nodes' inputs, we still merge the node.
194 // Because the node only can be the inputs of `depend`, when the `depend` is duplicated merge the depend the
195 // node.
196 if (CheckReplace(inp1_j, inp2_j, false)) {
197 continue;
198 }
199 }
200 return false;
201 }
202 }
203 // When appsame is true, check if has random effect do not merge
204 if (CheckRandomEffect(c_main, c_node)) {
205 return false;
206 }
207 return true;
208 }
209 // a parameter node.
210 return false;
211 }
212
DoReplace(const FuncGraphManagerPtr manager,const std::vector<std::size_t> & order_group,std::unordered_map<std::size_t,std::vector<AnfNodePtr>> * groups) const213 bool CSE::DoReplace(const FuncGraphManagerPtr manager, const std::vector<std::size_t> &order_group,
214 std::unordered_map<std::size_t, std::vector<AnfNodePtr>> *groups) const {
215 bool changes = false;
216 std::set<size_t> clear_set;
217 for (auto &h : order_group) {
218 std::vector<AnfNodePtr> &group = (*groups)[h];
219 // If there are more than 2 node in that group, they may be same common expression can be eliminated.
220 if (group.size() > 1) {
221 for (size_t k = 0; k < group.size() - 1; k++) {
222 AnfNodePtr main = group[k];
223 MS_EXCEPTION_IF_NULL(main);
224
225 // When all node in group has been replaced
226 // or a valuenode node, skip compare in group
227 if ((k + 1 + clear_set.size() == group.size()) || (k > 0 && main->isa<ValueNode>())) {
228 break;
229 }
230
231 // skip node has been replaced
232 if (clear_set.find(k) != clear_set.end()) {
233 continue;
234 }
235
236 // Compare with rest elements in this group.
237 for (size_t i = k + 1; i < group.size(); i++) {
238 auto node = group[i];
239 MS_EXCEPTION_IF_NULL(node);
240
241 if (clear_set.find(i) != clear_set.end()) {
242 continue;
243 }
244 if (main->func_graph() != node->func_graph()) {
245 continue;
246 }
247 if (CheckReplace(node, main)) {
248 changes = true;
249 (void)manager->Replace(node, main);
250 (void)clear_set.insert(i);
251 }
252 }
253 }
254 clear_set.clear();
255 }
256 }
257
258 return changes;
259 }
260
Cse(const FuncGraphPtr root,const FuncGraphManagerPtr manager) const261 bool CSE::Cse(const FuncGraphPtr root, const FuncGraphManagerPtr manager) const {
262 MS_EXCEPTION_IF_NULL(manager);
263 manager->AddFuncGraph(root);
264 return BuildOrderGroupAndDoReplace(manager);
265 }
266 } // namespace opt
267 } // namespace mindspore
268