• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2017 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 #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_H_
17 #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_H_
18 
19 #include <unordered_set>
20 #include "tensorflow/core/grappler/costs/graph_properties.h"
21 #include "tensorflow/core/grappler/optimizers/graph_optimizer.h"
22 #include "tensorflow/core/grappler/utils.h"
23 #include "tensorflow/core/lib/gtl/flatset.h"
24 #include "tensorflow/core/protobuf/rewriter_config.pb.h"
25 
26 namespace tensorflow {
27 namespace grappler {
28 
29 constexpr char kArithmeticOptimizer[] = "ArithmeticOptimizer";
30 
31 // Optimize TF computations by reducing the arithmetic complexity required to
32 // run a model.
33 class ArithmeticOptimizer : public GraphOptimizer {
34  public:
ArithmeticOptimizer()35   ArithmeticOptimizer()
36       : opt_level_(RewriterConfig::ON),
37         options_(ArithmeticOptimizerOptions::Default(RewriterConfig::ON)) {}
38 
ArithmeticOptimizer(RewriterConfig::Toggle opt_level)39   explicit ArithmeticOptimizer(RewriterConfig::Toggle opt_level)
40       : opt_level_(opt_level),
41         options_(ArithmeticOptimizerOptions::Default(opt_level)) {}
42 
~ArithmeticOptimizer()43   ~ArithmeticOptimizer() override {}
44 
name()45   string name() const override { return "arithmetic_optimizer"; };
46 
47   Status Optimize(Cluster* cluster, const GrapplerItem& item,
48                   GraphDef* optimized_graph) override;
49 
50   void Feedback(Cluster* cluster, const GrapplerItem& item,
51                 const GraphDef& optimized_graph, double result) override;
52 
53  private:
54   friend class ArithmeticOptimizerTest;
55 
56   // Granular control for arithmetic optimizer stages
57   struct ArithmeticOptimizerOptions {
58     bool combine_add_to_addn = true;
59     bool convert_sqrt_div_to_rsqrt_mul = true;
60     bool dedup_computations = true;
61     bool fold_conjugate_into_transpose = true;
62     bool fold_multiply_into_conv = true;
63     bool fold_transpose_into_matmul = true;
64     bool fuse_squared_diff = true;
65     bool hoist_common_factor_out_of_aggregation = true;
66     bool hoist_cwise_unary_chains = true;
67     bool minimize_broadcasts = true;
68     bool optimize_max_or_min_of_monotonic = true;
69     bool remove_idempotent = true;
70     bool remove_identity_transpose = true;
71     bool remove_involution = true;
72     bool remove_logical_not = true;
73     bool remove_negation = true;
74     bool remove_redundant_bitcast = true;
75     bool remove_redundant_cast = true;
76     bool remove_redundant_reshape = true;
77     bool reorder_cast_like_and_value_preserving = true;
78     bool replace_mul_with_square = true;
79     bool simplify_aggregation = true;
80     bool convert_pow = true;
81     bool convert_log1p = true;
82     bool convert_log_softmax = true;
83     bool convert_expm1 = true;
84     bool unary_ops_composition = true;
85     bool remove_stack_strided_slice_same_axis = true;
86 
87     // Choose which arithmetic optimizer stages will be enabled for a given
88     // optimization level by default.
DefaultArithmeticOptimizerOptions89     static ArithmeticOptimizerOptions Default(
90         RewriterConfig::Toggle opt_level) {
91       ArithmeticOptimizerOptions options;
92       return options;
93     }
94   };
95 
96   // Returns true if it is safe to dedup node from the graph.
97   bool CanDedup(const NodeDef& node) const;
98 
99   // Dedup redundant nodes in the graph.
100   void DedupComputations();
101 
102   // Forward the control dependencies anchored on src_nodes to the target_nodes.
103   void ForwardControlDependencies(NodeDef* target_node,
104                                   const std::vector<const NodeDef*>& src_nodes);
105 
106   // Runs peep-hole optimizations on `optimized_graph`, e.g., removing inverse
107   // transposes.
108   Status SimplifyArithmeticOps(bool can_use_shapes);
109   // Tries to simplify the expression that roots at `node` and replaces the uses
110   // of `node` to the simplified expression. Returns the name of the simplified
111   // tensor (e.g. "split:1") or an empty string if no simplification is
112   // performed.
113   //
114   // `node_map` stores the mapping from node names to NodeDef*, and will be
115   // updated according to the rewrite.
116   //
117   // `new_nodes` will be populated with the new nodes this function creates and
118   // updates. The caller can push these nodes into the simplification queue to
119   // optimize them further.
120   //
121   // TODO(jingyue): This interface is not suitable for optimizing nodes with
122   // multiple output tensors. We should pass in a tensor name instead of a
123   // NodeDef.
124   string TrySimplifyAndReplaceUses(const NodeDef* node,
125                                    SetVector<NodeDef*>* nodes_to_simplify);
126 
127   RewriterConfig::Toggle opt_level_;
128   ArithmeticOptimizerOptions options_;
129 
130   bool fetch_nodes_known_ = false;
131   std::unordered_set<string> nodes_to_preserve_;
132   std::unique_ptr<NodeMap> node_map_;
133   std::unique_ptr<GraphProperties> graph_properties_;
134   GraphDef* optimized_graph_ = nullptr;  // Not owned.
135   gtl::FlatSet<string> feed_nodes_;
136 };
137 
138 }  // end namespace grappler
139 }  // end namespace tensorflow
140 
141 #endif  // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_H_
142