You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

498 lines
20 KiB

6 years ago
  1. # Copyright 2017 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. """Functions to export object detection inference graph."""
  16. import os
  17. import tempfile
  18. import tensorflow as tf
  19. from tensorflow.contrib.quantize.python import graph_matcher
  20. from tensorflow.core.protobuf import saver_pb2
  21. from tensorflow.python.tools import freeze_graph # pylint: disable=g-direct-tensorflow-import
  22. from object_detection.builders import graph_rewriter_builder
  23. from object_detection.builders import model_builder
  24. from object_detection.core import standard_fields as fields
  25. from object_detection.data_decoders import tf_example_decoder
  26. from object_detection.utils import config_util
  27. from object_detection.utils import shape_utils
  28. slim = tf.contrib.slim
  29. freeze_graph_with_def_protos = freeze_graph.freeze_graph_with_def_protos
  30. def rewrite_nn_resize_op(is_quantized=False):
  31. """Replaces a custom nearest-neighbor resize op with the Tensorflow version.
  32. Some graphs use this custom version for TPU-compatibility.
  33. Args:
  34. is_quantized: True if the default graph is quantized.
  35. """
  36. input_pattern = graph_matcher.OpTypePattern(
  37. 'FakeQuantWithMinMaxVars' if is_quantized else '*')
  38. reshape_1_pattern = graph_matcher.OpTypePattern(
  39. 'Reshape', inputs=[input_pattern, 'Const'], ordered_inputs=False)
  40. mul_pattern = graph_matcher.OpTypePattern(
  41. 'Mul', inputs=[reshape_1_pattern, 'Const'], ordered_inputs=False)
  42. # The quantization script may or may not insert a fake quant op after the
  43. # Mul. In either case, these min/max vars are not needed once replaced with
  44. # the TF version of NN resize.
  45. fake_quant_pattern = graph_matcher.OpTypePattern(
  46. 'FakeQuantWithMinMaxVars',
  47. inputs=[mul_pattern, 'Identity', 'Identity'],
  48. ordered_inputs=False)
  49. reshape_2_pattern = graph_matcher.OpTypePattern(
  50. 'Reshape',
  51. inputs=[graph_matcher.OneofPattern([fake_quant_pattern, mul_pattern]),
  52. 'Const'],
  53. ordered_inputs=False)
  54. add_pattern = graph_matcher.OpTypePattern(
  55. 'Add', inputs=[reshape_2_pattern, '*'], ordered_inputs=False)
  56. matcher = graph_matcher.GraphMatcher(add_pattern)
  57. for match in matcher.match_graph(tf.get_default_graph()):
  58. projection_op = match.get_op(input_pattern)
  59. reshape_2_op = match.get_op(reshape_2_pattern)
  60. add_op = match.get_op(add_pattern)
  61. nn_resize = tf.image.resize_nearest_neighbor(
  62. projection_op.outputs[0],
  63. add_op.outputs[0].shape.dims[1:3],
  64. align_corners=False,
  65. name=os.path.split(reshape_2_op.name)[0] + '/resize_nearest_neighbor')
  66. for index, op_input in enumerate(add_op.inputs):
  67. if op_input == reshape_2_op.outputs[0]:
  68. add_op._update_input(index, nn_resize) # pylint: disable=protected-access
  69. break
  70. def replace_variable_values_with_moving_averages(graph,
  71. current_checkpoint_file,
  72. new_checkpoint_file):
  73. """Replaces variable values in the checkpoint with their moving averages.
  74. If the current checkpoint has shadow variables maintaining moving averages of
  75. the variables defined in the graph, this function generates a new checkpoint
  76. where the variables contain the values of their moving averages.
  77. Args:
  78. graph: a tf.Graph object.
  79. current_checkpoint_file: a checkpoint containing both original variables and
  80. their moving averages.
  81. new_checkpoint_file: file path to write a new checkpoint.
  82. """
  83. with graph.as_default():
  84. variable_averages = tf.train.ExponentialMovingAverage(0.0)
  85. ema_variables_to_restore = variable_averages.variables_to_restore()
  86. with tf.Session() as sess:
  87. read_saver = tf.train.Saver(ema_variables_to_restore)
  88. read_saver.restore(sess, current_checkpoint_file)
  89. write_saver = tf.train.Saver()
  90. write_saver.save(sess, new_checkpoint_file)
  91. def _image_tensor_input_placeholder(input_shape=None):
  92. """Returns input placeholder and a 4-D uint8 image tensor."""
  93. if input_shape is None:
  94. input_shape = (None, None, None, 3)
  95. input_tensor = tf.placeholder(
  96. dtype=tf.uint8, shape=input_shape, name='image_tensor')
  97. return input_tensor, input_tensor
  98. def _tf_example_input_placeholder():
  99. """Returns input that accepts a batch of strings with tf examples.
  100. Returns:
  101. a tuple of input placeholder and the output decoded images.
  102. """
  103. batch_tf_example_placeholder = tf.placeholder(
  104. tf.string, shape=[None], name='tf_example')
  105. def decode(tf_example_string_tensor):
  106. tensor_dict = tf_example_decoder.TfExampleDecoder().decode(
  107. tf_example_string_tensor)
  108. image_tensor = tensor_dict[fields.InputDataFields.image]
  109. return image_tensor
  110. return (batch_tf_example_placeholder,
  111. shape_utils.static_or_dynamic_map_fn(
  112. decode,
  113. elems=batch_tf_example_placeholder,
  114. dtype=tf.uint8,
  115. parallel_iterations=32,
  116. back_prop=False))
  117. def _encoded_image_string_tensor_input_placeholder():
  118. """Returns input that accepts a batch of PNG or JPEG strings.
  119. Returns:
  120. a tuple of input placeholder and the output decoded images.
  121. """
  122. batch_image_str_placeholder = tf.placeholder(
  123. dtype=tf.string,
  124. shape=[None],
  125. name='encoded_image_string_tensor')
  126. def decode(encoded_image_string_tensor):
  127. image_tensor = tf.image.decode_image(encoded_image_string_tensor,
  128. channels=3)
  129. image_tensor.set_shape((None, None, 3))
  130. return image_tensor
  131. return (batch_image_str_placeholder,
  132. tf.map_fn(
  133. decode,
  134. elems=batch_image_str_placeholder,
  135. dtype=tf.uint8,
  136. parallel_iterations=32,
  137. back_prop=False))
  138. input_placeholder_fn_map = {
  139. 'image_tensor': _image_tensor_input_placeholder,
  140. 'encoded_image_string_tensor':
  141. _encoded_image_string_tensor_input_placeholder,
  142. 'tf_example': _tf_example_input_placeholder,
  143. }
  144. def add_output_tensor_nodes(postprocessed_tensors,
  145. output_collection_name='inference_op'):
  146. """Adds output nodes for detection boxes and scores.
  147. Adds the following nodes for output tensors -
  148. * num_detections: float32 tensor of shape [batch_size].
  149. * detection_boxes: float32 tensor of shape [batch_size, num_boxes, 4]
  150. containing detected boxes.
  151. * detection_scores: float32 tensor of shape [batch_size, num_boxes]
  152. containing scores for the detected boxes.
  153. * detection_classes: float32 tensor of shape [batch_size, num_boxes]
  154. containing class predictions for the detected boxes.
  155. * detection_keypoints: (Optional) float32 tensor of shape
  156. [batch_size, num_boxes, num_keypoints, 2] containing keypoints for each
  157. detection box.
  158. * detection_masks: (Optional) float32 tensor of shape
  159. [batch_size, num_boxes, mask_height, mask_width] containing masks for each
  160. detection box.
  161. Args:
  162. postprocessed_tensors: a dictionary containing the following fields
  163. 'detection_boxes': [batch, max_detections, 4]
  164. 'detection_scores': [batch, max_detections]
  165. 'detection_classes': [batch, max_detections]
  166. 'detection_masks': [batch, max_detections, mask_height, mask_width]
  167. (optional).
  168. 'detection_keypoints': [batch, max_detections, num_keypoints, 2]
  169. (optional).
  170. 'num_detections': [batch]
  171. output_collection_name: Name of collection to add output tensors to.
  172. Returns:
  173. A tensor dict containing the added output tensor nodes.
  174. """
  175. detection_fields = fields.DetectionResultFields
  176. label_id_offset = 1
  177. boxes = postprocessed_tensors.get(detection_fields.detection_boxes)
  178. scores = postprocessed_tensors.get(detection_fields.detection_scores)
  179. raw_boxes = postprocessed_tensors.get(detection_fields.raw_detection_boxes)
  180. raw_scores = postprocessed_tensors.get(detection_fields.raw_detection_scores)
  181. classes = postprocessed_tensors.get(
  182. detection_fields.detection_classes) + label_id_offset
  183. keypoints = postprocessed_tensors.get(detection_fields.detection_keypoints)
  184. masks = postprocessed_tensors.get(detection_fields.detection_masks)
  185. num_detections = postprocessed_tensors.get(detection_fields.num_detections)
  186. outputs = {}
  187. outputs[detection_fields.detection_boxes] = tf.identity(
  188. boxes, name=detection_fields.detection_boxes)
  189. outputs[detection_fields.detection_scores] = tf.identity(
  190. scores, name=detection_fields.detection_scores)
  191. outputs[detection_fields.detection_classes] = tf.identity(
  192. classes, name=detection_fields.detection_classes)
  193. outputs[detection_fields.num_detections] = tf.identity(
  194. num_detections, name=detection_fields.num_detections)
  195. if raw_boxes is not None:
  196. outputs[detection_fields.raw_detection_boxes] = tf.identity(
  197. raw_boxes, name=detection_fields.raw_detection_boxes)
  198. if raw_scores is not None:
  199. outputs[detection_fields.raw_detection_scores] = tf.identity(
  200. raw_scores, name=detection_fields.raw_detection_scores)
  201. if keypoints is not None:
  202. outputs[detection_fields.detection_keypoints] = tf.identity(
  203. keypoints, name=detection_fields.detection_keypoints)
  204. if masks is not None:
  205. outputs[detection_fields.detection_masks] = tf.identity(
  206. masks, name=detection_fields.detection_masks)
  207. for output_key in outputs:
  208. tf.add_to_collection(output_collection_name, outputs[output_key])
  209. return outputs
  210. def write_saved_model(saved_model_path,
  211. frozen_graph_def,
  212. inputs,
  213. outputs):
  214. """Writes SavedModel to disk.
  215. If checkpoint_path is not None bakes the weights into the graph thereby
  216. eliminating the need of checkpoint files during inference. If the model
  217. was trained with moving averages, setting use_moving_averages to true
  218. restores the moving averages, otherwise the original set of variables
  219. is restored.
  220. Args:
  221. saved_model_path: Path to write SavedModel.
  222. frozen_graph_def: tf.GraphDef holding frozen graph.
  223. inputs: The input placeholder tensor.
  224. outputs: A tensor dictionary containing the outputs of a DetectionModel.
  225. """
  226. with tf.Graph().as_default():
  227. with tf.Session() as sess:
  228. tf.import_graph_def(frozen_graph_def, name='')
  229. builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
  230. tensor_info_inputs = {
  231. 'inputs': tf.saved_model.utils.build_tensor_info(inputs)}
  232. tensor_info_outputs = {}
  233. for k, v in outputs.items():
  234. tensor_info_outputs[k] = tf.saved_model.utils.build_tensor_info(v)
  235. detection_signature = (
  236. tf.saved_model.signature_def_utils.build_signature_def(
  237. inputs=tensor_info_inputs,
  238. outputs=tensor_info_outputs,
  239. method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
  240. ))
  241. builder.add_meta_graph_and_variables(
  242. sess,
  243. [tf.saved_model.tag_constants.SERVING],
  244. signature_def_map={
  245. tf.saved_model.signature_constants
  246. .DEFAULT_SERVING_SIGNATURE_DEF_KEY:
  247. detection_signature,
  248. },
  249. )
  250. builder.save()
  251. def write_graph_and_checkpoint(inference_graph_def,
  252. model_path,
  253. input_saver_def,
  254. trained_checkpoint_prefix):
  255. """Writes the graph and the checkpoint into disk."""
  256. for node in inference_graph_def.node:
  257. node.device = ''
  258. with tf.Graph().as_default():
  259. tf.import_graph_def(inference_graph_def, name='')
  260. with tf.Session() as sess:
  261. saver = tf.train.Saver(
  262. saver_def=input_saver_def, save_relative_paths=True)
  263. saver.restore(sess, trained_checkpoint_prefix)
  264. saver.save(sess, model_path)
  265. def _get_outputs_from_inputs(input_tensors, detection_model,
  266. output_collection_name):
  267. inputs = tf.to_float(input_tensors)
  268. preprocessed_inputs, true_image_shapes = detection_model.preprocess(inputs)
  269. output_tensors = detection_model.predict(
  270. preprocessed_inputs, true_image_shapes)
  271. postprocessed_tensors = detection_model.postprocess(
  272. output_tensors, true_image_shapes)
  273. return add_output_tensor_nodes(postprocessed_tensors,
  274. output_collection_name)
  275. def build_detection_graph(input_type, detection_model, input_shape,
  276. output_collection_name, graph_hook_fn):
  277. """Build the detection graph."""
  278. if input_type not in input_placeholder_fn_map:
  279. raise ValueError('Unknown input type: {}'.format(input_type))
  280. placeholder_args = {}
  281. if input_shape is not None:
  282. if input_type != 'image_tensor':
  283. raise ValueError('Can only specify input shape for `image_tensor` '
  284. 'inputs.')
  285. placeholder_args['input_shape'] = input_shape
  286. placeholder_tensor, input_tensors = input_placeholder_fn_map[input_type](
  287. **placeholder_args)
  288. outputs = _get_outputs_from_inputs(
  289. input_tensors=input_tensors,
  290. detection_model=detection_model,
  291. output_collection_name=output_collection_name)
  292. # Add global step to the graph.
  293. slim.get_or_create_global_step()
  294. if graph_hook_fn: graph_hook_fn()
  295. return outputs, placeholder_tensor
  296. def _export_inference_graph(input_type,
  297. detection_model,
  298. use_moving_averages,
  299. trained_checkpoint_prefix,
  300. output_directory,
  301. additional_output_tensor_names=None,
  302. input_shape=None,
  303. output_collection_name='inference_op',
  304. graph_hook_fn=None,
  305. write_inference_graph=False,
  306. temp_checkpoint_prefix=''):
  307. """Export helper."""
  308. tf.gfile.MakeDirs(output_directory)
  309. frozen_graph_path = os.path.join(output_directory,
  310. 'frozen_inference_graph.pb')
  311. saved_model_path = os.path.join(output_directory, 'saved_model')
  312. model_path = os.path.join(output_directory, 'model.ckpt')
  313. outputs, placeholder_tensor = build_detection_graph(
  314. input_type=input_type,
  315. detection_model=detection_model,
  316. input_shape=input_shape,
  317. output_collection_name=output_collection_name,
  318. graph_hook_fn=graph_hook_fn)
  319. profile_inference_graph(tf.get_default_graph())
  320. saver_kwargs = {}
  321. if use_moving_averages:
  322. if not temp_checkpoint_prefix:
  323. # This check is to be compatible with both version of SaverDef.
  324. if os.path.isfile(trained_checkpoint_prefix):
  325. saver_kwargs['write_version'] = saver_pb2.SaverDef.V1
  326. temp_checkpoint_prefix = tempfile.NamedTemporaryFile().name
  327. else:
  328. temp_checkpoint_prefix = tempfile.mkdtemp()
  329. replace_variable_values_with_moving_averages(
  330. tf.get_default_graph(), trained_checkpoint_prefix,
  331. temp_checkpoint_prefix)
  332. checkpoint_to_use = temp_checkpoint_prefix
  333. else:
  334. checkpoint_to_use = trained_checkpoint_prefix
  335. saver = tf.train.Saver(**saver_kwargs)
  336. input_saver_def = saver.as_saver_def()
  337. write_graph_and_checkpoint(
  338. inference_graph_def=tf.get_default_graph().as_graph_def(),
  339. model_path=model_path,
  340. input_saver_def=input_saver_def,
  341. trained_checkpoint_prefix=checkpoint_to_use)
  342. if write_inference_graph:
  343. inference_graph_def = tf.get_default_graph().as_graph_def()
  344. inference_graph_path = os.path.join(output_directory,
  345. 'inference_graph.pbtxt')
  346. for node in inference_graph_def.node:
  347. node.device = ''
  348. with tf.gfile.GFile(inference_graph_path, 'wb') as f:
  349. f.write(str(inference_graph_def))
  350. if additional_output_tensor_names is not None:
  351. output_node_names = ','.join(outputs.keys()+additional_output_tensor_names)
  352. else:
  353. output_node_names = ','.join(outputs.keys())
  354. frozen_graph_def = freeze_graph.freeze_graph_with_def_protos(
  355. input_graph_def=tf.get_default_graph().as_graph_def(),
  356. input_saver_def=input_saver_def,
  357. input_checkpoint=checkpoint_to_use,
  358. output_node_names=output_node_names,
  359. restore_op_name='save/restore_all',
  360. filename_tensor_name='save/Const:0',
  361. output_graph=frozen_graph_path,
  362. clear_devices=True,
  363. initializer_nodes='')
  364. write_saved_model(saved_model_path, frozen_graph_def,
  365. placeholder_tensor, outputs)
  366. def export_inference_graph(input_type,
  367. pipeline_config,
  368. trained_checkpoint_prefix,
  369. output_directory,
  370. input_shape=None,
  371. output_collection_name='inference_op',
  372. additional_output_tensor_names=None,
  373. write_inference_graph=False):
  374. """Exports inference graph for the model specified in the pipeline config.
  375. Args:
  376. input_type: Type of input for the graph. Can be one of ['image_tensor',
  377. 'encoded_image_string_tensor', 'tf_example'].
  378. pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.
  379. trained_checkpoint_prefix: Path to the trained checkpoint file.
  380. output_directory: Path to write outputs.
  381. input_shape: Sets a fixed shape for an `image_tensor` input. If not
  382. specified, will default to [None, None, None, 3].
  383. output_collection_name: Name of collection to add output tensors to.
  384. If None, does not add output tensors to a collection.
  385. additional_output_tensor_names: list of additional output
  386. tensors to include in the frozen graph.
  387. write_inference_graph: If true, writes inference graph to disk.
  388. """
  389. detection_model = model_builder.build(pipeline_config.model,
  390. is_training=False)
  391. graph_rewriter_fn = None
  392. if pipeline_config.HasField('graph_rewriter'):
  393. graph_rewriter_config = pipeline_config.graph_rewriter
  394. graph_rewriter_fn = graph_rewriter_builder.build(graph_rewriter_config,
  395. is_training=False)
  396. _export_inference_graph(
  397. input_type,
  398. detection_model,
  399. pipeline_config.eval_config.use_moving_averages,
  400. trained_checkpoint_prefix,
  401. output_directory,
  402. additional_output_tensor_names,
  403. input_shape,
  404. output_collection_name,
  405. graph_hook_fn=graph_rewriter_fn,
  406. write_inference_graph=write_inference_graph)
  407. pipeline_config.eval_config.use_moving_averages = False
  408. config_util.save_pipeline_config(pipeline_config, output_directory)
  409. def profile_inference_graph(graph):
  410. """Profiles the inference graph.
  411. Prints model parameters and computation FLOPs given an inference graph.
  412. BatchNorms are excluded from the parameter count due to the fact that
  413. BatchNorms are usually folded. BatchNorm, Initializer, Regularizer
  414. and BiasAdd are not considered in FLOP count.
  415. Args:
  416. graph: the inference graph.
  417. """
  418. tfprof_vars_option = (
  419. tf.contrib.tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
  420. tfprof_flops_option = tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS
  421. # Batchnorm is usually folded during inference.
  422. tfprof_vars_option['trim_name_regexes'] = ['.*BatchNorm.*']
  423. # Initializer and Regularizer are only used in training.
  424. tfprof_flops_option['trim_name_regexes'] = [
  425. '.*BatchNorm.*', '.*Initializer.*', '.*Regularizer.*', '.*BiasAdd.*'
  426. ]
  427. tf.contrib.tfprof.model_analyzer.print_model_analysis(
  428. graph,
  429. tfprof_options=tfprof_vars_option)
  430. tf.contrib.tfprof.model_analyzer.print_model_analysis(
  431. graph,
  432. tfprof_options=tfprof_flops_option)