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

from tempfile import mkstemp

import numpy as np
Karmel Allison's avatar
Karmel Allison committed
23
import tensorflow as tf  # pylint: disable=g-bad-import-order
24

25
from official.resnet import cifar10_main
26
from official.utils.testing import integration
27

28
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
29

30
_BATCH_SIZE = 128
Neal Wu's avatar
Neal Wu committed
31
32
33
_HEIGHT = 32
_WIDTH = 32
_NUM_CHANNELS = 3
34

35
36

class BaseTest(tf.test.TestCase):
Karmel Allison's avatar
Karmel Allison committed
37
38
  """Tests for the Cifar10 version of Resnet.
  """
39

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

45
46
  def tearDown(self):
    super(BaseTest, self).tearDown()
47
    tf.io.gfile.rmtree(self.get_temp_dir())
48

49
50
51
  def test_dataset_input_fn(self):
    fake_data = bytearray()
    fake_data.append(7)
Neal Wu's avatar
Neal Wu committed
52
53
    for i in range(_NUM_CHANNELS):
      for _ in range(_HEIGHT * _WIDTH):
54
55
56
        fake_data.append(i)

    _, filename = mkstemp(dir=self.get_temp_dir())
57
58
59
    data_file = open(filename, 'wb')
    data_file.write(fake_data)
    data_file.close()
60

61
    fake_dataset = tf.data.FixedLengthRecordDataset(
Karmel Allison's avatar
Karmel Allison committed
62
        filename, cifar10_main._RECORD_BYTES)  # pylint: disable=protected-access
63
    fake_dataset = fake_dataset.map(
Toby Boyd's avatar
Toby Boyd committed
64
        lambda val: cifar10_main.parse_record(val, False, tf.float32))
65
66
    image, label = tf.compat.v1.data.make_one_shot_iterator(
        fake_dataset).get_next()
67

68
    self.assertAllEqual(label.shape, ())
Neal Wu's avatar
Neal Wu committed
69
    self.assertAllEqual(image.shape, (_HEIGHT, _WIDTH, _NUM_CHANNELS))
70
71
72
73

    with self.test_session() as sess:
      image, label = sess.run([image, label])

74
      self.assertEqual(label, 7)
75
76
77

      for row in image:
        for pixel in row:
78
          self.assertAllClose(pixel, np.array([-1.225, 0., 1.225]), rtol=1e-3)
79

80
  def cifar10_model_fn_helper(self, mode, resnet_version, dtype):
Toby Boyd's avatar
Toby Boyd committed
81
    input_fn = cifar10_main.get_synth_input_fn(dtype)
82
    dataset = input_fn(True, '', _BATCH_SIZE)
83
    iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
84
85
86
87
88
89
90
    features, labels = iterator.get_next()
    spec = cifar10_main.cifar10_model_fn(
        features, labels, mode, {
            'dtype': dtype,
            'resnet_size': 32,
            'data_format': 'channels_last',
            'batch_size': _BATCH_SIZE,
91
            'resnet_version': resnet_version,
92
            'loss_scale': 128 if dtype == tf.float16 else 1,
Zac Wellmer's avatar
Zac Wellmer committed
93
            'fine_tune': False,
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
        })

    predictions = spec.predictions
    self.assertAllEqual(predictions['probabilities'].shape,
                        (_BATCH_SIZE, 10))
    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)
114

115
  def test_cifar10_model_fn_train_mode_v1(self):
116
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, resnet_version=1,
117
                                 dtype=tf.float32)
118

119
  def test_cifar10_model_fn_trainmode__v2(self):
120
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, resnet_version=2,
121
                                 dtype=tf.float32)
122
123

  def test_cifar10_model_fn_eval_mode_v1(self):
124
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.EVAL, resnet_version=1,
125
                                 dtype=tf.float32)
126
127

  def test_cifar10_model_fn_eval_mode_v2(self):
128
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.EVAL, resnet_version=2,
129
                                 dtype=tf.float32)
130
131

  def test_cifar10_model_fn_predict_mode_v1(self):
132
133
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.PREDICT,
                                 resnet_version=1, dtype=tf.float32)
134
135

  def test_cifar10_model_fn_predict_mode_v2(self):
136
137
    self.cifar10_model_fn_helper(tf.estimator.ModeKeys.PREDICT,
                                 resnet_version=2, dtype=tf.float32)
138

139
  def _test_cifar10model_shape(self, resnet_version):
Neal Wu's avatar
Neal Wu committed
140
141
142
    batch_size = 135
    num_classes = 246

143
    model = cifar10_main.Cifar10Model(32, data_format='channels_last',
144
145
                                      num_classes=num_classes,
                                      resnet_version=resnet_version)
146
    fake_input = tf.random.uniform([batch_size, _HEIGHT, _WIDTH, _NUM_CHANNELS])
147
148
149
150
151
    output = model(fake_input, training=True)

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

  def test_cifar10model_shape_v1(self):
152
    self._test_cifar10model_shape(resnet_version=1)
Neal Wu's avatar
Neal Wu committed
153

154
  def test_cifar10model_shape_v2(self):
155
    self._test_cifar10model_shape(resnet_version=2)
Neal Wu's avatar
Neal Wu committed
156

157
  def test_cifar10_end_to_end_synthetic_v1(self):
158
    integration.run_synthetic(
159
        main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(),
160
        extra_flags=['-resnet_version', '1']
161
    )
162
163

  def test_cifar10_end_to_end_synthetic_v2(self):
164
    integration.run_synthetic(
165
        main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(),
166
        extra_flags=['-resnet_version', '2']
167
    )
168

169
170
171

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