exporter.py 27.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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 os
Vivek Rathod's avatar
Vivek Rathod committed
18
import tempfile
19
20
import tensorflow.compat.v1 as tf
import tf_slim as slim
21
from tensorflow.core.protobuf import saver_pb2
22
from tensorflow.python.tools import freeze_graph  # pylint: disable=g-direct-tensorflow-import
23
from object_detection.builders import graph_rewriter_builder
24
25
26
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
27
from object_detection.utils import config_util
28
from object_detection.utils import shape_utils
29

30
31
32
33
34
35
36
37
# pylint: disable=g-import-not-at-top
try:
  from tensorflow.contrib import tfprof as contrib_tfprof
  from tensorflow.contrib.quantize.python import graph_matcher
except ImportError:
  # TF 2.0 doesn't ship with contrib.
  pass
# pylint: enable=g-import-not-at-top
38

39
freeze_graph_with_def_protos = freeze_graph.freeze_graph_with_def_protos
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
def parse_side_inputs(side_input_shapes_string, side_input_names_string,
                      side_input_types_string):
  """Parses side input flags.

  Args:
    side_input_shapes_string: The shape of the side input tensors, provided as a
      comma-separated list of integers. A value of -1 is used for unknown
      dimensions. A `/` denotes a break, starting the shape of the next side
      input tensor.
    side_input_names_string: The names of the side input tensors, provided as a
      comma-separated list of strings.
    side_input_types_string: The type of the side input tensors, provided as a
      comma-separated list of types, each of `string`, `integer`, or `float`.

  Returns:
    side_input_shapes: A list of shapes.
    side_input_names: A list of strings.
    side_input_types: A list of tensorflow dtypes.

  """
  if side_input_shapes_string:
    side_input_shapes = []
    for side_input_shape_list in side_input_shapes_string.split('/'):
      side_input_shape = [
          int(dim) if dim != '-1' else None
          for dim in side_input_shape_list.split(',')
      ]
      side_input_shapes.append(side_input_shape)
  else:
    raise ValueError('When using side_inputs, side_input_shapes must be '
                     'specified in the input flags.')
  if side_input_names_string:
    side_input_names = list(side_input_names_string.split(','))
  else:
    raise ValueError('When using side_inputs, side_input_names must be '
                     'specified in the input flags.')
  if side_input_types_string:
    typelookup = {'float': tf.float32, 'int': tf.int32, 'string': tf.string}
    side_input_types = [
        typelookup[side_input_type]
        for side_input_type in side_input_types_string.split(',')
    ]
  else:
    raise ValueError('When using side_inputs, side_input_types must be '
                     'specified in the input flags.')
  return side_input_shapes, side_input_names, side_input_types


90
91
92
93
94
95
96
97
def rewrite_nn_resize_op(is_quantized=False):
  """Replaces a custom nearest-neighbor resize op with the Tensorflow version.

  Some graphs use this custom version for TPU-compatibility.

  Args:
    is_quantized: True if the default graph is quantized.
  """
98
  def remove_nn():
99
    """Remove nearest neighbor upsampling structures and replace with TF op."""
100
101
102
103
    input_pattern = graph_matcher.OpTypePattern(
        'FakeQuantWithMinMaxVars' if is_quantized else '*')
    stack_1_pattern = graph_matcher.OpTypePattern(
        'Pack', inputs=[input_pattern, input_pattern], ordered_inputs=False)
104
105
    reshape_1_pattern = graph_matcher.OpTypePattern(
        'Reshape', inputs=[stack_1_pattern, 'Const'], ordered_inputs=False)
106
    stack_2_pattern = graph_matcher.OpTypePattern(
107
108
109
110
        'Pack',
        inputs=[reshape_1_pattern, reshape_1_pattern],
        ordered_inputs=False)
    reshape_2_pattern = graph_matcher.OpTypePattern(
111
        'Reshape', inputs=[stack_2_pattern, 'Const'], ordered_inputs=False)
112
    consumer_pattern1 = graph_matcher.OpTypePattern(
113
114
        'Add|AddV2|Max|Mul',
        inputs=[reshape_2_pattern, '*'],
115
        ordered_inputs=False)
116
    consumer_pattern2 = graph_matcher.OpTypePattern(
117
118
        'StridedSlice',
        inputs=[reshape_2_pattern, '*', '*', '*'],
119
        ordered_inputs=False)
120

121
122
123
124
125
126
127
    def replace_matches(consumer_pattern):
      """Search for nearest neighbor pattern and replace with TF op."""
      match_counter = 0
      matcher = graph_matcher.GraphMatcher(consumer_pattern)
      for match in matcher.match_graph(tf.get_default_graph()):
        match_counter += 1
        projection_op = match.get_op(input_pattern)
128
        reshape_2_op = match.get_op(reshape_2_pattern)
129
130
131
        consumer_op = match.get_op(consumer_pattern)
        nn_resize = tf.image.resize_nearest_neighbor(
            projection_op.outputs[0],
132
            reshape_2_op.outputs[0].shape.dims[1:3],
133
            align_corners=False,
134
135
            name=os.path.split(reshape_2_op.name)[0] +
            '/resize_nearest_neighbor')
136
137

        for index, op_input in enumerate(consumer_op.inputs):
138
          if op_input == reshape_2_op.outputs[0]:
139
140
141
142
143
144
145
            consumer_op._update_input(index, nn_resize)  # pylint: disable=protected-access
            break

      return match_counter

    match_counter = replace_matches(consumer_pattern1)
    match_counter += replace_matches(consumer_pattern2)
146
147
148
149
150
151
152
153
154
155
156

    tf.logging.info('Found and fixed {} matches'.format(match_counter))
    return match_counter

  # Applying twice because both inputs to Add could be NN pattern
  total_removals = 0
  while remove_nn():
    total_removals += 1
    # This number is chosen based on the nas-fpn architecture.
    if total_removals > 4:
      raise ValueError('Graph removal encountered a infinite loop.')
157
158


Vivek Rathod's avatar
Vivek Rathod committed
159
160
def replace_variable_values_with_moving_averages(graph,
                                                 current_checkpoint_file,
161
162
                                                 new_checkpoint_file,
                                                 no_ema_collection=None):
Vivek Rathod's avatar
Vivek Rathod committed
163
  """Replaces variable values in the checkpoint with their moving averages.
164

Vivek Rathod's avatar
Vivek Rathod committed
165
166
167
168
169
170
171
172
173
  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.
174
175
    no_ema_collection: A list of namescope substrings to match the variables
      to eliminate EMA.
Vivek Rathod's avatar
Vivek Rathod committed
176
177
178
179
  """
  with graph.as_default():
    variable_averages = tf.train.ExponentialMovingAverage(0.0)
    ema_variables_to_restore = variable_averages.variables_to_restore()
180
    ema_variables_to_restore = config_util.remove_unnecessary_ema(
181
        ema_variables_to_restore, no_ema_collection)
Vivek Rathod's avatar
Vivek Rathod committed
182
183
184
185
186
187
188
189
190
191
192
193
194
    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
195
  return input_tensor, input_tensor
196

197

198
199
200
201
202
203
204
205
def _side_input_tensor_placeholder(side_input_shape, side_input_name,
                                   side_input_type):
  """Returns side input placeholder and side input tensor."""
  side_input_tensor = tf.placeholder(
      dtype=side_input_type, shape=side_input_shape, name=side_input_name)
  return side_input_tensor, side_input_tensor


206
def _tf_example_input_placeholder(input_shape=None):
Derek Chow's avatar
Derek Chow committed
207
208
  """Returns input that accepts a batch of strings with tf examples.

209
210
211
  Args:
    input_shape: the shape to resize the output decoded images to (optional).

Derek Chow's avatar
Derek Chow committed
212
  Returns:
Vivek Rathod's avatar
Vivek Rathod committed
213
    a tuple of input placeholder and the output decoded images.
Derek Chow's avatar
Derek Chow committed
214
  """
215
216
217
218
219
220
  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]
221
222
    if input_shape is not None:
      image_tensor = tf.image.resize(image_tensor, input_shape[1:3])
223
    return image_tensor
Derek Chow's avatar
Derek Chow committed
224
  return (batch_tf_example_placeholder,
225
226
227
228
229
230
          shape_utils.static_or_dynamic_map_fn(
              decode,
              elems=batch_tf_example_placeholder,
              dtype=tf.uint8,
              parallel_iterations=32,
              back_prop=False))
231
232


233
def _encoded_image_string_tensor_input_placeholder(input_shape=None):
Derek Chow's avatar
Derek Chow committed
234
235
  """Returns input that accepts a batch of PNG or JPEG strings.

236
237
238
  Args:
    input_shape: the shape to resize the output decoded images to (optional).

Derek Chow's avatar
Derek Chow committed
239
  Returns:
Vivek Rathod's avatar
Vivek Rathod committed
240
    a tuple of input placeholder and the output decoded images.
Derek Chow's avatar
Derek Chow committed
241
  """
242
243
244
245
246
247
248
249
  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))
250
251
    if input_shape is not None:
      image_tensor = tf.image.resize(image_tensor, input_shape[1:3])
252
    return image_tensor
Derek Chow's avatar
Derek Chow committed
253
254
255
256
257
258
259
  return (batch_image_str_placeholder,
          tf.map_fn(
              decode,
              elems=batch_image_str_placeholder,
              dtype=tf.uint8,
              parallel_iterations=32,
              back_prop=False))
260
261


262
input_placeholder_fn_map = {
263
264
265
    'image_tensor': _image_tensor_input_placeholder,
    'encoded_image_string_tensor':
    _encoded_image_string_tensor_input_placeholder,
266
    'tf_example': _tf_example_input_placeholder
267
268
269
}


270
271
def add_output_tensor_nodes(postprocessed_tensors,
                            output_collection_name='inference_op'):
272
273
274
275
276
277
278
279
  """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.
280
281
282
    * detection_multiclass_scores: (Optional) float32 tensor of shape
      [batch_size, num_boxes, num_classes_with_background] for containing class
      score distribution for detected boxes including background if any.
pkulzc's avatar
pkulzc committed
283
284
285
286
    * detection_features: (Optional) float32 tensor of shape
      [batch, num_boxes, roi_height, roi_width, depth]
      containing classifier features
      for each detected box
287
288
    * detection_classes: float32 tensor of shape [batch_size, num_boxes]
      containing class predictions for the detected boxes.
289
290
291
    * detection_keypoints: (Optional) float32 tensor of shape
      [batch_size, num_boxes, num_keypoints, 2] containing keypoints for each
      detection box.
292
293
294
    * detection_masks: (Optional) float32 tensor of shape
      [batch_size, num_boxes, mask_height, mask_width] containing masks for each
      detection box.
295
296
297
298
299

  Args:
    postprocessed_tensors: a dictionary containing the following fields
      'detection_boxes': [batch, max_detections, 4]
      'detection_scores': [batch, max_detections]
300
301
      'detection_multiclass_scores': [batch, max_detections,
        num_classes_with_background]
pkulzc's avatar
pkulzc committed
302
      'detection_features': [batch, num_boxes, roi_height, roi_width, depth]
303
      'detection_classes': [batch, max_detections]
304
305
      'detection_masks': [batch, max_detections, mask_height, mask_width]
        (optional).
306
307
      'detection_keypoints': [batch, max_detections, num_keypoints, 2]
        (optional).
308
      'num_detections': [batch]
309
    output_collection_name: Name of collection to add output tensors to.
310
311
312

  Returns:
    A tensor dict containing the added output tensor nodes.
313
  """
314
  detection_fields = fields.DetectionResultFields
315
  label_id_offset = 1
316
317
  boxes = postprocessed_tensors.get(detection_fields.detection_boxes)
  scores = postprocessed_tensors.get(detection_fields.detection_scores)
318
319
  multiclass_scores = postprocessed_tensors.get(
      detection_fields.detection_multiclass_scores)
pkulzc's avatar
pkulzc committed
320
321
  box_classifier_features = postprocessed_tensors.get(
      detection_fields.detection_features)
322
323
  raw_boxes = postprocessed_tensors.get(detection_fields.raw_detection_boxes)
  raw_scores = postprocessed_tensors.get(detection_fields.raw_detection_scores)
324
325
  classes = postprocessed_tensors.get(
      detection_fields.detection_classes) + label_id_offset
326
  keypoints = postprocessed_tensors.get(detection_fields.detection_keypoints)
327
328
  masks = postprocessed_tensors.get(detection_fields.detection_masks)
  num_detections = postprocessed_tensors.get(detection_fields.num_detections)
329
  outputs = {}
330
331
332
333
  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)
334
335
336
  if multiclass_scores is not None:
    outputs[detection_fields.detection_multiclass_scores] = tf.identity(
        multiclass_scores, name=detection_fields.detection_multiclass_scores)
pkulzc's avatar
pkulzc committed
337
338
339
340
  if box_classifier_features is not None:
    outputs[detection_fields.detection_features] = tf.identity(
        box_classifier_features,
        name=detection_fields.detection_features)
341
342
343
344
  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)
345
346
347
348
349
350
  if raw_boxes is not None:
    outputs[detection_fields.raw_detection_boxes] = tf.identity(
        raw_boxes, name=detection_fields.raw_detection_boxes)
  if raw_scores is not None:
    outputs[detection_fields.raw_detection_scores] = tf.identity(
        raw_scores, name=detection_fields.raw_detection_scores)
351
352
353
  if keypoints is not None:
    outputs[detection_fields.detection_keypoints] = tf.identity(
        keypoints, name=detection_fields.detection_keypoints)
354
  if masks is not None:
355
356
    outputs[detection_fields.detection_masks] = tf.identity(
        masks, name=detection_fields.detection_masks)
357
358
  for output_key in outputs:
    tf.add_to_collection(output_collection_name, outputs[output_key])
359

360
  return outputs
361
362


363
364
365
366
def write_saved_model(saved_model_path,
                      frozen_graph_def,
                      inputs,
                      outputs):
367
368
369
370
371
372
373
374
375
  """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:
376
377
    saved_model_path: Path to write SavedModel.
    frozen_graph_def: tf.GraphDef holding frozen graph.
378
    inputs: A tensor dictionary containing the inputs to a DetectionModel.
379
380
381
    outputs: A tensor dictionary containing the outputs of a DetectionModel.
  """
  with tf.Graph().as_default():
382
    with tf.Session() as sess:
383

384
      tf.import_graph_def(frozen_graph_def, name='')
385

386
      builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
387

388
389
390
391
392
393
394
      tensor_info_inputs = {}
      if isinstance(inputs, dict):
        for k, v in inputs.items():
          tensor_info_inputs[k] = tf.saved_model.utils.build_tensor_info(v)
      else:
        tensor_info_inputs['inputs'] = tf.saved_model.utils.build_tensor_info(
            inputs)
395
396
397
398
399
400
401
402
      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,
403
404
              method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
          ))
405
406

      builder.add_meta_graph_and_variables(
407
408
          sess,
          [tf.saved_model.tag_constants.SERVING],
409
          signature_def_map={
410
411
              tf.saved_model.signature_constants
              .DEFAULT_SERVING_SIGNATURE_DEF_KEY:
412
413
414
415
416
417
                  detection_signature,
          },
      )
      builder.save()


418
419
420
421
422
def write_graph_and_checkpoint(inference_graph_def,
                               model_path,
                               input_saver_def,
                               trained_checkpoint_prefix):
  """Writes the graph and the checkpoint into disk."""
423
424
425
426
  for node in inference_graph_def.node:
    node.device = ''
  with tf.Graph().as_default():
    tf.import_graph_def(inference_graph_def, name='')
427
428
429
    with tf.Session() as sess:
      saver = tf.train.Saver(
          saver_def=input_saver_def, save_relative_paths=True)
430
431
432
433
      saver.restore(sess, trained_checkpoint_prefix)
      saver.save(sess, model_path)


434
def _get_outputs_from_inputs(input_tensors, detection_model,
435
                             output_collection_name, **side_inputs):
436
  inputs = tf.cast(input_tensors, dtype=tf.float32)
437
438
  preprocessed_inputs, true_image_shapes = detection_model.preprocess(inputs)
  output_tensors = detection_model.predict(
439
      preprocessed_inputs, true_image_shapes, **side_inputs)
440
441
  postprocessed_tensors = detection_model.postprocess(
      output_tensors, true_image_shapes)
442
443
  return add_output_tensor_nodes(postprocessed_tensors,
                                 output_collection_name)
444
445


446
def build_detection_graph(input_type, detection_model, input_shape,
447
448
449
                          output_collection_name, graph_hook_fn,
                          use_side_inputs=False, side_input_shapes=None,
                          side_input_names=None, side_input_types=None):
450
451
452
453
  """Build the detection graph."""
  if input_type not in input_placeholder_fn_map:
    raise ValueError('Unknown input type: {}'.format(input_type))
  placeholder_args = {}
454
  side_inputs = {}
455
  if input_shape is not None:
456
457
    if (input_type != 'image_tensor' and
        input_type != 'encoded_image_string_tensor' and
458
459
        input_type != 'tf_example' and
        input_type != 'tf_sequence_example'):
460
      raise ValueError('Can only specify input shape for `image_tensor`, '
461
462
                       '`encoded_image_string_tensor`, `tf_example`, '
                       ' or `tf_sequence_example` inputs.')
463
464
465
    placeholder_args['input_shape'] = input_shape
  placeholder_tensor, input_tensors = input_placeholder_fn_map[input_type](
      **placeholder_args)
466
467
468
469
470
471
472
473
  placeholder_tensors = {'inputs': placeholder_tensor}
  if use_side_inputs:
    for idx, side_input_name in enumerate(side_input_names):
      side_input_placeholder, side_input = _side_input_tensor_placeholder(
          side_input_shapes[idx], side_input_name, side_input_types[idx])
      print(side_input)
      side_inputs[side_input_name] = side_input
      placeholder_tensors[side_input_name] = side_input_placeholder
474
475
476
  outputs = _get_outputs_from_inputs(
      input_tensors=input_tensors,
      detection_model=detection_model,
477
478
      output_collection_name=output_collection_name,
      **side_inputs)
479
480
481
482
483
484

  # Add global step to the graph.
  slim.get_or_create_global_step()

  if graph_hook_fn: graph_hook_fn()

485
  return outputs, placeholder_tensors
486
487


488
489
490
def _export_inference_graph(input_type,
                            detection_model,
                            use_moving_averages,
491
492
                            trained_checkpoint_prefix,
                            output_directory,
Vivek Rathod's avatar
Vivek Rathod committed
493
494
                            additional_output_tensor_names=None,
                            input_shape=None,
495
                            output_collection_name='inference_op',
496
                            graph_hook_fn=None,
497
                            write_inference_graph=False,
498
499
500
501
502
                            temp_checkpoint_prefix='',
                            use_side_inputs=False,
                            side_input_shapes=None,
                            side_input_names=None,
                            side_input_types=None):
503
  """Export helper."""
504
505
506
507
508
509
  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')

510
  outputs, placeholder_tensor_dict = build_detection_graph(
511
512
513
514
      input_type=input_type,
      detection_model=detection_model,
      input_shape=input_shape,
      output_collection_name=output_collection_name,
515
516
517
518
519
      graph_hook_fn=graph_hook_fn,
      use_side_inputs=use_side_inputs,
      side_input_shapes=side_input_shapes,
      side_input_names=side_input_names,
      side_input_types=side_input_types)
520

521
  profile_inference_graph(tf.get_default_graph())
522
  saver_kwargs = {}
523
  if use_moving_averages:
524
525
526
527
528
529
530
    if not temp_checkpoint_prefix:
      # This check is to be compatible with both version of SaverDef.
      if os.path.isfile(trained_checkpoint_prefix):
        saver_kwargs['write_version'] = saver_pb2.SaverDef.V1
        temp_checkpoint_prefix = tempfile.NamedTemporaryFile().name
      else:
        temp_checkpoint_prefix = tempfile.mkdtemp()
Vivek Rathod's avatar
Vivek Rathod committed
531
532
    replace_variable_values_with_moving_averages(
        tf.get_default_graph(), trained_checkpoint_prefix,
533
534
        temp_checkpoint_prefix)
    checkpoint_to_use = temp_checkpoint_prefix
535
  else:
Vivek Rathod's avatar
Vivek Rathod committed
536
537
    checkpoint_to_use = trained_checkpoint_prefix

538
  saver = tf.train.Saver(**saver_kwargs)
539
540
  input_saver_def = saver.as_saver_def()

541
  write_graph_and_checkpoint(
542
543
544
      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
545
      trained_checkpoint_prefix=checkpoint_to_use)
546
547
548
549
550
551
  if write_inference_graph:
    inference_graph_def = tf.get_default_graph().as_graph_def()
    inference_graph_path = os.path.join(output_directory,
                                        'inference_graph.pbtxt')
    for node in inference_graph_def.node:
      node.device = ''
552
    with tf.gfile.GFile(inference_graph_path, 'wb') as f:
553
      f.write(str(inference_graph_def))
Vivek Rathod's avatar
Vivek Rathod committed
554
555

  if additional_output_tensor_names is not None:
556
557
    output_node_names = ','.join(list(outputs.keys())+(
        additional_output_tensor_names))
Vivek Rathod's avatar
Vivek Rathod committed
558
559
  else:
    output_node_names = ','.join(outputs.keys())
560

561
  frozen_graph_def = freeze_graph.freeze_graph_with_def_protos(
562
563
      input_graph_def=tf.get_default_graph().as_graph_def(),
      input_saver_def=input_saver_def,
Vivek Rathod's avatar
Vivek Rathod committed
564
565
      input_checkpoint=checkpoint_to_use,
      output_node_names=output_node_names,
566
567
      restore_op_name='save/restore_all',
      filename_tensor_name='save/Const:0',
568
      output_graph=frozen_graph_path,
569
570
      clear_devices=True,
      initializer_nodes='')
571

572
  write_saved_model(saved_model_path, frozen_graph_def,
573
                    placeholder_tensor_dict, outputs)
574
575


576
577
578
579
def export_inference_graph(input_type,
                           pipeline_config,
                           trained_checkpoint_prefix,
                           output_directory,
Vivek Rathod's avatar
Vivek Rathod committed
580
581
                           input_shape=None,
                           output_collection_name='inference_op',
582
                           additional_output_tensor_names=None,
583
584
585
586
587
                           write_inference_graph=False,
                           use_side_inputs=False,
                           side_input_shapes=None,
                           side_input_names=None,
                           side_input_types=None):
588
589
590
  """Exports inference graph for the model specified in the pipeline config.

  Args:
591
592
    input_type: Type of input for the graph. Can be one of ['image_tensor',
      'encoded_image_string_tensor', 'tf_example'].
593
    pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.
594
595
    trained_checkpoint_prefix: Path to the trained checkpoint file.
    output_directory: Path to write outputs.
Vivek Rathod's avatar
Vivek Rathod committed
596
597
    input_shape: Sets a fixed shape for an `image_tensor` input. If not
      specified, will default to [None, None, None, 3].
598
599
    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
600
    additional_output_tensor_names: list of additional output
601
      tensors to include in the frozen graph.
602
    write_inference_graph: If true, writes inference graph to disk.
603
604
605
606
607
608
609
    use_side_inputs: If True, the model requires side_inputs.
    side_input_shapes: List of shapes of the side input tensors,
      required if use_side_inputs is True.
    side_input_names: List of names of the side input tensors,
      required if use_side_inputs is True.
    side_input_types: List of types of the side input tensors,
      required if use_side_inputs is True.
610
611
612
  """
  detection_model = model_builder.build(pipeline_config.model,
                                        is_training=False)
613
614
615
616
617
  graph_rewriter_fn = None
  if pipeline_config.HasField('graph_rewriter'):
    graph_rewriter_config = pipeline_config.graph_rewriter
    graph_rewriter_fn = graph_rewriter_builder.build(graph_rewriter_config,
                                                     is_training=False)
618
619
620
621
622
623
624
625
626
  _export_inference_graph(
      input_type,
      detection_model,
      pipeline_config.eval_config.use_moving_averages,
      trained_checkpoint_prefix,
      output_directory,
      additional_output_tensor_names,
      input_shape,
      output_collection_name,
627
      graph_hook_fn=graph_rewriter_fn,
628
629
630
631
632
      write_inference_graph=write_inference_graph,
      use_side_inputs=use_side_inputs,
      side_input_shapes=side_input_shapes,
      side_input_names=side_input_names,
      side_input_types=side_input_types)
633
  pipeline_config.eval_config.use_moving_averages = False
634
  config_util.save_pipeline_config(pipeline_config, output_directory)
635
636
637
638
639
640
641
642
643
644
645
646
647
648


def profile_inference_graph(graph):
  """Profiles the inference graph.

  Prints model parameters and computation FLOPs given an inference graph.
  BatchNorms are excluded from the parameter count due to the fact that
  BatchNorms are usually folded. BatchNorm, Initializer, Regularizer
  and BiasAdd are not considered in FLOP count.

  Args:
    graph: the inference graph.
  """
  tfprof_vars_option = (
649
650
      contrib_tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
  tfprof_flops_option = contrib_tfprof.model_analyzer.FLOAT_OPS_OPTIONS
651
652
653
654
655
656
657
658

  # Batchnorm is usually folded during inference.
  tfprof_vars_option['trim_name_regexes'] = ['.*BatchNorm.*']
  # Initializer and Regularizer are only used in training.
  tfprof_flops_option['trim_name_regexes'] = [
      '.*BatchNorm.*', '.*Initializer.*', '.*Regularizer.*', '.*BiasAdd.*'
  ]

659
660
  contrib_tfprof.model_analyzer.print_model_analysis(
      graph, tfprof_options=tfprof_vars_option)
661

662
663
  contrib_tfprof.model_analyzer.print_model_analysis(
      graph, tfprof_options=tfprof_flops_option)