exporter.py 16.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Copyright 2017 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.
# ==============================================================================

"""Functions to export object detection inference graph."""
import logging
import os
Vivek Rathod's avatar
Vivek Rathod committed
19
import tempfile
20
import tensorflow as tf
21
from google.protobuf import text_format
22
23
24
25
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.client import session
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
26
from tensorflow.python.saved_model import signature_constants
27
28
29
30
31
32
33
34
from tensorflow.python.training import saver as saver_lib
from object_detection.builders import model_builder
from object_detection.core import standard_fields as fields
from object_detection.data_decoders import tf_example_decoder

slim = tf.contrib.slim


35
36
# TODO: Replace with freeze_graph.freeze_graph_with_def_protos when
# newer version of Tensorflow becomes more common.
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def freeze_graph_with_def_protos(
    input_graph_def,
    input_saver_def,
    input_checkpoint,
    output_node_names,
    restore_op_name,
    filename_tensor_name,
    clear_devices,
    initializer_nodes,
    variable_names_blacklist=''):
  """Converts all variables in a graph and checkpoint into constants."""
  del restore_op_name, filename_tensor_name  # Unused by updated loading code.

  # 'input_checkpoint' may be a prefix if we're using Saver V2 format
  if not saver_lib.checkpoint_exists(input_checkpoint):
52
53
    raise ValueError(
        'Input checkpoint "' + input_checkpoint + '" does not exist!')
54
55

  if not output_node_names:
56
57
    raise ValueError(
        'You must supply the name of a node to --output_node_names.')
58
59
60
61
62
63
64

  # Remove all the explicit device specifications for this node. This helps to
  # make the graph more portable.
  if clear_devices:
    for node in input_graph_def.node:
      node.device = ''

65
66
  with tf.Graph().as_default():
    tf.import_graph_def(input_graph_def, name='')
67
    config = tf.ConfigProto(graph_options=tf.GraphOptions())
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
    with session.Session(config=config) as sess:
      if input_saver_def:
        saver = saver_lib.Saver(saver_def=input_saver_def)
        saver.restore(sess, input_checkpoint)
      else:
        var_list = {}
        reader = pywrap_tensorflow.NewCheckpointReader(input_checkpoint)
        var_to_shape_map = reader.get_variable_to_shape_map()
        for key in var_to_shape_map:
          try:
            tensor = sess.graph.get_tensor_by_name(key + ':0')
          except KeyError:
            # This tensor doesn't exist in the graph (for example it's
            # 'global_step' or a similar housekeeping element) so skip it.
            continue
          var_list[key] = tensor
        saver = saver_lib.Saver(var_list=var_list)
        saver.restore(sess, input_checkpoint)
        if initializer_nodes:
          sess.run(initializer_nodes)

      variable_names_blacklist = (variable_names_blacklist.split(',') if
                                  variable_names_blacklist else None)
      output_graph_def = graph_util.convert_variables_to_constants(
          sess,
          input_graph_def,
          output_node_names.split(','),
          variable_names_blacklist=variable_names_blacklist)
96

97
98
99
  return output_graph_def


Vivek Rathod's avatar
Vivek Rathod committed
100
101
102
103
def replace_variable_values_with_moving_averages(graph,
                                                 current_checkpoint_file,
                                                 new_checkpoint_file):
  """Replaces variable values in the checkpoint with their moving averages.
104

Vivek Rathod's avatar
Vivek Rathod committed
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
  If the current checkpoint has shadow variables maintaining moving averages of
  the variables defined in the graph, this function generates a new checkpoint
  where the variables contain the values of their moving averages.

  Args:
    graph: a tf.Graph object.
    current_checkpoint_file: a checkpoint containing both original variables and
      their moving averages.
    new_checkpoint_file: file path to write a new checkpoint.
  """
  with graph.as_default():
    variable_averages = tf.train.ExponentialMovingAverage(0.0)
    ema_variables_to_restore = variable_averages.variables_to_restore()
    with tf.Session() as sess:
      read_saver = tf.train.Saver(ema_variables_to_restore)
      read_saver.restore(sess, current_checkpoint_file)
      write_saver = tf.train.Saver()
      write_saver.save(sess, new_checkpoint_file)


def _image_tensor_input_placeholder(input_shape=None):
  """Returns input placeholder and a 4-D uint8 image tensor."""
  if input_shape is None:
    input_shape = (None, None, None, 3)
  input_tensor = tf.placeholder(
      dtype=tf.uint8, shape=input_shape, name='image_tensor')
Derek Chow's avatar
Derek Chow committed
131
  return input_tensor, input_tensor
132

133

134
def _tf_example_input_placeholder():
Derek Chow's avatar
Derek Chow committed
135
136
137
  """Returns input that accepts a batch of strings with tf examples.

  Returns:
Vivek Rathod's avatar
Vivek Rathod committed
138
    a tuple of input placeholder and the output decoded images.
Derek Chow's avatar
Derek Chow committed
139
  """
140
141
142
143
144
145
146
  batch_tf_example_placeholder = tf.placeholder(
      tf.string, shape=[None], name='tf_example')
  def decode(tf_example_string_tensor):
    tensor_dict = tf_example_decoder.TfExampleDecoder().decode(
        tf_example_string_tensor)
    image_tensor = tensor_dict[fields.InputDataFields.image]
    return image_tensor
Derek Chow's avatar
Derek Chow committed
147
148
149
150
151
152
  return (batch_tf_example_placeholder,
          tf.map_fn(decode,
                    elems=batch_tf_example_placeholder,
                    dtype=tf.uint8,
                    parallel_iterations=32,
                    back_prop=False))
153
154


155
def _encoded_image_string_tensor_input_placeholder():
Derek Chow's avatar
Derek Chow committed
156
157
158
  """Returns input that accepts a batch of PNG or JPEG strings.

  Returns:
Vivek Rathod's avatar
Vivek Rathod committed
159
    a tuple of input placeholder and the output decoded images.
Derek Chow's avatar
Derek Chow committed
160
  """
161
162
163
164
165
166
167
168
169
  batch_image_str_placeholder = tf.placeholder(
      dtype=tf.string,
      shape=[None],
      name='encoded_image_string_tensor')
  def decode(encoded_image_string_tensor):
    image_tensor = tf.image.decode_image(encoded_image_string_tensor,
                                         channels=3)
    image_tensor.set_shape((None, None, 3))
    return image_tensor
Derek Chow's avatar
Derek Chow committed
170
171
172
173
174
175
176
  return (batch_image_str_placeholder,
          tf.map_fn(
              decode,
              elems=batch_image_str_placeholder,
              dtype=tf.uint8,
              parallel_iterations=32,
              back_prop=False))
177
178


179
input_placeholder_fn_map = {
180
181
182
    'image_tensor': _image_tensor_input_placeholder,
    'encoded_image_string_tensor':
    _encoded_image_string_tensor_input_placeholder,
183
184
185
186
    'tf_example': _tf_example_input_placeholder,
}


187
188
def _add_output_tensor_nodes(postprocessed_tensors,
                             output_collection_name='inference_op'):
189
190
191
192
193
194
195
196
197
198
  """Adds output nodes for detection boxes and scores.

  Adds the following nodes for output tensors -
    * num_detections: float32 tensor of shape [batch_size].
    * detection_boxes: float32 tensor of shape [batch_size, num_boxes, 4]
      containing detected boxes.
    * detection_scores: float32 tensor of shape [batch_size, num_boxes]
      containing scores for the detected boxes.
    * detection_classes: float32 tensor of shape [batch_size, num_boxes]
      containing class predictions for the detected boxes.
199
200
201
    * detection_masks: (Optional) float32 tensor of shape
      [batch_size, num_boxes, mask_height, mask_width] containing masks for each
      detection box.
202
203
204
205
206
207

  Args:
    postprocessed_tensors: a dictionary containing the following fields
      'detection_boxes': [batch, max_detections, 4]
      'detection_scores': [batch, max_detections]
      'detection_classes': [batch, max_detections]
208
209
      'detection_masks': [batch, max_detections, mask_height, mask_width]
        (optional).
210
      'num_detections': [batch]
211
    output_collection_name: Name of collection to add output tensors to.
212
213
214

  Returns:
    A tensor dict containing the added output tensor nodes.
215
  """
216
  detection_fields = fields.DetectionResultFields
217
  label_id_offset = 1
218
219
220
221
222
223
  boxes = postprocessed_tensors.get(detection_fields.detection_boxes)
  scores = postprocessed_tensors.get(detection_fields.detection_scores)
  classes = postprocessed_tensors.get(
      detection_fields.detection_classes) + label_id_offset
  masks = postprocessed_tensors.get(detection_fields.detection_masks)
  num_detections = postprocessed_tensors.get(detection_fields.num_detections)
224
  outputs = {}
225
226
227
228
229
230
231
232
  outputs[detection_fields.detection_boxes] = tf.identity(
      boxes, name=detection_fields.detection_boxes)
  outputs[detection_fields.detection_scores] = tf.identity(
      scores, name=detection_fields.detection_scores)
  outputs[detection_fields.detection_classes] = tf.identity(
      classes, name=detection_fields.detection_classes)
  outputs[detection_fields.num_detections] = tf.identity(
      num_detections, name=detection_fields.num_detections)
233
  if masks is not None:
234
235
    outputs[detection_fields.detection_masks] = tf.identity(
        masks, name=detection_fields.detection_masks)
236
237
238
  for output_key in outputs:
    tf.add_to_collection(output_collection_name, outputs[output_key])
  if masks is not None:
239
240
    tf.add_to_collection(output_collection_name,
                         outputs[detection_fields.detection_masks])
241
  return outputs
242
243


244
245
def _write_frozen_graph(frozen_graph_path, frozen_graph_def):
  """Writes frozen graph to disk.
246
247

  Args:
248
249
    frozen_graph_path: Path to write inference graph.
    frozen_graph_def: tf.GraphDef holding frozen graph.
250
  """
251
252
253
254
255
256
257
258
259
  with gfile.GFile(frozen_graph_path, 'wb') as f:
    f.write(frozen_graph_def.SerializeToString())
  logging.info('%d ops in the final graph.', len(frozen_graph_def.node))


def _write_saved_model(saved_model_path,
                       frozen_graph_def,
                       inputs,
                       outputs):
260
261
262
263
264
265
266
267
268
  """Writes SavedModel to disk.

  If checkpoint_path is not None bakes the weights into the graph thereby
  eliminating the need of checkpoint files during inference. If the model
  was trained with moving averages, setting use_moving_averages to true
  restores the moving averages, otherwise the original set of variables
  is restored.

  Args:
269
270
    saved_model_path: Path to write SavedModel.
    frozen_graph_def: tf.GraphDef holding frozen graph.
271
272
273
274
275
276
    inputs: The input image tensor to use for detection.
    outputs: A tensor dictionary containing the outputs of a DetectionModel.
  """
  with tf.Graph().as_default():
    with session.Session() as sess:

277
      tf.import_graph_def(frozen_graph_def, name='')
278

279
      builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

      tensor_info_inputs = {
          'inputs': tf.saved_model.utils.build_tensor_info(inputs)}
      tensor_info_outputs = {}
      for k, v in outputs.items():
        tensor_info_outputs[k] = tf.saved_model.utils.build_tensor_info(v)

      detection_signature = (
          tf.saved_model.signature_def_utils.build_signature_def(
              inputs=tensor_info_inputs,
              outputs=tensor_info_outputs,
              method_name=signature_constants.PREDICT_METHOD_NAME))

      builder.add_meta_graph_and_variables(
          sess, [tf.saved_model.tag_constants.SERVING],
          signature_def_map={
Derek Chow's avatar
Derek Chow committed
296
              signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
297
298
299
300
301
302
                  detection_signature,
          },
      )
      builder.save()


303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def _write_graph_and_checkpoint(inference_graph_def,
                                model_path,
                                input_saver_def,
                                trained_checkpoint_prefix):
  for node in inference_graph_def.node:
    node.device = ''
  with tf.Graph().as_default():
    tf.import_graph_def(inference_graph_def, name='')
    with session.Session() as sess:
      saver = saver_lib.Saver(saver_def=input_saver_def,
                              save_relative_paths=True)
      saver.restore(sess, trained_checkpoint_prefix)
      saver.save(sess, model_path)


318
319
320
def _export_inference_graph(input_type,
                            detection_model,
                            use_moving_averages,
321
322
                            trained_checkpoint_prefix,
                            output_directory,
Vivek Rathod's avatar
Vivek Rathod committed
323
324
                            additional_output_tensor_names=None,
                            input_shape=None,
325
326
                            output_collection_name='inference_op',
                            graph_hook_fn=None):
327
  """Export helper."""
328
329
330
331
332
333
  tf.gfile.MakeDirs(output_directory)
  frozen_graph_path = os.path.join(output_directory,
                                   'frozen_inference_graph.pb')
  saved_model_path = os.path.join(output_directory, 'saved_model')
  model_path = os.path.join(output_directory, 'model.ckpt')

334
335
  if input_type not in input_placeholder_fn_map:
    raise ValueError('Unknown input type: {}'.format(input_type))
Vivek Rathod's avatar
Vivek Rathod committed
336
337
338
339
340
341
342
343
  placeholder_args = {}
  if input_shape is not None:
    if input_type != 'image_tensor':
      raise ValueError('Can only specify input shape for `image_tensor` '
                       'inputs.')
    placeholder_args['input_shape'] = input_shape
  placeholder_tensor, input_tensors = input_placeholder_fn_map[input_type](
      **placeholder_args)
Derek Chow's avatar
Derek Chow committed
344
  inputs = tf.to_float(input_tensors)
345
346
347
348
349
  preprocessed_inputs, true_image_shapes = detection_model.preprocess(inputs)
  output_tensors = detection_model.predict(
      preprocessed_inputs, true_image_shapes)
  postprocessed_tensors = detection_model.postprocess(
      output_tensors, true_image_shapes)
350
351
  outputs = _add_output_tensor_nodes(postprocessed_tensors,
                                     output_collection_name)
Vivek Rathod's avatar
Vivek Rathod committed
352
353
  # Add global step to the graph.
  slim.get_or_create_global_step()
354

355
356
  if graph_hook_fn: graph_hook_fn()

357
  if use_moving_averages:
Vivek Rathod's avatar
Vivek Rathod committed
358
359
360
361
362
    temp_checkpoint_file = tempfile.NamedTemporaryFile()
    replace_variable_values_with_moving_averages(
        tf.get_default_graph(), trained_checkpoint_prefix,
        temp_checkpoint_file.name)
    checkpoint_to_use = temp_checkpoint_file.name
363
  else:
Vivek Rathod's avatar
Vivek Rathod committed
364
365
366
    checkpoint_to_use = trained_checkpoint_prefix

  saver = tf.train.Saver()
367
368
369
370
371
372
  input_saver_def = saver.as_saver_def()

  _write_graph_and_checkpoint(
      inference_graph_def=tf.get_default_graph().as_graph_def(),
      model_path=model_path,
      input_saver_def=input_saver_def,
Vivek Rathod's avatar
Vivek Rathod committed
373
374
375
376
377
378
      trained_checkpoint_prefix=checkpoint_to_use)

  if additional_output_tensor_names is not None:
    output_node_names = ','.join(outputs.keys()+additional_output_tensor_names)
  else:
    output_node_names = ','.join(outputs.keys())
379
380
381
382

  frozen_graph_def = freeze_graph_with_def_protos(
      input_graph_def=tf.get_default_graph().as_graph_def(),
      input_saver_def=input_saver_def,
Vivek Rathod's avatar
Vivek Rathod committed
383
384
      input_checkpoint=checkpoint_to_use,
      output_node_names=output_node_names,
385
386
387
388
389
      restore_op_name='save/restore_all',
      filename_tensor_name='save/Const:0',
      clear_devices=True,
      initializer_nodes='')
  _write_frozen_graph(frozen_graph_path, frozen_graph_def)
Vivek Rathod's avatar
Vivek Rathod committed
390
391
  _write_saved_model(saved_model_path, frozen_graph_def,
                     placeholder_tensor, outputs)
392
393


394
395
396
397
def export_inference_graph(input_type,
                           pipeline_config,
                           trained_checkpoint_prefix,
                           output_directory,
Vivek Rathod's avatar
Vivek Rathod committed
398
399
400
                           input_shape=None,
                           output_collection_name='inference_op',
                           additional_output_tensor_names=None):
401
402
403
404
405
406
  """Exports inference graph for the model specified in the pipeline config.

  Args:
    input_type: Type of input for the graph. Can be one of [`image_tensor`,
      `tf_example`].
    pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.
407
408
    trained_checkpoint_prefix: Path to the trained checkpoint file.
    output_directory: Path to write outputs.
Vivek Rathod's avatar
Vivek Rathod committed
409
410
    input_shape: Sets a fixed shape for an `image_tensor` input. If not
      specified, will default to [None, None, None, 3].
411
412
    output_collection_name: Name of collection to add output tensors to.
      If None, does not add output tensors to a collection.
Vivek Rathod's avatar
Vivek Rathod committed
413
    additional_output_tensor_names: list of additional output
414
      tensors to include in the frozen graph.
415
416
417
418
419
  """
  detection_model = model_builder.build(pipeline_config.model,
                                        is_training=False)
  _export_inference_graph(input_type, detection_model,
                          pipeline_config.eval_config.use_moving_averages,
Vivek Rathod's avatar
Vivek Rathod committed
420
421
                          trained_checkpoint_prefix,
                          output_directory, additional_output_tensor_names,
422
423
424
425
426
427
428
                          input_shape, output_collection_name,
                          graph_hook_fn=None)
  pipeline_config.eval_config.use_moving_averages = False
  config_text = text_format.MessageToString(pipeline_config)
  with tf.gfile.Open(
      os.path.join(output_directory, 'pipeline.config'), 'wb') as f:
    f.write(config_text)