imagenet_test.py 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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.
# ==============================================================================

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import unittest

Karmel Allison's avatar
Karmel Allison committed
22
import tensorflow as tf  # pylint: disable=g-bad-import-order
23
from absl import logging
24

25
from official.r1.resnet import imagenet_main
26
from official.utils.testing import integration
27

28
logging.set_verbosity(logging.ERROR)
29

30
_BATCH_SIZE = 32
31
32
33
34
35
_LABEL_CLASSES = 1001


class BaseTest(tf.test.TestCase):

36
37
  _num_validation_images = None

38
39
40
41
  @classmethod
  def setUpClass(cls):  # pylint: disable=invalid-name
    super(BaseTest, cls).setUpClass()
    imagenet_main.define_imagenet_flags()
42
43
44

  def setUp(self):
    super(BaseTest, self).setUp()
45
    tf.compat.v1.disable_eager_execution()
46
47
    self._num_validation_images = imagenet_main.NUM_IMAGES['validation']
    imagenet_main.NUM_IMAGES['validation'] = 4
48

49
50
  def tearDown(self):
    super(BaseTest, self).tearDown()
51
    tf.io.gfile.rmtree(self.get_temp_dir())
52
    imagenet_main.NUM_IMAGES['validation'] = self._num_validation_images
53

54
  def _tensor_shapes_helper(self, resnet_size, resnet_version, dtype, with_gpu):
55
56
    """Checks the tensor shapes after each phase of the ResNet model."""
    def reshape(shape):
Karmel Allison's avatar
Karmel Allison committed
57
58
      """Returns the expected dimensions depending on if a GPU is being used."""

59
60
      # If a GPU is used for the test, the shape is returned (already in NCHW
      # form). When GPU is not used, the shape is converted to NHWC.
61
62
63
64
65
66
67
      if with_gpu:
        return shape
      return shape[0], shape[2], shape[3], shape[1]

    graph = tf.Graph()

    with graph.as_default(), self.test_session(
68
        graph=graph, use_gpu=with_gpu, force_gpu=with_gpu):
69
      model = imagenet_main.ImagenetModel(
70
          resnet_size=resnet_size,
71
          data_format='channels_first' if with_gpu else 'channels_last',
72
          resnet_version=resnet_version,
73
74
          dtype=dtype
      )
75
      inputs = tf.random.uniform([1, 224, 224, 3])
76
      output = model(inputs, training=True)
77

78
79
80
81
82
83
84
85
      initial_conv = graph.get_tensor_by_name('resnet_model/initial_conv:0')
      max_pool = graph.get_tensor_by_name('resnet_model/initial_max_pool:0')
      block_layer1 = graph.get_tensor_by_name('resnet_model/block_layer1:0')
      block_layer2 = graph.get_tensor_by_name('resnet_model/block_layer2:0')
      block_layer3 = graph.get_tensor_by_name('resnet_model/block_layer3:0')
      block_layer4 = graph.get_tensor_by_name('resnet_model/block_layer4:0')
      reduce_mean = graph.get_tensor_by_name('resnet_model/final_reduce_mean:0')
      dense = graph.get_tensor_by_name('resnet_model/final_dense:0')
86
87
88
89
90
91
92
93
94
95
96

      self.assertAllEqual(initial_conv.shape, reshape((1, 64, 112, 112)))
      self.assertAllEqual(max_pool.shape, reshape((1, 64, 56, 56)))

      # The number of channels after each block depends on whether we're
      # using the building_block or the bottleneck_block.
      if resnet_size < 50:
        self.assertAllEqual(block_layer1.shape, reshape((1, 64, 56, 56)))
        self.assertAllEqual(block_layer2.shape, reshape((1, 128, 28, 28)))
        self.assertAllEqual(block_layer3.shape, reshape((1, 256, 14, 14)))
        self.assertAllEqual(block_layer4.shape, reshape((1, 512, 7, 7)))
97
        self.assertAllEqual(reduce_mean.shape, reshape((1, 512, 1, 1)))
98
99
100
101
102
      else:
        self.assertAllEqual(block_layer1.shape, reshape((1, 256, 56, 56)))
        self.assertAllEqual(block_layer2.shape, reshape((1, 512, 28, 28)))
        self.assertAllEqual(block_layer3.shape, reshape((1, 1024, 14, 14)))
        self.assertAllEqual(block_layer4.shape, reshape((1, 2048, 7, 7)))
103
        self.assertAllEqual(reduce_mean.shape, reshape((1, 2048, 1, 1)))
104

105
106
      self.assertAllEqual(dense.shape, (1, _LABEL_CLASSES))
      self.assertAllEqual(output.shape, (1, _LABEL_CLASSES))
107

108
109
110
  def tensor_shapes_helper(self, resnet_size, resnet_version, with_gpu=False):
    self._tensor_shapes_helper(resnet_size=resnet_size,
                               resnet_version=resnet_version,
111
                               dtype=tf.float32, with_gpu=with_gpu)
112
113
    self._tensor_shapes_helper(resnet_size=resnet_size,
                               resnet_version=resnet_version,
114
115
                               dtype=tf.float16, with_gpu=with_gpu)

116
  def test_tensor_shapes_resnet_18_v1(self):
117
    self.tensor_shapes_helper(18, resnet_version=1)
118

119
  def test_tensor_shapes_resnet_18_v2(self):
120
    self.tensor_shapes_helper(18, resnet_version=2)
121

122
  def test_tensor_shapes_resnet_34_v1(self):
123
    self.tensor_shapes_helper(34, resnet_version=1)
124

125
  def test_tensor_shapes_resnet_34_v2(self):
126
    self.tensor_shapes_helper(34, resnet_version=2)
127

128
  def test_tensor_shapes_resnet_50_v1(self):
129
    self.tensor_shapes_helper(50, resnet_version=1)
130

131
  def test_tensor_shapes_resnet_50_v2(self):
132
    self.tensor_shapes_helper(50, resnet_version=2)
133
134

  def test_tensor_shapes_resnet_101_v1(self):
135
    self.tensor_shapes_helper(101, resnet_version=1)
136
137

  def test_tensor_shapes_resnet_101_v2(self):
138
    self.tensor_shapes_helper(101, resnet_version=2)
139
140

  def test_tensor_shapes_resnet_152_v1(self):
141
    self.tensor_shapes_helper(152, resnet_version=1)
142
143

  def test_tensor_shapes_resnet_152_v2(self):
144
    self.tensor_shapes_helper(152, resnet_version=2)
145
146

  def test_tensor_shapes_resnet_200_v1(self):
147
    self.tensor_shapes_helper(200, resnet_version=1)
148
149

  def test_tensor_shapes_resnet_200_v2(self):
150
    self.tensor_shapes_helper(200, resnet_version=2)
151
152
153

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_18_with_gpu_v1(self):
154
    self.tensor_shapes_helper(18, resnet_version=1, with_gpu=True)
155
156
157

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_18_with_gpu_v2(self):
158
    self.tensor_shapes_helper(18, resnet_version=2, with_gpu=True)
159
160
161

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_34_with_gpu_v1(self):
162
    self.tensor_shapes_helper(34, resnet_version=1, with_gpu=True)
163
164
165

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_34_with_gpu_v2(self):
166
    self.tensor_shapes_helper(34, resnet_version=2, with_gpu=True)
167
168

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
169
  def test_tensor_shapes_resnet_50_with_gpu_v1(self):
170
    self.tensor_shapes_helper(50, resnet_version=1, with_gpu=True)
171
172

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
173
  def test_tensor_shapes_resnet_50_with_gpu_v2(self):
174
    self.tensor_shapes_helper(50, resnet_version=2, with_gpu=True)
175
176

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
177
  def test_tensor_shapes_resnet_101_with_gpu_v1(self):
178
    self.tensor_shapes_helper(101, resnet_version=1, with_gpu=True)
179
180

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
181
  def test_tensor_shapes_resnet_101_with_gpu_v2(self):
182
    self.tensor_shapes_helper(101, resnet_version=2, with_gpu=True)
183
184

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
185
  def test_tensor_shapes_resnet_152_with_gpu_v1(self):
186
    self.tensor_shapes_helper(152, resnet_version=1, with_gpu=True)
187
188

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
189
  def test_tensor_shapes_resnet_152_with_gpu_v2(self):
190
    self.tensor_shapes_helper(152, resnet_version=2, with_gpu=True)
191

192
193
  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_200_with_gpu_v1(self):
194
    self.tensor_shapes_helper(200, resnet_version=1, with_gpu=True)
195
196
197

  @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
  def test_tensor_shapes_resnet_200_with_gpu_v2(self):
198
    self.tensor_shapes_helper(200, resnet_version=2, with_gpu=True)
199

200
  def resnet_model_fn_helper(self, mode, resnet_version, dtype):
201
    """Tests that the EstimatorSpec is given the appropriate arguments."""
202
    tf.compat.v1.train.create_global_step()
203

Toby Boyd's avatar
Toby Boyd committed
204
    input_fn = imagenet_main.get_synth_input_fn(dtype)
205
    dataset = input_fn(True, '', _BATCH_SIZE)
206
    iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
207
208
209
210
211
212
213
    features, labels = iterator.get_next()
    spec = imagenet_main.imagenet_model_fn(
        features, labels, mode, {
            'dtype': dtype,
            'resnet_size': 50,
            'data_format': 'channels_last',
            'batch_size': _BATCH_SIZE,
214
            'resnet_version': resnet_version,
215
            'loss_scale': 128 if dtype == tf.float16 else 1,
Zac Wellmer's avatar
Zac Wellmer committed
216
            'fine_tune': False,
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        })

    predictions = spec.predictions
    self.assertAllEqual(predictions['probabilities'].shape,
                        (_BATCH_SIZE, _LABEL_CLASSES))
    self.assertEqual(predictions['probabilities'].dtype, tf.float32)
    self.assertAllEqual(predictions['classes'].shape, (_BATCH_SIZE,))
    self.assertEqual(predictions['classes'].dtype, tf.int64)

    if mode != tf.estimator.ModeKeys.PREDICT:
      loss = spec.loss
      self.assertAllEqual(loss.shape, ())
      self.assertEqual(loss.dtype, tf.float32)

    if mode == tf.estimator.ModeKeys.EVAL:
      eval_metric_ops = spec.eval_metric_ops
      self.assertAllEqual(eval_metric_ops['accuracy'][0].shape, ())
      self.assertAllEqual(eval_metric_ops['accuracy'][1].shape, ())
      self.assertEqual(eval_metric_ops['accuracy'][0].dtype, tf.float32)
      self.assertEqual(eval_metric_ops['accuracy'][1].dtype, tf.float32)
237

238
  def test_resnet_model_fn_train_mode_v1(self):
239
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.TRAIN, resnet_version=1,
240
                                dtype=tf.float32)
241

242
  def test_resnet_model_fn_train_mode_v2(self):
243
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.TRAIN, resnet_version=2,
244
                                dtype=tf.float32)
245
246

  def test_resnet_model_fn_eval_mode_v1(self):
247
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.EVAL, resnet_version=1,
248
                                dtype=tf.float32)
249

250
  def test_resnet_model_fn_eval_mode_v2(self):
251
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.EVAL, resnet_version=2,
252
                                dtype=tf.float32)
Karmel Allison's avatar
Karmel Allison committed
253

254
  def test_resnet_model_fn_predict_mode_v1(self):
255
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.PREDICT, resnet_version=1,
256
                                dtype=tf.float32)
257

258
  def test_resnet_model_fn_predict_mode_v2(self):
259
    self.resnet_model_fn_helper(tf.estimator.ModeKeys.PREDICT, resnet_version=2,
260
                                dtype=tf.float32)
261

262
  def _test_imagenetmodel_shape(self, resnet_version):
Neal Wu's avatar
Neal Wu committed
263
264
265
    batch_size = 135
    num_classes = 246

266
267
    model = imagenet_main.ImagenetModel(
        50, data_format='channels_last', num_classes=num_classes,
268
        resnet_version=resnet_version)
269

270
    fake_input = tf.random.uniform([batch_size, 224, 224, 3])
271
272
273
274
275
    output = model(fake_input, training=True)

    self.assertAllEqual(output.shape, (batch_size, num_classes))

  def test_imagenetmodel_shape_v1(self):
276
    self._test_imagenetmodel_shape(resnet_version=1)
Neal Wu's avatar
Neal Wu committed
277

278
  def test_imagenetmodel_shape_v2(self):
279
    self._test_imagenetmodel_shape(resnet_version=2)
Neal Wu's avatar
Neal Wu committed
280

281
  def test_imagenet_end_to_end_synthetic_v1(self):
282
    integration.run_synthetic(
283
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
284
285
        extra_flags=['-resnet_version', '1', '-batch_size', '4',
                     '--max_train_steps', '1']
286
    )
287
288

  def test_imagenet_end_to_end_synthetic_v2(self):
289
    integration.run_synthetic(
290
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
291
292
        extra_flags=['-resnet_version', '2', '-batch_size', '4',
                     '--max_train_steps', '1']
293
    )
294
295

  def test_imagenet_end_to_end_synthetic_v1_tiny(self):
296
    integration.run_synthetic(
297
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
298
        extra_flags=['-resnet_version', '1', '-batch_size', '4',
299
                     '-resnet_size', '18', '--max_train_steps', '1']
300
    )
301
302

  def test_imagenet_end_to_end_synthetic_v2_tiny(self):
303
    integration.run_synthetic(
304
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
305
        extra_flags=['-resnet_version', '2', '-batch_size', '4',
306
                     '-resnet_size', '18', '--max_train_steps', '1']
307
    )
308
309

  def test_imagenet_end_to_end_synthetic_v1_huge(self):
310
    integration.run_synthetic(
311
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
312
        extra_flags=['-resnet_version', '1', '-batch_size', '4',
313
                     '-resnet_size', '200', '--max_train_steps', '1']
314
    )
315
316

  def test_imagenet_end_to_end_synthetic_v2_huge(self):
317
    integration.run_synthetic(
318
        main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
319
        extra_flags=['-resnet_version', '2', '-batch_size', '4',
320
                     '-resnet_size', '200', '--max_train_steps', '1']
321
322
    )

323

324
325
if __name__ == '__main__':
  tf.test.main()