• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "tensorflow/lite/graph_info.h"
16 #include <algorithm>
17 #include "tensorflow/lite/c/c_api_internal.h"
18 
19 namespace tflite {
20 
21 namespace {
22 
23 // Provide a range iterable wrapper for TfLiteIntArray* (C lists that TfLite
24 // C api uses. Can't use the google array_view, since we can't depend on even
25 // absl for embedded device reasons.
26 // TODO(aselle): Move this into central utilities.
27 class TfLiteIntArrayView {
28  public:
29   // Construct a view of a TfLiteIntArray*. Note, `int_array` should be non-null
30   // and this view does not take ownership of it.
TfLiteIntArrayView(const TfLiteIntArray * int_array)31   explicit TfLiteIntArrayView(const TfLiteIntArray* int_array)
32       : int_array_(int_array) {}
33 
34   typedef const int* const_iterator;
begin() const35   const_iterator begin() const { return int_array_->data; }
end() const36   const_iterator end() const { return &int_array_->data[int_array_->size]; }
37 
38   TfLiteIntArrayView(const TfLiteIntArrayView&) = default;
39   TfLiteIntArrayView& operator=(const TfLiteIntArrayView& rhs) = default;
40 
41  private:
42   const TfLiteIntArray* int_array_;
43 };
44 
45 // Helper class that actually performs partitioning by node sub set.
46 // Outputs to a provided `NodeSubset` structure.
47 //
48 // Example usage:
49 // PartitionGraphIntoIndependentNodeSubsetsImpl partitioner(
50 //     info, nodes_to_part, node_subsets);
51 // partitioner.Partition();
52 class PartitionGraphIntoIndependentNodeSubsetsImpl {
53  public:
PartitionGraphIntoIndependentNodeSubsetsImpl(const GraphInfo * info,const TfLiteIntArray * nodes_to_partition,std::vector<NodeSubset> * node_subsets)54   PartitionGraphIntoIndependentNodeSubsetsImpl(
55       const GraphInfo* info, const TfLiteIntArray* nodes_to_partition,
56       std::vector<NodeSubset>* node_subsets)
57       : info_(info),
58         node_subsets_(node_subsets),
59         node_type_(info->num_nodes(), NodeSubset::kTfNonPartition) {
60     // Populate the node_type_ map.
61     for (auto node_index : TfLiteIntArrayView(nodes_to_partition)) {
62       node_type_[node_index] = NodeSubset::kTfPartition;
63     }
64   }
65 
66   // Actually partition the graph.
Partition()67   void Partition() {
68     // Initialize here to make Partition() re-entrant.
69     node_subsets_->clear();
70     tensor_epochs_.clear();
71     tensor_epochs_.resize(info_->num_tensors(), kEpochAlwaysReady);
72     node_epochs_.clear();
73     node_epochs_.resize(info_->num_nodes(), kEpochNotReady);
74     // Set computed tensors to be kEpochNotReady (initializer set everything to
75     // AlwaysReady).
76     for (int node_index = 0; node_index < info_->num_nodes(); node_index++) {
77       const TfLiteNode& node = info_->node(node_index);
78       for (int output_tensor_index : TfLiteIntArrayView(node.outputs)) {
79         tensor_epochs_[output_tensor_index] = kEpochNotReady;
80       }
81     }
82 
83     // Do a graph traversal where each iteration in the loop is an epoch
84     // that corresponds to a node sub set that only contains nodes that are of
85     // the same node_type_.
86     while (true) {
87       BuildNodeSubset();
88       if (node_subsets_->back().nodes.empty()) {
89         node_subsets_->pop_back();
90         break;
91       }
92     }
93 
94     // Mark model outputs as node sub set outputs. All the rest have already
95     // been identified.
96     for (int output_index : info_->outputs()) {
97       int output_epoch = tensor_epochs_[output_index];
98       if (output_epoch == kEpochAlwaysReady) {
99         // This happens when an input of subgraph is also an output of subgraph.
100         continue;
101       }
102       NodeSubset& output_subset = (*node_subsets_)[output_epoch];
103       output_subset.output_tensors.push_back(output_index);
104     }
105     // Make sure every node sub set's inputs and outputs are unique. Since the
106     // list of inputs and outputs is generated in a way that produces
107     // duplicates.
108     for (NodeSubset& node_subset : *node_subsets_) {
109       // Sort and uniquefy using standard library algorithms.
110       auto uniquefy = [](std::vector<int>* items) {
111         std::sort(items->begin(), items->end());
112         auto last = std::unique(items->begin(), items->end());
113         items->erase(last, items->end());
114       };
115       uniquefy(&node_subset.input_tensors);
116       uniquefy(&node_subset.output_tensors);
117     }
118   }
119 
120  private:
121   // Special integer values needed for tensor_epochs_ and node_epochs_.
122   enum {
123     // The node or tensor is not ready to be assigned an epoch. e.g. a node's
124     // inputs have not all been assigned epochs.
125     kEpochNotReady = -1,
126     // Used for tensor_epochs_. This means that the tensor is always ready.
127     // e.g. an input to the whole model or a constant that has no dependencies.
128     kEpochAlwaysReady = -2
129   };
130 
131   // Updates the  node `node_index` and returns true if it is assigned to an
132   // epoch. False is returned if the node is already set to an epoch, its inputs
133   // are not all assigned to epochs, or if it cannot be assigned to the current
134   // epoch since the epoch's node_type doesn't match.
UpdateNode(int node_index)135   bool UpdateNode(int node_index) {
136     const TfLiteNode& node = info_->node(node_index);
137     NodeSubset& current_subset = node_subsets_->back();
138     int current_epoch = node_subsets_->size() - 1;
139     // Check if node is already done.
140     if (node_epochs_[node_index] != kEpochNotReady) {
141       return false;
142     }
143     // See if all dependencies of this node are already assigned to a
144     // node sub set.
145     for (int input_tensor_index : TfLiteIntArrayView(node.inputs)) {
146       if (input_tensor_index != kOptionalTensor &&
147           tensor_epochs_[input_tensor_index] == kEpochNotReady) {
148         return false;
149       }
150     }
151     // When we are starting a new epoch, the first ready node defines
152     // the type of that epoch.
153     if (current_subset.type == NodeSubset::kTfUnexplored) {
154       current_subset.type = node_type_[node_index];
155     }
156     // The node gets assigned to this epoch if it is the same type as
157     // the epoch's assigned type. Note, if this is the current ready
158     // node encountered during this epoch, this condition will be
159     // automatically true.
160     if (current_subset.type == node_type_[node_index]) {
161       node_epochs_[node_index] = current_epoch;
162       current_subset.nodes.push_back(node_index);
163       // All outputs of this node now are assigned to this epoch as
164       // well.
165       for (int output_tensor_index : TfLiteIntArrayView(node.outputs)) {
166         tensor_epochs_[output_tensor_index] = current_epoch;
167       }
168       // Look at our inputs one more time to update that tensor's
169       // epochs' outputs
170       for (int input_tensor_index : TfLiteIntArrayView(node.inputs)) {
171         if (input_tensor_index == kOptionalTensor) {
172           continue;
173         }
174         int input_epoch = tensor_epochs_[input_tensor_index];
175         int node_epoch = current_epoch;
176         if (input_epoch != node_epoch) {
177           current_subset.input_tensors.push_back(input_tensor_index);
178           // Set inputs to be outputs of the node sub set where they reside.
179           // the if condition makes sure inputs to the whole computation
180           // are not included (i.e. those initialized to -2 above).
181           if (input_epoch >= 0) {
182             NodeSubset& input_subset = (*node_subsets_)[input_epoch];
183             input_subset.output_tensors.push_back(input_tensor_index);
184           }
185         }
186       }
187       return true;
188     } else {
189       return false;
190     }
191   }
192 
193   // Completely populates the current node_subset by doing graph traversal
BuildNodeSubset()194   void BuildNodeSubset() {
195     node_subsets_->emplace_back(NodeSubset());
196     // loop until no more nodes can be updated.
197     while (true) {
198       bool did_something = false;
199       for (int node_index = 0; node_index < info_->num_nodes(); node_index++) {
200         if (UpdateNode(node_index)) {
201           did_something = true;
202         }
203       }
204       if (!did_something) return;
205     }
206   }
207 
208   // Temporary data needed for partitioning.
209   const GraphInfo* info_;
210   // List of node_subsets to populate
211   std::vector<NodeSubset>* node_subsets_;
212   std::vector<NodeSubset::Type> node_type_;
213   // Maps from tensor index to the epoch in which it is assigned. Also special
214   // negative values of kEpochNotAssigned if not assigned, kEpochNotReady if it
215   // is an input or constant.
216   std::vector<int> tensor_epochs_;
217   // Maps from tensor index to the epoch in which it is assigned. Also special
218   // negative values of kEpochNotAssigned if not assigned.
219   std::vector<int> node_epochs_;
220 };
221 
222 }  // namespace
223 
PartitionGraphIntoIndependentNodeSubsets(const GraphInfo * info,const TfLiteIntArray * nodes_to_partition,std::vector<NodeSubset> * node_subsets)224 TfLiteStatus PartitionGraphIntoIndependentNodeSubsets(
225     const GraphInfo* info, const TfLiteIntArray* nodes_to_partition,
226     std::vector<NodeSubset>* node_subsets) {
227   PartitionGraphIntoIndependentNodeSubsetsImpl(info, nodes_to_partition,
228                                                node_subsets)
229       .Partition();
230   return kTfLiteOk;
231 }
232 
233 }  // namespace tflite
234