mnist_test.py 4.48 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

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

24
from official.mnist import mnist
25

Asim Shankar's avatar
Asim Shankar committed
26
BATCH_SIZE = 100
27
28


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

34

Asim Shankar's avatar
Asim Shankar committed
35
36
37
38
39
40
41
42
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
      })
43
44


Asim Shankar's avatar
Asim Shankar committed
45
class Tests(tf.test.TestCase):
Karmel Allison's avatar
Karmel Allison committed
46
  """Run tests for MNIST model."""
47

Asim Shankar's avatar
Asim Shankar committed
48
49
50
51
  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)
52

Asim Shankar's avatar
Asim Shankar committed
53
54
55
56
57
58
    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, ())
59

Asim Shankar's avatar
Asim Shankar committed
60
61
    input_fn = lambda: tf.random_uniform([3, 784])
    predictions_generator = classifier.predict(input_fn)
Karmel Allison's avatar
Karmel Allison committed
62
    for _ in range(3):
Asim Shankar's avatar
Asim Shankar committed
63
64
65
      predictions = next(predictions_generator)
      self.assertEqual(predictions['probabilities'].shape, (10,))
      self.assertEqual(predictions['classes'].shape, ())
66

67
  def mnist_model_fn_helper(self, mode, multi_gpu=False):
Asim Shankar's avatar
Asim Shankar committed
68
69
70
    features, labels = dummy_input_fn()
    image_count = features.shape[0]
    spec = mnist.model_fn(features, labels, mode, {
71
72
        'data_format': 'channels_last',
        'multi_gpu': multi_gpu
Asim Shankar's avatar
Asim Shankar committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    })

    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)

  def test_mnist_model_fn_train_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN)

97
98
99
  def test_mnist_model_fn_train_mode_multi_gpu(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN, multi_gpu=True)

Asim Shankar's avatar
Asim Shankar committed
100
101
102
103
104
105
  def test_mnist_model_fn_eval_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.EVAL)

  def test_mnist_model_fn_predict_mode(self):
    self.mnist_model_fn_helper(tf.estimator.ModeKeys.PREDICT)

Asim Shankar's avatar
Asim Shankar committed
106
107

class Benchmarks(tf.test.Benchmark):
Karmel Allison's avatar
Karmel Allison committed
108
  """Simple speed benchmarking for MNIST."""
Asim Shankar's avatar
Asim Shankar committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

  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
        })
131
132
133


if __name__ == '__main__':
Asim Shankar's avatar
Asim Shankar committed
134
  tf.logging.set_verbosity(tf.logging.ERROR)
135
  tf.test.main()