1 /* Copyright 2020 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_COMMON_SUBGRAPH_ELIMINATION_H_
17 #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_COMMON_SUBGRAPH_ELIMINATION_H_
18 
19 #include <unordered_set>
20 
21 #include "tensorflow/core/framework/graph.pb.h"
22 #include "tensorflow/core/framework/node_def.pb.h"
23 #include "tensorflow/core/grappler/optimizers/graph_optimizer.h"
24 #include "tensorflow/core/lib/gtl/flatset.h"
25 #include "tensorflow/core/platform/hash.h"
26 #include "tensorflow/core/platform/status.h"
27 #include "tensorflow/core/protobuf/rewriter_config.pb.h"
28 
29 namespace tensorflow {
30 namespace grappler {
31 
32 // Optimize TF computations by deduping equivalent subgraphs.
33 class Cluster;
34 struct GrapplerItem;
35 
36 class CommonSubgraphElimination : public GraphOptimizer {
37  public:
CommonSubgraphElimination()38   CommonSubgraphElimination() {}
39 
CommonSubgraphElimination(RewriterConfig::Toggle opt_level)40   explicit CommonSubgraphElimination(RewriterConfig::Toggle opt_level)
41       : opt_level_(opt_level) {}
42 
~CommonSubgraphElimination()43   ~CommonSubgraphElimination() override {}
44 
name()45   string name() const override { return "common_subgraph_elimination"; };
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 CommonSubgraphEliminationTest;
57 
58   // Returns true if it is safe to dedup node from the graph.
59   bool CanDedup(const NodeDef& node) const;
60 
61   // Dedup redundant nodes in the graph.
62   Status DedupComputations(GraphDef* optimized_graph);
63 
64   RewriterConfig::Toggle opt_level_;
65 
66   bool fetch_nodes_known_ = false;
67   std::unordered_set<string> nodes_to_preserve_;
68 };
69 
70 }  // end namespace grappler
71 }  // end namespace tensorflow
72 
73 #endif  // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_COMMON_SUBGRAPH_ELIMINATION_H_
74