• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // This module implements a common subexpression elimination pass.  We
17 // process the nodes in the graph in reverse postorder
18 // (i.e. inputs before their downstream dependencies).  The rough algorithm is
19 // as follows:
20 //
21 // std::unordered_map<size_t, Node*> available
22 // for each node n in forward topological order:
23 //   h = NodeHash(n)
24 //   if available[h] exists and Equivalent(available(h), h)
25 //     redirect downstream uses of outputs of n to available[h]
26 //     remove n from graph
27 //   else
28 //     if available[h] does not exist
29 //       available[h] = n
30 //
31 // This is similar to the global value number algorithm describe in this
32 // paper:
33 //
34 // "Global code motion/global value numbering", Cliff Click, PLDI '95
35 // Proceedings of the ACM SIGPLAN 1995 conference on Programming
36 // language design and implementation, Pages 246-257
37 //      http://dl.acm.org/citation.cfm?id=207154
38 
39 #include "tensorflow/core/graph/optimizer_cse.h"
40 
41 #include <unordered_map>
42 #include <utility>
43 #include <vector>
44 
45 #include "tensorflow/core/framework/node_def.pb.h"
46 #include "tensorflow/core/framework/node_def_util.h"
47 #include "tensorflow/core/graph/algorithm.h"
48 #include "tensorflow/core/lib/gtl/map_util.h"
49 #include "tensorflow/core/lib/hash/hash.h"
50 #include "tensorflow/core/platform/logging.h"
51 
52 namespace tensorflow {
53 
54 class OptimizerCSE {
55  public:
OptimizerCSE(Graph * g)56   explicit OptimizerCSE(Graph* g) : g_(g) {}
57 
58   bool Optimize(const std::function<bool(const Node*)>& consider_fn);
59 
60  private:
61   static size_t NodeHash(const Node* n);
62   static bool Equivalent(const Node* a, const Node* b,
63                          AttrSlice::Scratch* scratch);
64 
65   Graph* g_;
66 };
67 
FillInputs(const Node * n,gtl::InlinedVector<const Node *,4> * control_edges,gtl::InlinedVector<std::pair<const Node *,int>,4> * in)68 static void FillInputs(const Node* n,
69                        gtl::InlinedVector<const Node*, 4>* control_edges,
70                        gtl::InlinedVector<std::pair<const Node*, int>, 4>* in) {
71   DCHECK_EQ(in->size(), n->num_inputs());
72   control_edges->clear();
73   for (const Edge* e : n->in_edges()) {
74     if (e->IsControlEdge()) {
75       control_edges->push_back(e->src());
76     } else {
77       (*in)[e->dst_input()] = std::make_pair(e->src(), e->src_output());
78     }
79   }
80   std::sort(control_edges->begin(), control_edges->end());
81   if (n->op_def().is_commutative()) {
82     // For commutative inputs, we sort the input by the input Node*
83     // to get a canonical ordering (so that add(a,b) and add(b, a) will
84     // hash to the same value if is_commutative is true for 'add').
85     std::sort(in->begin(), in->end());
86   }
87 }
88 
89 static size_t kIllegalNodeHash = 0;
90 
NodeHash(const Node * n)91 size_t OptimizerCSE::NodeHash(const Node* n) {
92   const DataTypeVector& out = n->output_types();
93   string str_to_hash = strings::StrCat(n->type_string(), out.size());
94   for (DataType dt : out) {
95     strings::StrAppend(&str_to_hash, dt);
96   }
97 
98   const int N_in = n->num_inputs();
99   strings::StrAppend(&str_to_hash, N_in);
100   gtl::InlinedVector<const Node*, 4> control_edges;
101   gtl::InlinedVector<std::pair<const Node*, int>, 4> in(N_in);
102   FillInputs(n, &control_edges, &in);
103   for (const auto& edge : in) {
104     strings::StrAppend(&str_to_hash, edge.first->id(), edge.second);
105   }
106 
107   size_t h = Hash64(str_to_hash);
108 
109 #if !defined(__ANDROID__)
110   // Hash the attrs.  For example, this makes sure different constants
111   // end up in different hash buckets.
112   string tmp;
113   for (const auto& attr : n->attrs()) {
114     tmp = attr.first;
115     attr.second.AppendToString(&tmp);
116     // Add hashes of attrs, so the order of attrs doesn't matter.
117     h += Hash32(tmp.data(), tmp.size(), 0x87341245);
118   }
119 #endif
120 
121   if (h == kIllegalNodeHash) h = kIllegalNodeHash + 1;
122   return h;
123 }
124 
HasRefInput(const Node * n)125 static bool HasRefInput(const Node* n) {
126   for (auto dt : n->input_types()) {
127     if (IsRefType(dt)) return true;
128   }
129   return false;
130 }
131 
Equivalent(const Node * a,const Node * b,AttrSlice::Scratch * scratch)132 bool OptimizerCSE::Equivalent(const Node* a, const Node* b,
133                               AttrSlice::Scratch* scratch) {
134   // Different op names are different
135   if (a->type_string() != b->type_string()) return false;
136 
137   // Never consider stateful nodes (such as non-const inputs) equivalent.
138   if (a->op_def().is_stateful()) return false;
139 
140   // For now, we consider any node that takes a ref input to not be
141   // equivalent to any other node.
142   if (HasRefInput(a) || HasRefInput(b)) return false;
143 
144   // Compare attrs.  Note that equal attrs implies equal input and
145   // output types.
146   if (!a->attrs().EqualAttrs(b->attrs(), scratch)) return false;
147 
148   // Compare input sources
149   if (a->num_inputs() != b->num_inputs()) return false;
150   const int N_in = a->num_inputs();
151   gtl::InlinedVector<const Node*, 4> a_control_edges;
152   gtl::InlinedVector<const Node*, 4> b_control_edges;
153   gtl::InlinedVector<std::pair<const Node*, int>, 4> a_in(N_in);
154   gtl::InlinedVector<std::pair<const Node*, int>, 4> b_in(N_in);
155   FillInputs(a, &a_control_edges, &a_in);
156   FillInputs(b, &b_control_edges, &b_in);
157   if (a_in != b_in) return false;
158   if (a_control_edges != b_control_edges) return false;
159 
160   return true;
161 }
162 
Optimize(const std::function<bool (const Node *)> & consider_fn)163 bool OptimizerCSE::Optimize(
164     const std::function<bool(const Node*)>& consider_fn) {
165   // This very simple implementation works if the whole graph is one
166   // giant basic block (because we just traverse nodes in a
167   // topological order). This simple implementation works well
168   // with control flow/loops/etc. But we need to be careful about
169   // control flow if we want to add more sophisticated CSE optimizations.
170 
171   // TODO(jeff): We need to handle Update nodes specially, but dealing
172   // with more general control flow will also solve this issue, and for
173   // now, our updates are almost always the most downstream nodes in
174   // the graph.
175   std::vector<Node*> order;
176   GetReversePostOrder(*g_, &order);
177 
178   // Our value is just a single Node*, meaning we keep just a single
179   // candidate for a given node hash value.  This may cause us to
180   // (rarely) lose some optimization opportunities if there are
181   // hash collisions, but it allows us to avoid having the value
182   // be a set<Node*> (or equivalent).
183   std::unordered_map<size_t, Node*> available;
184 
185   // Scratch space for Equivalent calls.  Allocated here and passed in to
186   // Equivalent to avoid allocation inside the loop below.
187   bool changed = false;
188   AttrSlice::Scratch scratch;
189   for (Node* n : order) {
190     if (!n->IsOp()) continue;
191 
192     // Don't prune placeholder nodes.
193     if (n->type_string() == "Placeholder" ||
194         n->type_string() == "PlaceholderV2" ||
195         n->type_string() == "PlaceholderWithDefault") {
196       continue;
197     }
198 
199     // See if we should consider this node at all
200     if (consider_fn != nullptr && !consider_fn(n)) continue;
201 
202     size_t h = NodeHash(n);
203     Node** candidate = &available[h];
204     if (*candidate == nullptr) {
205       // No existing match: insert "n" into the hash table under "h"
206       *candidate = n;
207     } else if (Equivalent(*candidate, n, &scratch)) {
208       VLOG(1) << "CSE: equivalent: " << (*candidate)->name() << " and "
209               << n->name();
210       // *candidate and n are equivalent.  Therefore, we can replace
211       // n with *candidate by fixing up outgoing edges from "n" to instead
212       // come from "*candidate", and then delete n from the graph
213       for (const Edge* e : n->out_edges()) {
214         g_->AddEdge(*candidate, e->src_output(), e->dst(), e->dst_input());
215       }
216 
217       MergeDebugInfo(NodeDebugInfo(*n), *candidate);
218       g_->RemoveNode(n);
219       changed = true;
220     }
221   }
222   return changed;
223 }
224 
OptimizeCSE(Graph * g,const std::function<bool (const Node *)> & consider_fn)225 bool OptimizeCSE(Graph* g,
226                  const std::function<bool(const Node*)>& consider_fn) {
227   OptimizerCSE opt(g);
228   return opt.Optimize(consider_fn);
229 }
230 
231 }  // namespace tensorflow
232