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.

1016 lines
49 KiB

  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. """Tests for object_detection.export_inference_graph."""
  16. import os
  17. import numpy as np
  18. import six
  19. import tensorflow as tf
  20. from google.protobuf import text_format
  21. from tensorflow.python.framework import dtypes
  22. from tensorflow.python.ops import array_ops
  23. from object_detection import exporter
  24. from object_detection.builders import graph_rewriter_builder
  25. from object_detection.builders import model_builder
  26. from object_detection.core import model
  27. from object_detection.protos import graph_rewriter_pb2
  28. from object_detection.protos import pipeline_pb2
  29. from object_detection.utils import ops
  30. if six.PY2:
  31. import mock # pylint: disable=g-import-not-at-top
  32. else:
  33. from unittest import mock # pylint: disable=g-import-not-at-top
  34. slim = tf.contrib.slim
  35. class FakeModel(model.DetectionModel):
  36. def __init__(self, add_detection_keypoints=False, add_detection_masks=False):
  37. self._add_detection_keypoints = add_detection_keypoints
  38. self._add_detection_masks = add_detection_masks
  39. def preprocess(self, inputs):
  40. true_image_shapes = [] # Doesn't matter for the fake model.
  41. return tf.identity(inputs), true_image_shapes
  42. def predict(self, preprocessed_inputs, true_image_shapes):
  43. return {'image': tf.layers.conv2d(preprocessed_inputs, 3, 1)}
  44. def postprocess(self, prediction_dict, true_image_shapes):
  45. with tf.control_dependencies(prediction_dict.values()):
  46. postprocessed_tensors = {
  47. 'detection_boxes': tf.constant([[[0.0, 0.0, 0.5, 0.5],
  48. [0.5, 0.5, 0.8, 0.8]],
  49. [[0.5, 0.5, 1.0, 1.0],
  50. [0.0, 0.0, 0.0, 0.0]]], tf.float32),
  51. 'detection_scores': tf.constant([[0.7, 0.6],
  52. [0.9, 0.0]], tf.float32),
  53. 'detection_multiclass_scores': tf.constant([[[0.3, 0.7], [0.4, 0.6]],
  54. [[0.1, 0.9], [0.0, 0.0]]],
  55. tf.float32),
  56. 'detection_classes': tf.constant([[0, 1],
  57. [1, 0]], tf.float32),
  58. 'num_detections': tf.constant([2, 1], tf.float32),
  59. 'raw_detection_boxes': tf.constant([[[0.0, 0.0, 0.5, 0.5],
  60. [0.5, 0.5, 0.8, 0.8]],
  61. [[0.5, 0.5, 1.0, 1.0],
  62. [0.0, 0.5, 0.0, 0.5]]],
  63. tf.float32),
  64. 'raw_detection_scores': tf.constant([[0.7, 0.6],
  65. [0.9, 0.5]], tf.float32),
  66. }
  67. if self._add_detection_keypoints:
  68. postprocessed_tensors['detection_keypoints'] = tf.constant(
  69. np.arange(48).reshape([2, 2, 6, 2]), tf.float32)
  70. if self._add_detection_masks:
  71. postprocessed_tensors['detection_masks'] = tf.constant(
  72. np.arange(64).reshape([2, 2, 4, 4]), tf.float32)
  73. return postprocessed_tensors
  74. def restore_map(self, checkpoint_path, fine_tune_checkpoint_type):
  75. pass
  76. def loss(self, prediction_dict, true_image_shapes):
  77. pass
  78. def regularization_losses(self):
  79. pass
  80. def updates(self):
  81. pass
  82. class ExportInferenceGraphTest(tf.test.TestCase):
  83. def _save_checkpoint_from_mock_model(self,
  84. checkpoint_path,
  85. use_moving_averages,
  86. enable_quantization=False):
  87. g = tf.Graph()
  88. with g.as_default():
  89. mock_model = FakeModel()
  90. preprocessed_inputs, true_image_shapes = mock_model.preprocess(
  91. tf.placeholder(tf.float32, shape=[None, None, None, 3]))
  92. predictions = mock_model.predict(preprocessed_inputs, true_image_shapes)
  93. mock_model.postprocess(predictions, true_image_shapes)
  94. if use_moving_averages:
  95. tf.train.ExponentialMovingAverage(0.0).apply()
  96. tf.train.get_or_create_global_step()
  97. if enable_quantization:
  98. graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
  99. graph_rewriter_config.quantization.delay = 500000
  100. graph_rewriter_fn = graph_rewriter_builder.build(
  101. graph_rewriter_config, is_training=False)
  102. graph_rewriter_fn()
  103. saver = tf.train.Saver()
  104. init = tf.global_variables_initializer()
  105. with self.test_session() as sess:
  106. sess.run(init)
  107. saver.save(sess, checkpoint_path)
  108. def _load_inference_graph(self, inference_graph_path, is_binary=True):
  109. od_graph = tf.Graph()
  110. with od_graph.as_default():
  111. od_graph_def = tf.GraphDef()
  112. with tf.gfile.GFile(inference_graph_path) as fid:
  113. if is_binary:
  114. od_graph_def.ParseFromString(fid.read())
  115. else:
  116. text_format.Parse(fid.read(), od_graph_def)
  117. tf.import_graph_def(od_graph_def, name='')
  118. return od_graph
  119. def _create_tf_example(self, image_array):
  120. with self.test_session():
  121. encoded_image = tf.image.encode_jpeg(tf.constant(image_array)).eval()
  122. def _bytes_feature(value):
  123. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  124. example = tf.train.Example(features=tf.train.Features(feature={
  125. 'image/encoded': _bytes_feature(encoded_image),
  126. 'image/format': _bytes_feature('jpg'),
  127. 'image/source_id': _bytes_feature('image_id')
  128. })).SerializeToString()
  129. return example
  130. def test_export_graph_with_image_tensor_input(self):
  131. tmp_dir = self.get_temp_dir()
  132. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  133. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  134. use_moving_averages=False)
  135. with mock.patch.object(
  136. model_builder, 'build', autospec=True) as mock_builder:
  137. mock_builder.return_value = FakeModel()
  138. output_directory = os.path.join(tmp_dir, 'output')
  139. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  140. pipeline_config.eval_config.use_moving_averages = False
  141. exporter.export_inference_graph(
  142. input_type='image_tensor',
  143. pipeline_config=pipeline_config,
  144. trained_checkpoint_prefix=trained_checkpoint_prefix,
  145. output_directory=output_directory)
  146. self.assertTrue(os.path.exists(os.path.join(
  147. output_directory, 'saved_model', 'saved_model.pb')))
  148. def test_write_inference_graph(self):
  149. tmp_dir = self.get_temp_dir()
  150. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  151. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  152. use_moving_averages=False)
  153. with mock.patch.object(
  154. model_builder, 'build', autospec=True) as mock_builder:
  155. mock_builder.return_value = FakeModel()
  156. output_directory = os.path.join(tmp_dir, 'output')
  157. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  158. pipeline_config.eval_config.use_moving_averages = False
  159. exporter.export_inference_graph(
  160. input_type='image_tensor',
  161. pipeline_config=pipeline_config,
  162. trained_checkpoint_prefix=trained_checkpoint_prefix,
  163. output_directory=output_directory,
  164. write_inference_graph=True)
  165. self.assertTrue(os.path.exists(os.path.join(
  166. output_directory, 'inference_graph.pbtxt')))
  167. def test_export_graph_with_fixed_size_image_tensor_input(self):
  168. input_shape = [1, 320, 320, 3]
  169. tmp_dir = self.get_temp_dir()
  170. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  171. self._save_checkpoint_from_mock_model(
  172. trained_checkpoint_prefix, use_moving_averages=False)
  173. with mock.patch.object(
  174. model_builder, 'build', autospec=True) as mock_builder:
  175. mock_builder.return_value = FakeModel()
  176. output_directory = os.path.join(tmp_dir, 'output')
  177. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  178. pipeline_config.eval_config.use_moving_averages = False
  179. exporter.export_inference_graph(
  180. input_type='image_tensor',
  181. pipeline_config=pipeline_config,
  182. trained_checkpoint_prefix=trained_checkpoint_prefix,
  183. output_directory=output_directory,
  184. input_shape=input_shape)
  185. saved_model_path = os.path.join(output_directory, 'saved_model')
  186. self.assertTrue(
  187. os.path.exists(os.path.join(saved_model_path, 'saved_model.pb')))
  188. with tf.Graph().as_default() as od_graph:
  189. with self.test_session(graph=od_graph) as sess:
  190. meta_graph = tf.saved_model.loader.load(
  191. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  192. signature = meta_graph.signature_def['serving_default']
  193. input_tensor_name = signature.inputs['inputs'].name
  194. image_tensor = od_graph.get_tensor_by_name(input_tensor_name)
  195. self.assertSequenceEqual(image_tensor.get_shape().as_list(),
  196. input_shape)
  197. def test_export_graph_with_tf_example_input(self):
  198. tmp_dir = self.get_temp_dir()
  199. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  200. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  201. use_moving_averages=False)
  202. with mock.patch.object(
  203. model_builder, 'build', autospec=True) as mock_builder:
  204. mock_builder.return_value = FakeModel()
  205. output_directory = os.path.join(tmp_dir, 'output')
  206. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  207. pipeline_config.eval_config.use_moving_averages = False
  208. exporter.export_inference_graph(
  209. input_type='tf_example',
  210. pipeline_config=pipeline_config,
  211. trained_checkpoint_prefix=trained_checkpoint_prefix,
  212. output_directory=output_directory)
  213. self.assertTrue(os.path.exists(os.path.join(
  214. output_directory, 'saved_model', 'saved_model.pb')))
  215. def test_export_graph_with_encoded_image_string_input(self):
  216. tmp_dir = self.get_temp_dir()
  217. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  218. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  219. use_moving_averages=False)
  220. with mock.patch.object(
  221. model_builder, 'build', autospec=True) as mock_builder:
  222. mock_builder.return_value = FakeModel()
  223. output_directory = os.path.join(tmp_dir, 'output')
  224. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  225. pipeline_config.eval_config.use_moving_averages = False
  226. exporter.export_inference_graph(
  227. input_type='encoded_image_string_tensor',
  228. pipeline_config=pipeline_config,
  229. trained_checkpoint_prefix=trained_checkpoint_prefix,
  230. output_directory=output_directory)
  231. self.assertTrue(os.path.exists(os.path.join(
  232. output_directory, 'saved_model', 'saved_model.pb')))
  233. def _get_variables_in_checkpoint(self, checkpoint_file):
  234. return set([
  235. var_name
  236. for var_name, _ in tf.train.list_variables(checkpoint_file)])
  237. def test_replace_variable_values_with_moving_averages(self):
  238. tmp_dir = self.get_temp_dir()
  239. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  240. new_checkpoint_prefix = os.path.join(tmp_dir, 'new.ckpt')
  241. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  242. use_moving_averages=True)
  243. graph = tf.Graph()
  244. with graph.as_default():
  245. fake_model = FakeModel()
  246. preprocessed_inputs, true_image_shapes = fake_model.preprocess(
  247. tf.placeholder(dtype=tf.float32, shape=[None, None, None, 3]))
  248. predictions = fake_model.predict(preprocessed_inputs, true_image_shapes)
  249. fake_model.postprocess(predictions, true_image_shapes)
  250. exporter.replace_variable_values_with_moving_averages(
  251. graph, trained_checkpoint_prefix, new_checkpoint_prefix)
  252. expected_variables = set(['conv2d/bias', 'conv2d/kernel'])
  253. variables_in_old_ckpt = self._get_variables_in_checkpoint(
  254. trained_checkpoint_prefix)
  255. self.assertIn('conv2d/bias/ExponentialMovingAverage',
  256. variables_in_old_ckpt)
  257. self.assertIn('conv2d/kernel/ExponentialMovingAverage',
  258. variables_in_old_ckpt)
  259. variables_in_new_ckpt = self._get_variables_in_checkpoint(
  260. new_checkpoint_prefix)
  261. self.assertTrue(expected_variables.issubset(variables_in_new_ckpt))
  262. self.assertNotIn('conv2d/bias/ExponentialMovingAverage',
  263. variables_in_new_ckpt)
  264. self.assertNotIn('conv2d/kernel/ExponentialMovingAverage',
  265. variables_in_new_ckpt)
  266. def test_export_graph_with_moving_averages(self):
  267. tmp_dir = self.get_temp_dir()
  268. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  269. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  270. use_moving_averages=True)
  271. output_directory = os.path.join(tmp_dir, 'output')
  272. with mock.patch.object(
  273. model_builder, 'build', autospec=True) as mock_builder:
  274. mock_builder.return_value = FakeModel()
  275. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  276. pipeline_config.eval_config.use_moving_averages = True
  277. exporter.export_inference_graph(
  278. input_type='image_tensor',
  279. pipeline_config=pipeline_config,
  280. trained_checkpoint_prefix=trained_checkpoint_prefix,
  281. output_directory=output_directory)
  282. self.assertTrue(os.path.exists(os.path.join(
  283. output_directory, 'saved_model', 'saved_model.pb')))
  284. expected_variables = set(['conv2d/bias', 'conv2d/kernel', 'global_step'])
  285. actual_variables = set(
  286. [var_name for var_name, _ in tf.train.list_variables(output_directory)])
  287. self.assertTrue(expected_variables.issubset(actual_variables))
  288. def test_export_model_with_quantization_nodes(self):
  289. tmp_dir = self.get_temp_dir()
  290. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  291. self._save_checkpoint_from_mock_model(
  292. trained_checkpoint_prefix,
  293. use_moving_averages=False,
  294. enable_quantization=True)
  295. output_directory = os.path.join(tmp_dir, 'output')
  296. inference_graph_path = os.path.join(output_directory,
  297. 'inference_graph.pbtxt')
  298. with mock.patch.object(
  299. model_builder, 'build', autospec=True) as mock_builder:
  300. mock_builder.return_value = FakeModel()
  301. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  302. text_format.Merge(
  303. """graph_rewriter {
  304. quantization {
  305. delay: 50000
  306. activation_bits: 8
  307. weight_bits: 8
  308. }
  309. }""", pipeline_config)
  310. exporter.export_inference_graph(
  311. input_type='image_tensor',
  312. pipeline_config=pipeline_config,
  313. trained_checkpoint_prefix=trained_checkpoint_prefix,
  314. output_directory=output_directory,
  315. write_inference_graph=True)
  316. self._load_inference_graph(inference_graph_path, is_binary=False)
  317. has_quant_nodes = False
  318. for v in tf.global_variables():
  319. if v.op.name.endswith('act_quant/min'):
  320. has_quant_nodes = True
  321. break
  322. self.assertTrue(has_quant_nodes)
  323. def test_export_model_with_all_output_nodes(self):
  324. tmp_dir = self.get_temp_dir()
  325. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  326. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  327. use_moving_averages=True)
  328. output_directory = os.path.join(tmp_dir, 'output')
  329. inference_graph_path = os.path.join(output_directory,
  330. 'frozen_inference_graph.pb')
  331. with mock.patch.object(
  332. model_builder, 'build', autospec=True) as mock_builder:
  333. mock_builder.return_value = FakeModel(
  334. add_detection_keypoints=True, add_detection_masks=True)
  335. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  336. exporter.export_inference_graph(
  337. input_type='image_tensor',
  338. pipeline_config=pipeline_config,
  339. trained_checkpoint_prefix=trained_checkpoint_prefix,
  340. output_directory=output_directory)
  341. inference_graph = self._load_inference_graph(inference_graph_path)
  342. with self.test_session(graph=inference_graph):
  343. inference_graph.get_tensor_by_name('image_tensor:0')
  344. inference_graph.get_tensor_by_name('detection_boxes:0')
  345. inference_graph.get_tensor_by_name('detection_scores:0')
  346. inference_graph.get_tensor_by_name('detection_multiclass_scores:0')
  347. inference_graph.get_tensor_by_name('detection_classes:0')
  348. inference_graph.get_tensor_by_name('detection_keypoints:0')
  349. inference_graph.get_tensor_by_name('detection_masks:0')
  350. inference_graph.get_tensor_by_name('num_detections:0')
  351. def test_export_model_with_detection_only_nodes(self):
  352. tmp_dir = self.get_temp_dir()
  353. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  354. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  355. use_moving_averages=True)
  356. output_directory = os.path.join(tmp_dir, 'output')
  357. inference_graph_path = os.path.join(output_directory,
  358. 'frozen_inference_graph.pb')
  359. with mock.patch.object(
  360. model_builder, 'build', autospec=True) as mock_builder:
  361. mock_builder.return_value = FakeModel(add_detection_masks=False)
  362. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  363. exporter.export_inference_graph(
  364. input_type='image_tensor',
  365. pipeline_config=pipeline_config,
  366. trained_checkpoint_prefix=trained_checkpoint_prefix,
  367. output_directory=output_directory)
  368. inference_graph = self._load_inference_graph(inference_graph_path)
  369. with self.test_session(graph=inference_graph):
  370. inference_graph.get_tensor_by_name('image_tensor:0')
  371. inference_graph.get_tensor_by_name('detection_boxes:0')
  372. inference_graph.get_tensor_by_name('detection_scores:0')
  373. inference_graph.get_tensor_by_name('detection_multiclass_scores:0')
  374. inference_graph.get_tensor_by_name('detection_classes:0')
  375. inference_graph.get_tensor_by_name('num_detections:0')
  376. with self.assertRaises(KeyError):
  377. inference_graph.get_tensor_by_name('detection_keypoints:0')
  378. inference_graph.get_tensor_by_name('detection_masks:0')
  379. def test_export_and_run_inference_with_image_tensor(self):
  380. tmp_dir = self.get_temp_dir()
  381. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  382. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  383. use_moving_averages=True)
  384. output_directory = os.path.join(tmp_dir, 'output')
  385. inference_graph_path = os.path.join(output_directory,
  386. 'frozen_inference_graph.pb')
  387. with mock.patch.object(
  388. model_builder, 'build', autospec=True) as mock_builder:
  389. mock_builder.return_value = FakeModel(
  390. add_detection_keypoints=True, add_detection_masks=True)
  391. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  392. pipeline_config.eval_config.use_moving_averages = False
  393. exporter.export_inference_graph(
  394. input_type='image_tensor',
  395. pipeline_config=pipeline_config,
  396. trained_checkpoint_prefix=trained_checkpoint_prefix,
  397. output_directory=output_directory)
  398. inference_graph = self._load_inference_graph(inference_graph_path)
  399. with self.test_session(graph=inference_graph) as sess:
  400. image_tensor = inference_graph.get_tensor_by_name('image_tensor:0')
  401. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  402. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  403. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  404. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  405. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  406. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  407. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  408. num_detections_np) = sess.run(
  409. [boxes, scores, classes, keypoints, masks, num_detections],
  410. feed_dict={image_tensor: np.ones((2, 4, 4, 3)).astype(np.uint8)})
  411. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  412. [0.5, 0.5, 0.8, 0.8]],
  413. [[0.5, 0.5, 1.0, 1.0],
  414. [0.0, 0.0, 0.0, 0.0]]])
  415. self.assertAllClose(scores_np, [[0.7, 0.6],
  416. [0.9, 0.0]])
  417. self.assertAllClose(classes_np, [[1, 2],
  418. [2, 1]])
  419. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  420. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  421. self.assertAllClose(num_detections_np, [2, 1])
  422. def _create_encoded_image_string(self, image_array_np, encoding_format):
  423. od_graph = tf.Graph()
  424. with od_graph.as_default():
  425. if encoding_format == 'jpg':
  426. encoded_string = tf.image.encode_jpeg(image_array_np)
  427. elif encoding_format == 'png':
  428. encoded_string = tf.image.encode_png(image_array_np)
  429. else:
  430. raise ValueError('Supports only the following formats: `jpg`, `png`')
  431. with self.test_session(graph=od_graph):
  432. return encoded_string.eval()
  433. def test_export_and_run_inference_with_encoded_image_string_tensor(self):
  434. tmp_dir = self.get_temp_dir()
  435. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  436. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  437. use_moving_averages=True)
  438. output_directory = os.path.join(tmp_dir, 'output')
  439. inference_graph_path = os.path.join(output_directory,
  440. 'frozen_inference_graph.pb')
  441. with mock.patch.object(
  442. model_builder, 'build', autospec=True) as mock_builder:
  443. mock_builder.return_value = FakeModel(
  444. add_detection_keypoints=True, add_detection_masks=True)
  445. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  446. pipeline_config.eval_config.use_moving_averages = False
  447. exporter.export_inference_graph(
  448. input_type='encoded_image_string_tensor',
  449. pipeline_config=pipeline_config,
  450. trained_checkpoint_prefix=trained_checkpoint_prefix,
  451. output_directory=output_directory)
  452. inference_graph = self._load_inference_graph(inference_graph_path)
  453. jpg_image_str = self._create_encoded_image_string(
  454. np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
  455. png_image_str = self._create_encoded_image_string(
  456. np.ones((4, 4, 3)).astype(np.uint8), 'png')
  457. with self.test_session(graph=inference_graph) as sess:
  458. image_str_tensor = inference_graph.get_tensor_by_name(
  459. 'encoded_image_string_tensor:0')
  460. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  461. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  462. multiclass_scores = inference_graph.get_tensor_by_name(
  463. 'detection_multiclass_scores:0')
  464. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  465. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  466. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  467. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  468. for image_str in [jpg_image_str, png_image_str]:
  469. image_str_batch_np = np.hstack([image_str]* 2)
  470. (boxes_np, scores_np, multiclass_scores_np, classes_np, keypoints_np,
  471. masks_np, num_detections_np) = sess.run(
  472. [
  473. boxes, scores, multiclass_scores, classes, keypoints, masks,
  474. num_detections
  475. ],
  476. feed_dict={image_str_tensor: image_str_batch_np})
  477. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  478. [0.5, 0.5, 0.8, 0.8]],
  479. [[0.5, 0.5, 1.0, 1.0],
  480. [0.0, 0.0, 0.0, 0.0]]])
  481. self.assertAllClose(scores_np, [[0.7, 0.6],
  482. [0.9, 0.0]])
  483. self.assertAllClose(multiclass_scores_np, [[[0.3, 0.7], [0.4, 0.6]],
  484. [[0.1, 0.9], [0.0, 0.0]]])
  485. self.assertAllClose(classes_np, [[1, 2],
  486. [2, 1]])
  487. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  488. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  489. self.assertAllClose(num_detections_np, [2, 1])
  490. def test_raise_runtime_error_on_images_with_different_sizes(self):
  491. tmp_dir = self.get_temp_dir()
  492. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  493. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  494. use_moving_averages=True)
  495. output_directory = os.path.join(tmp_dir, 'output')
  496. inference_graph_path = os.path.join(output_directory,
  497. 'frozen_inference_graph.pb')
  498. with mock.patch.object(
  499. model_builder, 'build', autospec=True) as mock_builder:
  500. mock_builder.return_value = FakeModel(
  501. add_detection_keypoints=True, add_detection_masks=True)
  502. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  503. pipeline_config.eval_config.use_moving_averages = False
  504. exporter.export_inference_graph(
  505. input_type='encoded_image_string_tensor',
  506. pipeline_config=pipeline_config,
  507. trained_checkpoint_prefix=trained_checkpoint_prefix,
  508. output_directory=output_directory)
  509. inference_graph = self._load_inference_graph(inference_graph_path)
  510. large_image = self._create_encoded_image_string(
  511. np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
  512. small_image = self._create_encoded_image_string(
  513. np.ones((2, 2, 3)).astype(np.uint8), 'jpg')
  514. image_str_batch_np = np.hstack([large_image, small_image])
  515. with self.test_session(graph=inference_graph) as sess:
  516. image_str_tensor = inference_graph.get_tensor_by_name(
  517. 'encoded_image_string_tensor:0')
  518. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  519. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  520. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  521. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  522. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  523. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  524. with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
  525. 'TensorArray.*shape'):
  526. sess.run(
  527. [boxes, scores, classes, keypoints, masks, num_detections],
  528. feed_dict={image_str_tensor: image_str_batch_np})
  529. def test_export_and_run_inference_with_tf_example(self):
  530. tmp_dir = self.get_temp_dir()
  531. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  532. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  533. use_moving_averages=True)
  534. output_directory = os.path.join(tmp_dir, 'output')
  535. inference_graph_path = os.path.join(output_directory,
  536. 'frozen_inference_graph.pb')
  537. with mock.patch.object(
  538. model_builder, 'build', autospec=True) as mock_builder:
  539. mock_builder.return_value = FakeModel(
  540. add_detection_keypoints=True, add_detection_masks=True)
  541. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  542. pipeline_config.eval_config.use_moving_averages = False
  543. exporter.export_inference_graph(
  544. input_type='tf_example',
  545. pipeline_config=pipeline_config,
  546. trained_checkpoint_prefix=trained_checkpoint_prefix,
  547. output_directory=output_directory)
  548. inference_graph = self._load_inference_graph(inference_graph_path)
  549. tf_example_np = np.expand_dims(self._create_tf_example(
  550. np.ones((4, 4, 3)).astype(np.uint8)), axis=0)
  551. with self.test_session(graph=inference_graph) as sess:
  552. tf_example = inference_graph.get_tensor_by_name('tf_example:0')
  553. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  554. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  555. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  556. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  557. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  558. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  559. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  560. num_detections_np) = sess.run(
  561. [boxes, scores, classes, keypoints, masks, num_detections],
  562. feed_dict={tf_example: tf_example_np})
  563. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  564. [0.5, 0.5, 0.8, 0.8]],
  565. [[0.5, 0.5, 1.0, 1.0],
  566. [0.0, 0.0, 0.0, 0.0]]])
  567. self.assertAllClose(scores_np, [[0.7, 0.6],
  568. [0.9, 0.0]])
  569. self.assertAllClose(classes_np, [[1, 2],
  570. [2, 1]])
  571. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  572. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  573. self.assertAllClose(num_detections_np, [2, 1])
  574. def test_write_frozen_graph(self):
  575. tmp_dir = self.get_temp_dir()
  576. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  577. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  578. use_moving_averages=True)
  579. output_directory = os.path.join(tmp_dir, 'output')
  580. inference_graph_path = os.path.join(output_directory,
  581. 'frozen_inference_graph.pb')
  582. tf.gfile.MakeDirs(output_directory)
  583. with mock.patch.object(
  584. model_builder, 'build', autospec=True) as mock_builder:
  585. mock_builder.return_value = FakeModel(
  586. add_detection_keypoints=True, add_detection_masks=True)
  587. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  588. pipeline_config.eval_config.use_moving_averages = False
  589. detection_model = model_builder.build(pipeline_config.model,
  590. is_training=False)
  591. outputs, _ = exporter.build_detection_graph(
  592. input_type='tf_example',
  593. detection_model=detection_model,
  594. input_shape=None,
  595. output_collection_name='inference_op',
  596. graph_hook_fn=None)
  597. output_node_names = ','.join(outputs.keys())
  598. saver = tf.train.Saver()
  599. input_saver_def = saver.as_saver_def()
  600. exporter.freeze_graph_with_def_protos(
  601. input_graph_def=tf.get_default_graph().as_graph_def(),
  602. input_saver_def=input_saver_def,
  603. input_checkpoint=trained_checkpoint_prefix,
  604. output_node_names=output_node_names,
  605. restore_op_name='save/restore_all',
  606. filename_tensor_name='save/Const:0',
  607. output_graph=inference_graph_path,
  608. clear_devices=True,
  609. initializer_nodes='')
  610. inference_graph = self._load_inference_graph(inference_graph_path)
  611. tf_example_np = np.expand_dims(self._create_tf_example(
  612. np.ones((4, 4, 3)).astype(np.uint8)), axis=0)
  613. with self.test_session(graph=inference_graph) as sess:
  614. tf_example = inference_graph.get_tensor_by_name('tf_example:0')
  615. boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
  616. scores = inference_graph.get_tensor_by_name('detection_scores:0')
  617. classes = inference_graph.get_tensor_by_name('detection_classes:0')
  618. keypoints = inference_graph.get_tensor_by_name('detection_keypoints:0')
  619. masks = inference_graph.get_tensor_by_name('detection_masks:0')
  620. num_detections = inference_graph.get_tensor_by_name('num_detections:0')
  621. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  622. num_detections_np) = sess.run(
  623. [boxes, scores, classes, keypoints, masks, num_detections],
  624. feed_dict={tf_example: tf_example_np})
  625. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  626. [0.5, 0.5, 0.8, 0.8]],
  627. [[0.5, 0.5, 1.0, 1.0],
  628. [0.0, 0.0, 0.0, 0.0]]])
  629. self.assertAllClose(scores_np, [[0.7, 0.6],
  630. [0.9, 0.0]])
  631. self.assertAllClose(classes_np, [[1, 2],
  632. [2, 1]])
  633. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  634. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  635. self.assertAllClose(num_detections_np, [2, 1])
  636. def test_export_graph_saves_pipeline_file(self):
  637. tmp_dir = self.get_temp_dir()
  638. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  639. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  640. use_moving_averages=True)
  641. output_directory = os.path.join(tmp_dir, 'output')
  642. with mock.patch.object(
  643. model_builder, 'build', autospec=True) as mock_builder:
  644. mock_builder.return_value = FakeModel()
  645. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  646. exporter.export_inference_graph(
  647. input_type='image_tensor',
  648. pipeline_config=pipeline_config,
  649. trained_checkpoint_prefix=trained_checkpoint_prefix,
  650. output_directory=output_directory)
  651. expected_pipeline_path = os.path.join(
  652. output_directory, 'pipeline.config')
  653. self.assertTrue(os.path.exists(expected_pipeline_path))
  654. written_pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  655. with tf.gfile.GFile(expected_pipeline_path, 'r') as f:
  656. proto_str = f.read()
  657. text_format.Merge(proto_str, written_pipeline_config)
  658. self.assertProtoEquals(pipeline_config, written_pipeline_config)
  659. def test_export_saved_model_and_run_inference(self):
  660. tmp_dir = self.get_temp_dir()
  661. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  662. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  663. use_moving_averages=False)
  664. output_directory = os.path.join(tmp_dir, 'output')
  665. saved_model_path = os.path.join(output_directory, 'saved_model')
  666. with mock.patch.object(
  667. model_builder, 'build', autospec=True) as mock_builder:
  668. mock_builder.return_value = FakeModel(
  669. add_detection_keypoints=True, add_detection_masks=True)
  670. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  671. pipeline_config.eval_config.use_moving_averages = False
  672. exporter.export_inference_graph(
  673. input_type='tf_example',
  674. pipeline_config=pipeline_config,
  675. trained_checkpoint_prefix=trained_checkpoint_prefix,
  676. output_directory=output_directory)
  677. tf_example_np = np.hstack([self._create_tf_example(
  678. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  679. with tf.Graph().as_default() as od_graph:
  680. with self.test_session(graph=od_graph) as sess:
  681. meta_graph = tf.saved_model.loader.load(
  682. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  683. signature = meta_graph.signature_def['serving_default']
  684. input_tensor_name = signature.inputs['inputs'].name
  685. tf_example = od_graph.get_tensor_by_name(input_tensor_name)
  686. boxes = od_graph.get_tensor_by_name(
  687. signature.outputs['detection_boxes'].name)
  688. scores = od_graph.get_tensor_by_name(
  689. signature.outputs['detection_scores'].name)
  690. classes = od_graph.get_tensor_by_name(
  691. signature.outputs['detection_classes'].name)
  692. keypoints = od_graph.get_tensor_by_name(
  693. signature.outputs['detection_keypoints'].name)
  694. masks = od_graph.get_tensor_by_name(
  695. signature.outputs['detection_masks'].name)
  696. num_detections = od_graph.get_tensor_by_name(
  697. signature.outputs['num_detections'].name)
  698. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  699. num_detections_np) = sess.run(
  700. [boxes, scores, classes, keypoints, masks, num_detections],
  701. feed_dict={tf_example: tf_example_np})
  702. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  703. [0.5, 0.5, 0.8, 0.8]],
  704. [[0.5, 0.5, 1.0, 1.0],
  705. [0.0, 0.0, 0.0, 0.0]]])
  706. self.assertAllClose(scores_np, [[0.7, 0.6],
  707. [0.9, 0.0]])
  708. self.assertAllClose(classes_np, [[1, 2],
  709. [2, 1]])
  710. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  711. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  712. self.assertAllClose(num_detections_np, [2, 1])
  713. def test_write_saved_model(self):
  714. tmp_dir = self.get_temp_dir()
  715. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  716. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  717. use_moving_averages=False)
  718. output_directory = os.path.join(tmp_dir, 'output')
  719. saved_model_path = os.path.join(output_directory, 'saved_model')
  720. tf.gfile.MakeDirs(output_directory)
  721. with mock.patch.object(
  722. model_builder, 'build', autospec=True) as mock_builder:
  723. mock_builder.return_value = FakeModel(
  724. add_detection_keypoints=True, add_detection_masks=True)
  725. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  726. pipeline_config.eval_config.use_moving_averages = False
  727. detection_model = model_builder.build(pipeline_config.model,
  728. is_training=False)
  729. outputs, placeholder_tensor = exporter.build_detection_graph(
  730. input_type='tf_example',
  731. detection_model=detection_model,
  732. input_shape=None,
  733. output_collection_name='inference_op',
  734. graph_hook_fn=None)
  735. output_node_names = ','.join(outputs.keys())
  736. saver = tf.train.Saver()
  737. input_saver_def = saver.as_saver_def()
  738. frozen_graph_def = exporter.freeze_graph_with_def_protos(
  739. input_graph_def=tf.get_default_graph().as_graph_def(),
  740. input_saver_def=input_saver_def,
  741. input_checkpoint=trained_checkpoint_prefix,
  742. output_node_names=output_node_names,
  743. restore_op_name='save/restore_all',
  744. filename_tensor_name='save/Const:0',
  745. output_graph='',
  746. clear_devices=True,
  747. initializer_nodes='')
  748. exporter.write_saved_model(
  749. saved_model_path=saved_model_path,
  750. frozen_graph_def=frozen_graph_def,
  751. inputs=placeholder_tensor,
  752. outputs=outputs)
  753. tf_example_np = np.hstack([self._create_tf_example(
  754. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  755. with tf.Graph().as_default() as od_graph:
  756. with self.test_session(graph=od_graph) as sess:
  757. meta_graph = tf.saved_model.loader.load(
  758. sess, [tf.saved_model.tag_constants.SERVING], saved_model_path)
  759. signature = meta_graph.signature_def['serving_default']
  760. input_tensor_name = signature.inputs['inputs'].name
  761. tf_example = od_graph.get_tensor_by_name(input_tensor_name)
  762. boxes = od_graph.get_tensor_by_name(
  763. signature.outputs['detection_boxes'].name)
  764. scores = od_graph.get_tensor_by_name(
  765. signature.outputs['detection_scores'].name)
  766. classes = od_graph.get_tensor_by_name(
  767. signature.outputs['detection_classes'].name)
  768. keypoints = od_graph.get_tensor_by_name(
  769. signature.outputs['detection_keypoints'].name)
  770. masks = od_graph.get_tensor_by_name(
  771. signature.outputs['detection_masks'].name)
  772. num_detections = od_graph.get_tensor_by_name(
  773. signature.outputs['num_detections'].name)
  774. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  775. num_detections_np) = sess.run(
  776. [boxes, scores, classes, keypoints, masks, num_detections],
  777. feed_dict={tf_example: tf_example_np})
  778. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  779. [0.5, 0.5, 0.8, 0.8]],
  780. [[0.5, 0.5, 1.0, 1.0],
  781. [0.0, 0.0, 0.0, 0.0]]])
  782. self.assertAllClose(scores_np, [[0.7, 0.6],
  783. [0.9, 0.0]])
  784. self.assertAllClose(classes_np, [[1, 2],
  785. [2, 1]])
  786. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  787. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  788. self.assertAllClose(num_detections_np, [2, 1])
  789. def test_export_checkpoint_and_run_inference(self):
  790. tmp_dir = self.get_temp_dir()
  791. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  792. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  793. use_moving_averages=False)
  794. output_directory = os.path.join(tmp_dir, 'output')
  795. model_path = os.path.join(output_directory, 'model.ckpt')
  796. meta_graph_path = model_path + '.meta'
  797. with mock.patch.object(
  798. model_builder, 'build', autospec=True) as mock_builder:
  799. mock_builder.return_value = FakeModel(
  800. add_detection_keypoints=True, add_detection_masks=True)
  801. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  802. pipeline_config.eval_config.use_moving_averages = False
  803. exporter.export_inference_graph(
  804. input_type='tf_example',
  805. pipeline_config=pipeline_config,
  806. trained_checkpoint_prefix=trained_checkpoint_prefix,
  807. output_directory=output_directory)
  808. tf_example_np = np.hstack([self._create_tf_example(
  809. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  810. with tf.Graph().as_default() as od_graph:
  811. with self.test_session(graph=od_graph) as sess:
  812. new_saver = tf.train.import_meta_graph(meta_graph_path)
  813. new_saver.restore(sess, model_path)
  814. tf_example = od_graph.get_tensor_by_name('tf_example:0')
  815. boxes = od_graph.get_tensor_by_name('detection_boxes:0')
  816. scores = od_graph.get_tensor_by_name('detection_scores:0')
  817. classes = od_graph.get_tensor_by_name('detection_classes:0')
  818. keypoints = od_graph.get_tensor_by_name('detection_keypoints:0')
  819. masks = od_graph.get_tensor_by_name('detection_masks:0')
  820. num_detections = od_graph.get_tensor_by_name('num_detections:0')
  821. (boxes_np, scores_np, classes_np, keypoints_np, masks_np,
  822. num_detections_np) = sess.run(
  823. [boxes, scores, classes, keypoints, masks, num_detections],
  824. feed_dict={tf_example: tf_example_np})
  825. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  826. [0.5, 0.5, 0.8, 0.8]],
  827. [[0.5, 0.5, 1.0, 1.0],
  828. [0.0, 0.0, 0.0, 0.0]]])
  829. self.assertAllClose(scores_np, [[0.7, 0.6],
  830. [0.9, 0.0]])
  831. self.assertAllClose(classes_np, [[1, 2],
  832. [2, 1]])
  833. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  834. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  835. self.assertAllClose(num_detections_np, [2, 1])
  836. def test_write_graph_and_checkpoint(self):
  837. tmp_dir = self.get_temp_dir()
  838. trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
  839. self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
  840. use_moving_averages=False)
  841. output_directory = os.path.join(tmp_dir, 'output')
  842. model_path = os.path.join(output_directory, 'model.ckpt')
  843. meta_graph_path = model_path + '.meta'
  844. tf.gfile.MakeDirs(output_directory)
  845. with mock.patch.object(
  846. model_builder, 'build', autospec=True) as mock_builder:
  847. mock_builder.return_value = FakeModel(
  848. add_detection_keypoints=True, add_detection_masks=True)
  849. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  850. pipeline_config.eval_config.use_moving_averages = False
  851. detection_model = model_builder.build(pipeline_config.model,
  852. is_training=False)
  853. exporter.build_detection_graph(
  854. input_type='tf_example',
  855. detection_model=detection_model,
  856. input_shape=None,
  857. output_collection_name='inference_op',
  858. graph_hook_fn=None)
  859. saver = tf.train.Saver()
  860. input_saver_def = saver.as_saver_def()
  861. exporter.write_graph_and_checkpoint(
  862. inference_graph_def=tf.get_default_graph().as_graph_def(),
  863. model_path=model_path,
  864. input_saver_def=input_saver_def,
  865. trained_checkpoint_prefix=trained_checkpoint_prefix)
  866. tf_example_np = np.hstack([self._create_tf_example(
  867. np.ones((4, 4, 3)).astype(np.uint8))] * 2)
  868. with tf.Graph().as_default() as od_graph:
  869. with self.test_session(graph=od_graph) as sess:
  870. new_saver = tf.train.import_meta_graph(meta_graph_path)
  871. new_saver.restore(sess, model_path)
  872. tf_example = od_graph.get_tensor_by_name('tf_example:0')
  873. boxes = od_graph.get_tensor_by_name('detection_boxes:0')
  874. scores = od_graph.get_tensor_by_name('detection_scores:0')
  875. raw_boxes = od_graph.get_tensor_by_name('raw_detection_boxes:0')
  876. raw_scores = od_graph.get_tensor_by_name('raw_detection_scores:0')
  877. classes = od_graph.get_tensor_by_name('detection_classes:0')
  878. keypoints = od_graph.get_tensor_by_name('detection_keypoints:0')
  879. masks = od_graph.get_tensor_by_name('detection_masks:0')
  880. num_detections = od_graph.get_tensor_by_name('num_detections:0')
  881. (boxes_np, scores_np, raw_boxes_np, raw_scores_np, classes_np,
  882. keypoints_np, masks_np, num_detections_np) = sess.run(
  883. [boxes, scores, raw_boxes, raw_scores, classes, keypoints, masks,
  884. num_detections],
  885. feed_dict={tf_example: tf_example_np})
  886. self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  887. [0.5, 0.5, 0.8, 0.8]],
  888. [[0.5, 0.5, 1.0, 1.0],
  889. [0.0, 0.0, 0.0, 0.0]]])
  890. self.assertAllClose(scores_np, [[0.7, 0.6],
  891. [0.9, 0.0]])
  892. self.assertAllClose(raw_boxes_np, [[[0.0, 0.0, 0.5, 0.5],
  893. [0.5, 0.5, 0.8, 0.8]],
  894. [[0.5, 0.5, 1.0, 1.0],
  895. [0.0, 0.5, 0.0, 0.5]]])
  896. self.assertAllClose(raw_scores_np, [[0.7, 0.6],
  897. [0.9, 0.5]])
  898. self.assertAllClose(classes_np, [[1, 2],
  899. [2, 1]])
  900. self.assertAllClose(keypoints_np, np.arange(48).reshape([2, 2, 6, 2]))
  901. self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
  902. self.assertAllClose(num_detections_np, [2, 1])
  903. def test_rewrite_nn_resize_op(self):
  904. g = tf.Graph()
  905. with g.as_default():
  906. x = array_ops.placeholder(dtypes.float32, shape=(8, 10, 10, 8))
  907. y = array_ops.placeholder(dtypes.float32, shape=(8, 20, 20, 8))
  908. s = ops.nearest_neighbor_upsampling(x, 2)
  909. t = s + y
  910. exporter.rewrite_nn_resize_op()
  911. resize_op_found = False
  912. for op in g.get_operations():
  913. if op.type == 'ResizeNearestNeighbor':
  914. resize_op_found = True
  915. self.assertEqual(op.inputs[0], x)
  916. self.assertEqual(op.outputs[0].consumers()[0], t.op)
  917. break
  918. self.assertTrue(resize_op_found)
  919. def test_rewrite_nn_resize_op_quantized(self):
  920. g = tf.Graph()
  921. with g.as_default():
  922. x = array_ops.placeholder(dtypes.float32, shape=(8, 10, 10, 8))
  923. x_conv = tf.contrib.slim.conv2d(x, 8, 1)
  924. y = array_ops.placeholder(dtypes.float32, shape=(8, 20, 20, 8))
  925. s = ops.nearest_neighbor_upsampling(x_conv, 2)
  926. t = s + y
  927. graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
  928. graph_rewriter_config.quantization.delay = 500000
  929. graph_rewriter_fn = graph_rewriter_builder.build(
  930. graph_rewriter_config, is_training=False)
  931. graph_rewriter_fn()
  932. exporter.rewrite_nn_resize_op(is_quantized=True)
  933. resize_op_found = False
  934. for op in g.get_operations():
  935. if op.type == 'ResizeNearestNeighbor':
  936. resize_op_found = True
  937. self.assertEqual(op.inputs[0].op.type, 'FakeQuantWithMinMaxVars')
  938. self.assertEqual(op.outputs[0].consumers()[0], t.op)
  939. break
  940. self.assertTrue(resize_op_found)
  941. if __name__ == '__main__':
  942. tf.test.main()