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 UsesFunctionLibrary()47 bool UsesFunctionLibrary() const override { return false; } 48 49 Status Optimize(Cluster* cluster, const GrapplerItem& item, 50 GraphDef* optimized_graph) override; 51 52 void Feedback(Cluster* cluster, const GrapplerItem& item, 53 const GraphDef& optimized_graph, double result) override; 54 55 private: 56 friend class ArithmeticOptimizerTest; 57 58 // Granular control for arithmetic optimizer stages 59 struct ArithmeticOptimizerOptions { 60 bool combine_add_to_addn = true; 61 bool convert_sqrt_div_to_rsqrt_mul = true; 62 bool dedup_computations = true; 63 bool fold_conjugate_into_transpose = true; 64 bool fold_multiply_into_conv = true; 65 bool fold_transpose_into_matmul = true; 66 bool fuse_squared_diff = true; 67 bool hoist_common_factor_out_of_aggregation = true; 68 bool hoist_cwise_unary_chains = true; 69 bool minimize_broadcasts = true; 70 bool optimize_max_or_min_of_monotonic = true; 71 bool remove_idempotent = true; 72 bool remove_identity_transpose = true; 73 bool remove_involution = true; 74 bool remove_logical_not = true; 75 bool remove_negation = true; 76 bool remove_redundant_bitcast = true; 77 bool remove_redundant_cast = true; 78 bool remove_redundant_reshape = true; 79 bool reorder_cast_like_and_value_preserving = true; 80 bool replace_mul_with_square = true; 81 bool simplify_aggregation = true; 82 bool convert_pow = true; 83 bool convert_log1p = true; 84 bool convert_log_softmax = true; 85 bool convert_expm1 = true; 86 bool unary_ops_composition = true; 87 bool remove_stack_slice_same_axis = true; 88 bool simplify_embedding_lookup = true; 89 bool remove_cast_into_segment_reduction = true; 90 91 // Choose which arithmetic optimizer stages will be enabled for a given 92 // optimization level by default. DefaultArithmeticOptimizerOptions93 static ArithmeticOptimizerOptions Default( 94 RewriterConfig::Toggle opt_level) { 95 ArithmeticOptimizerOptions options; 96 return options; 97 } 98 }; 99 100 // Returns true if it is safe to dedup node from the graph. 101 bool CanDedup(const NodeDef& node) const; 102 103 // Dedup redundant nodes in the graph. 104 void DedupComputations(); 105 106 // Forward the control dependencies anchored on src_nodes to the target_nodes. 107 void ForwardControlDependencies(NodeDef* target_node, 108 const std::vector<const NodeDef*>& src_nodes); 109 110 // Runs peep-hole optimizations on `optimized_graph`, e.g., removing inverse 111 // transposes. 112 Status SimplifyArithmeticOps(bool can_use_shapes); 113 // Tries to simplify the expression that roots at `node` and replaces the uses 114 // of `node` to the simplified expression. Returns the name of the simplified 115 // tensor (e.g. "split:1") or an empty string if no simplification is 116 // performed. 117 // 118 // `node_map` stores the mapping from node names to NodeDef*, and will be 119 // updated according to the rewrite. 120 // 121 // `new_nodes` will be populated with the new nodes this function creates and 122 // updates. The caller can push these nodes into the simplification queue to 123 // optimize them further. 124 // 125 // TODO(jingyue): This interface is not suitable for optimizing nodes with 126 // multiple output tensors. We should pass in a tensor name instead of a 127 // NodeDef. 128 string TrySimplifyAndReplaceUses(const NodeDef* node, 129 SetVector<NodeDef*>* nodes_to_simplify); 130 131 RewriterConfig::Toggle opt_level_; 132 ArithmeticOptimizerOptions options_; 133 134 bool fetch_nodes_known_ = false; 135 std::unordered_set<string> nodes_to_preserve_; 136 std::unique_ptr<NodeMap> node_map_; 137 std::unique_ptr<GraphProperties> graph_properties_; 138 GraphDef* optimized_graph_ = nullptr; // Not owned. 139 gtl::FlatSet<string> feed_nodes_; 140 }; 141 142 } // end namespace grappler 143 } // end namespace tensorflow 144 145 #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_H_ 146