1 /* Copyright 2018 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_LOOP_OPTIMIZER_H_ 17 #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_LOOP_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/frame.h" 23 #include "tensorflow/core/protobuf/rewriter_config.pb.h" 24 25 namespace tensorflow { 26 namespace grappler { 27 28 constexpr char kLoopOptimizer[] = "LoopOptimizer"; 29 30 class LoopOptimizer : public GraphOptimizer { 31 public: 32 LoopOptimizer(); 33 34 explicit LoopOptimizer(RewriterConfig::Toggle opt_level, 35 DeviceBase* cpu_device); 36 ~LoopOptimizer()37 ~LoopOptimizer() override {} 38 name()39 string name() const override { return "loop_optimizer"; }; 40 41 Status Optimize(Cluster* cluster, const GrapplerItem& item, 42 GraphDef* optimized_graph) override; 43 44 void Feedback(Cluster* cluster, const GrapplerItem& item, 45 const GraphDef& optimized_graph, double result) override; 46 47 private: 48 friend class LoopOptimizerTest; 49 50 // Granular control for loop optimizer stages. 51 struct LoopOptimizerOptions { 52 bool enable_loop_invariant_node_motion = false; 53 bool enable_stack_push_removal = true; 54 bool enable_dead_branch_removal = true; 55 DefaultLoopOptimizerOptions56 static LoopOptimizerOptions Default(RewriterConfig::Toggle opt_level) { 57 LoopOptimizerOptions options; 58 return options; 59 } 60 }; 61 62 Status RemoveDeadBranches(const std::unordered_set<string>& nodes_to_preserve, 63 const NodeMap& node_map, 64 const absl::flat_hash_set<string>& feed_nodes, 65 GraphDef* optimized_graph); 66 67 RewriterConfig::Toggle opt_level_; 68 DeviceBase* cpu_device_; 69 LoopOptimizerOptions options_; 70 std::unique_ptr<ResourceMgr> resource_mgr_; 71 }; 72 73 } // end namespace grappler 74 } // end namespace tensorflow 75 76 #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_LOOP_OPTIMIZER_H_ 77