aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/tools/graph_transforms/summarize_graph_main.cc
blob: 8c23ae7a74901dd24558a6309fa428b2f5aec32f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// This program prints out a summary of a GraphDef file's contents, listing
// things that are useful for debugging and reusing the model it contains. For
// example it looks at the graph structure and op types to figure out likely
// input and output nodes, and shows which ops are used by the graph. To use it,
// run something like this:
//
// bazel build tensorflow/tools/graph_transforms:summarize_graph
// bazel-bin/tensorflow/tools/graph_transforms/summarize_graph \
// --in_graph=my_graph.pb

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"

namespace tensorflow {
namespace graph_transforms {
namespace {

void PrintNodeInfo(const NodeDef* node) {
  TensorShape shape;
  if (node->attr().count("shape")) {
    TensorShapeProto shape_proto = node->attr().at("shape").shape();
    shape = TensorShape(shape_proto);
  }
  DataType dtype = DT_INVALID;
  if (node->attr().count("dtype")) {
    dtype = node->attr().at("dtype").type();
  }
  std::cout << "(name=" << node->name();
  std::cout << ", type=" << DataTypeString(dtype) << "(" << dtype << ")";
  std::cout << ", shape=" << shape.DebugString() << ") ";
}

void PrintBenchmarkUsage(const std::vector<const NodeDef*> placeholders,
                         const std::vector<const NodeDef*> variables,
                         const std::vector<const NodeDef*> outputs,
                         const string& graph_path) {
  std::vector<const NodeDef*> all_inputs(placeholders);
  all_inputs.insert(all_inputs.end(), variables.begin(), variables.end());

  std::vector<string> input_layers;
  std::vector<string> input_layer_types;
  std::vector<string> input_layer_shapes;
  for (const NodeDef* node : all_inputs) {
    input_layers.push_back(node->name());
    DataType dtype = DT_INVALID;
    if (node->attr().count("dtype")) {
      dtype = node->attr().at("dtype").type();
    }
    input_layer_types.push_back(DataTypeString(dtype));
    std::vector<int64> sizes;
    TensorShape shape;
    if (node->attr().count("shape")) {
      TensorShapeProto shape_proto = node->attr().at("shape").shape();
      shape = TensorShape(shape_proto);
    }
    for (int i = 0; i < shape.dims(); ++i) {
      sizes.push_back(shape.dim_size(i));
    }
    string sizes_string = str_util::Join(sizes, ",");
    input_layer_shapes.push_back(sizes_string);
  }
  std::vector<string> output_layers;
  for (const NodeDef* node : outputs) {
    output_layers.push_back(node->name());
  }
  string input_layer_value = str_util::Join(input_layers, ",");
  string input_layer_type_value = str_util::Join(input_layer_types, ",");
  string input_layer_shape_value = str_util::Join(input_layer_shapes, ":");
  string output_layer_value = str_util::Join(output_layers, ",");

  std::cout << "To use with tensorflow/tools/benchmark:benchmark_model try "
               "these arguments:"
            << std::endl;
  std::cout << "bazel run tensorflow/tools/benchmark:benchmark_model --";
  std::cout << " --graph=" << graph_path;
  std::cout << " --show_flops";
  std::cout << " --logtostderr";
  std::cout << " --input_layer=" << input_layer_value;
  std::cout << " --input_layer_type=" << input_layer_type_value;
  std::cout << " --input_layer_shape=" << input_layer_shape_value;
  std::cout << " --output_layer=" << output_layer_value;
  std::cout << std::endl;
}

Status SummarizeGraph(const GraphDef& graph, const string& graph_path) {
  std::vector<const NodeDef*> placeholders;
  std::vector<const NodeDef*> variables;
  for (const NodeDef& node : graph.node()) {
    if (node.op() == "Placeholder") {
      placeholders.push_back(&node);
    }
    if (node.op() == "Variable") {
      variables.push_back(&node);
    }
  }

  if (placeholders.empty()) {
    std::cout << "No inputs spotted." << std::endl;
  } else {
    std::cout << "Found " << placeholders.size() << " possible inputs: ";
    for (const NodeDef* node : placeholders) {
      PrintNodeInfo(node);
    }
    std::cout << std::endl;
  }

  if (variables.empty()) {
    std::cout << "No variables spotted." << std::endl;
  } else {
    std::cout << "Found " << variables.size() << " variables: ";
    for (const NodeDef* node : variables) {
      PrintNodeInfo(node);
    }
    std::cout << std::endl;
  }

  std::map<string, std::vector<const NodeDef*>> output_map;
  MapNodesToOutputs(graph, &output_map);
  std::vector<const NodeDef*> outputs;
  for (const NodeDef& node : graph.node()) {
    if ((output_map.count(node.name()) == 0) && (node.op() != "Const") &&
        (node.op() != "Assign") && (node.op() != "NoOp")) {
      outputs.push_back(&node);
    }
  }

  if (outputs.empty()) {
    std::cout << "No outputs spotted." << std::endl;
  } else {
    std::cout << "Found " << outputs.size() << " possible outputs: ";
    for (const NodeDef* node : outputs) {
      std::cout << "(name=" << node->name();
      std::cout << ", op=" << node->op() << ") ";
    }
    std::cout << std::endl;
  }

  int64 const_parameter_count = 0;
  int64 variable_parameter_count = 0;
  int control_edge_count = 0;
  std::map<string, int> device_counts;
  for (const NodeDef& node : graph.node()) {
    for (const string& input : node.input()) {
      if (input.substr(0, 1) == "^") {
        ++control_edge_count;
      }
    }
    if (node.device() != "") {
      ++device_counts[node.device()];
    }
    if ((node.op() == "Const") || (node.op() == "Variable")) {
      Tensor tensor;
      if (node.attr().count("value") &&
          tensor.FromProto(node.attr().at("value").tensor())) {
        const size_t num_elements = tensor.NumElements();
        if (node.op() == "Const") {
          const_parameter_count += num_elements;
        } else {
          variable_parameter_count += num_elements;
        }
      } else {
        LOG(WARNING) << "Decoding Tensor failed for node" << node.name();
      }
    }
  }

  std::cout << "Found " << const_parameter_count << " ("
            << strings::HumanReadableNum(const_parameter_count)
            << ") const parameters, " << variable_parameter_count << " ("
            << strings::HumanReadableNum(variable_parameter_count)
            << ") variable parameters, and " << control_edge_count
            << " control_edges" << std::endl;
  if (!device_counts.empty()) {
    for (const auto& device_info : device_counts) {
      std::cout << device_info.second << " nodes assigned to device '"
                << device_info.first << "'";
    }
  }

  std::vector<std::pair<string, string>> invalid_inputs;
  FindInvalidInputs(graph, &invalid_inputs);
  if (!invalid_inputs.empty()) {
    for (const std::pair<string, string>& invalid_input : invalid_inputs) {
      std::cout << "Invalid input " << invalid_input.second << " for node "
                << invalid_input.first << std::endl;
    }
    return errors::Internal(
        "Invalid graph with inputs referring to nonexistent nodes");
  }

  std::map<string, int> op_counts;
  for (const NodeDef& node : graph.node()) {
    ++op_counts[node.op()];
  }
  std::vector<std::pair<string, int>> op_counts_vec(op_counts.begin(),
                                                    op_counts.end());
  std::sort(op_counts_vec.begin(), op_counts_vec.end(),
            [](std::pair<string, int> a, std::pair<string, int> b) {
              return (a.second > b.second);
            });
  std::cout << "Op types used: ";
  bool is_first = true;
  for (const std::pair<string, int>& op_count : op_counts_vec) {
    if (!is_first) {
      std::cout << ", ";
    } else {
      is_first = false;
    }
    std::cout << op_count.second << " " << op_count.first;
  }
  std::cout << std::endl;

  PrintBenchmarkUsage(placeholders, variables, outputs, graph_path);

  return Status::OK();
}

int ParseFlagsAndSummarizeGraph(int argc, char* argv[]) {
  string in_graph = "";
  std::vector<Flag> flag_list = {
      Flag("in_graph", &in_graph, "input graph file name"),
  };
  string usage = Flags::Usage(argv[0], flag_list);

  const bool parse_result = Flags::Parse(&argc, argv, flag_list);
  // We need to call this to set up global state for TensorFlow.
  port::InitMain(argv[0], &argc, &argv);

  if (!parse_result) {
    LOG(ERROR) << usage;
    return -1;
  }
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << ".\n" << usage;
    return -1;
  }
  if (in_graph.empty()) {
    LOG(ERROR) << "in_graph graph can't be empty.\n" << usage;
    return -1;
  }

  GraphDef graph_def;
  Status load_status = LoadTextOrBinaryGraphFile(in_graph, &graph_def);
  if (!load_status.ok()) {
    LOG(ERROR) << "Loading graph '" << in_graph << "' failed with "
               << load_status.error_message();
    LOG(ERROR) << usage;
    return -1;
  }

  Status summarize_result = SummarizeGraph(graph_def, in_graph);
  if (!summarize_result.ok()) {
    LOG(ERROR) << summarize_result.error_message() << "\n" << usage;
    return -1;
  }

  return 0;
}

}  // namespace
}  // namespace graph_transforms
}  // namespace tensorflow

int main(int argc, char* argv[]) {
  return tensorflow::graph_transforms::ParseFlagsAndSummarizeGraph(argc, argv);
}