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

Asim Shankar's avatar
Asim Shankar committed
20
import time
21
import unittest
22

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

25
from official.mnist import mnist
26
from official.utils.misc import keras_utils
27

Asim Shankar's avatar
Asim Shankar committed
28
BATCH_SIZE = 100
29
30


Asim Shankar's avatar
Asim Shankar committed
31
def dummy_input_fn():
32
33
  image = tf.random.uniform([BATCH_SIZE, 784])
  labels = tf.random.uniform([BATCH_SIZE, 1], maxval=9, dtype=tf.int32)
34
  return image, labels
35

36

Asim Shankar's avatar
Asim Shankar committed
37
38
39
40
41
42
43
44
def make_estimator():
  data_format = 'channels_last'
  if tf.test.is_built_with_cuda():
    data_format = 'channels_first'
  return tf.estimator.Estimator(
      model_fn=mnist.model_fn, params={
          'data_format': data_format
      })
45
46


Asim Shankar's avatar
Asim Shankar committed
47
class Tests(tf.test.TestCase):
48
  """Run tests for MNIST model.
49

50
51
52
53
54
  MNIST uses contrib and will not work with TF 2.0.  All tests are disabled if
  using TF 2.0.
  """

  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
Asim Shankar's avatar
Asim Shankar committed
55
56
57
58
  def test_mnist(self):
    classifier = make_estimator()
    classifier.train(input_fn=dummy_input_fn, steps=2)
    eval_results = classifier.evaluate(input_fn=dummy_input_fn, steps=1)
59

Asim Shankar's avatar
Asim Shankar committed
60
61
62
63
64
65
    loss = eval_results['loss']
    global_step = eval_results['global_step']
    accuracy = eval_results['accuracy']
    self.assertEqual(loss.shape, ())
    self.assertEqual(2, global_step)
    self.assertEqual(accuracy.shape, ())
66

67
    input_fn = lambda: tf.random.uniform([3, 784])
Asim Shankar's avatar
Asim Shankar committed
68
    predictions_generator = classifier.predict(input_fn)
Karmel Allison's avatar
Karmel Allison committed
69
    for _ in range(3):
Asim Shankar's avatar
Asim Shankar committed
70
71
72
      predictions = next(predictions_generator)
      self.assertEqual(predictions['probabilities'].shape, (10,))
      self.assertEqual(predictions['classes'].shape, ())
73

74
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
75
  def mnist_model_fn_helper(self, mode, multi_gpu=False):
Asim Shankar's avatar
Asim Shankar committed
76
77
78
    features, labels = dummy_input_fn()
    image_count = features.shape[0]
    spec = mnist.model_fn(features, labels, mode, {
79
80
        'data_format': 'channels_last',
        'multi_gpu': multi_gpu
Asim Shankar's avatar
Asim Shankar committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    })

    if mode == tf.estimator.ModeKeys.PREDICT:
      predictions = spec.predictions
      self.assertAllEqual(predictions['probabilities'].shape, (image_count, 10))
      self.assertEqual(predictions['probabilities'].dtype, tf.float32)
      self.assertAllEqual(predictions['classes'].shape, (image_count,))
      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)

102
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
Asim Shankar's avatar
Asim Shankar committed
103
104
105
  def test_mnist_model_fn_train_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN)

106
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
107
108
109
  def test_mnist_model_fn_train_mode_multi_gpu(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN, multi_gpu=True)

110
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
Asim Shankar's avatar
Asim Shankar committed
111
112
113
  def test_mnist_model_fn_eval_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.EVAL)

114
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
Asim Shankar's avatar
Asim Shankar committed
115
116
117
  def test_mnist_model_fn_predict_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.PREDICT)

Asim Shankar's avatar
Asim Shankar committed
118
119

class Benchmarks(tf.test.Benchmark):
Karmel Allison's avatar
Karmel Allison committed
120
  """Simple speed benchmarking for MNIST."""
Asim Shankar's avatar
Asim Shankar committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

  def benchmark_train_step_time(self):
    classifier = make_estimator()
    # Run one step to warmup any use of the GPU.
    classifier.train(input_fn=dummy_input_fn, steps=1)

    have_gpu = tf.test.is_gpu_available()
    num_steps = 1000 if have_gpu else 100
    name = 'train_step_time_%s' % ('gpu' if have_gpu else 'cpu')

    start = time.time()
    classifier.train(input_fn=dummy_input_fn, steps=num_steps)
    end = time.time()

    wall_time = (end - start) / num_steps
    self.report_benchmark(
        iters=num_steps,
        wall_time=wall_time,
        name=name,
        extras={
            'examples_per_sec': BATCH_SIZE / wall_time
        })
143
144
145


if __name__ == '__main__':
146
  tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
147
  tf.test.main()