• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2019 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 #include "tensorflow/lite/delegates/gpu/common/memory_management/types.h"
17 
18 #include <algorithm>
19 #include <cstddef>
20 #include <queue>
21 #include <vector>
22 
23 namespace tflite {
24 namespace gpu {
25 namespace {
26 
BFS(size_t start,const UsageGraph & deps_graph,std::vector<size_t> * num_visits)27 void BFS(size_t start, const UsageGraph& deps_graph,
28          std::vector<size_t>* num_visits) {
29   std::queue<size_t> queue;
30   std::vector<char> is_visited(deps_graph.size(),
31                                0);  // use char instead of bool, because
32                                     // std::vector<bool> is based on bitset
33   queue.push(start);
34   is_visited[start] = true;
35   while (!queue.empty()) {
36     size_t from_vertex = queue.front();
37     queue.pop();
38     for (const auto& to_vertex : deps_graph[from_vertex]) {
39       if (!is_visited[to_vertex]) {
40         queue.push(to_vertex);
41         is_visited[to_vertex] = true;
42         (*num_visits)[to_vertex] += 1;
43       }
44     }
45   }
46 }
47 
48 }  // namespace
49 
ReallocationGraph(const UsageGraph & deps_graph)50 UsageGraph ReallocationGraph(const UsageGraph& deps_graph) {
51   size_t num_vertices = deps_graph.size();
52   UsageGraph reallocation_graph(num_vertices);
53   for (size_t root = 0; root < num_vertices; ++root) {
54     std::vector<size_t> num_visits(num_vertices, 0);
55     const std::vector<size_t>& children = deps_graph[root];
56     if (children.empty()) {
57       // Check
58       continue;
59     }
60     for (const auto& child : children) {
61       BFS(child, deps_graph, &num_visits);
62     }
63     for (size_t vertex = 0; vertex < num_vertices; ++vertex) {
64       if (num_visits[vertex] == children.size()) {
65         reallocation_graph[root].push_back(vertex);
66         reallocation_graph[vertex].push_back(root);
67       }
68     }
69   }
70   for (size_t vertex = 0; vertex < num_vertices; ++vertex) {
71     std::sort(reallocation_graph[vertex].begin(),
72               reallocation_graph[vertex].end());
73   }
74   return reallocation_graph;
75 }
76 
77 }  // namespace gpu
78 }  // namespace tflite
79