pnasnet_test.py 10.9 KB
Newer Older
maximneumann's avatar
maximneumann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Copyright 2018 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.
# ==============================================================================
"""Tests for slim.pnasnet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

20
21
import tensorflow.compat.v1 as tf
import tf_slim as slim
maximneumann's avatar
maximneumann committed
22
23
24
25
26
27
28
29
30
31

from nets.nasnet import pnasnet


class PNASNetTest(tf.test.TestCase):

  def testBuildLogitsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
32
    inputs = tf.random.uniform((batch_size, height, width, 3))
33
    tf.train.create_global_step()
maximneumann's avatar
maximneumann committed
34
35
36
37
38
39
40
41
42
43
44
    with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
      logits, end_points = pnasnet.build_pnasnet_large(inputs, num_classes)
    auxlogits = end_points['AuxLogits']
    predictions = end_points['Predictions']
    self.assertListEqual(auxlogits.get_shape().as_list(),
                         [batch_size, num_classes])
    self.assertListEqual(logits.get_shape().as_list(),
                         [batch_size, num_classes])
    self.assertListEqual(predictions.get_shape().as_list(),
                         [batch_size, num_classes])

45
46
47
48
  def testBuildLogitsMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
49
    inputs = tf.random.uniform((batch_size, height, width, 3))
50
    tf.train.create_global_step()
51
52
53
54
55
56
57
58
59
60
61
62
63
    with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
      logits, end_points = pnasnet.build_pnasnet_mobile(inputs, num_classes)
    auxlogits = end_points['AuxLogits']
    predictions = end_points['Predictions']
    self.assertListEqual(auxlogits.get_shape().as_list(),
                         [batch_size, num_classes])
    self.assertListEqual(logits.get_shape().as_list(),
                         [batch_size, num_classes])
    self.assertListEqual(predictions.get_shape().as_list(),
                         [batch_size, num_classes])

  def testBuildNonExistingLayerLargeModel(self):
    """Tests that the model is built correctly without unnecessary layers."""
64
    inputs = tf.random.uniform((5, 331, 331, 3))
65
    tf.train.create_global_step()
66
67
    with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
      pnasnet.build_pnasnet_large(inputs, 1000)
68
    vars_names = [x.op.name for x in tf.trainable_variables()]
69
70
71
72
73
    self.assertIn('cell_stem_0/1x1/weights', vars_names)
    self.assertNotIn('cell_stem_1/comb_iter_0/right/1x1/weights', vars_names)

  def testBuildNonExistingLayerMobileModel(self):
    """Tests that the model is built correctly without unnecessary layers."""
74
    inputs = tf.random.uniform((5, 224, 224, 3))
75
    tf.train.create_global_step()
76
77
    with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
      pnasnet.build_pnasnet_mobile(inputs, 1000)
78
    vars_names = [x.op.name for x in tf.trainable_variables()]
79
80
81
    self.assertIn('cell_stem_0/1x1/weights', vars_names)
    self.assertNotIn('cell_stem_1/comb_iter_0/right/1x1/weights', vars_names)

maximneumann's avatar
maximneumann committed
82
83
84
85
  def testBuildPreLogitsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = None
86
    inputs = tf.random.uniform((batch_size, height, width, 3))
87
    tf.train.create_global_step()
maximneumann's avatar
maximneumann committed
88
89
90
91
92
93
94
    with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
      net, end_points = pnasnet.build_pnasnet_large(inputs, num_classes)
    self.assertFalse('AuxLogits' in end_points)
    self.assertFalse('Predictions' in end_points)
    self.assertTrue(net.op.name.startswith('final_layer/Mean'))
    self.assertListEqual(net.get_shape().as_list(), [batch_size, 4320])

95
96
97
98
  def testBuildPreLogitsMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = None
99
    inputs = tf.random.uniform((batch_size, height, width, 3))
100
    tf.train.create_global_step()
101
102
103
104
105
106
107
    with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
      net, end_points = pnasnet.build_pnasnet_mobile(inputs, num_classes)
    self.assertFalse('AuxLogits' in end_points)
    self.assertFalse('Predictions' in end_points)
    self.assertTrue(net.op.name.startswith('final_layer/Mean'))
    self.assertListEqual(net.get_shape().as_list(), [batch_size, 1080])

maximneumann's avatar
maximneumann committed
108
109
110
111
  def testAllEndPointsShapesLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
112
    inputs = tf.random.uniform((batch_size, height, width, 3))
113
    tf.train.create_global_step()
maximneumann's avatar
maximneumann committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
      _, end_points = pnasnet.build_pnasnet_large(inputs, num_classes)

    endpoints_shapes = {'Stem': [batch_size, 42, 42, 540],
                        'Cell_0': [batch_size, 42, 42, 1080],
                        'Cell_1': [batch_size, 42, 42, 1080],
                        'Cell_2': [batch_size, 42, 42, 1080],
                        'Cell_3': [batch_size, 42, 42, 1080],
                        'Cell_4': [batch_size, 21, 21, 2160],
                        'Cell_5': [batch_size, 21, 21, 2160],
                        'Cell_6': [batch_size, 21, 21, 2160],
                        'Cell_7': [batch_size, 21, 21, 2160],
                        'Cell_8': [batch_size, 11, 11, 4320],
                        'Cell_9': [batch_size, 11, 11, 4320],
                        'Cell_10': [batch_size, 11, 11, 4320],
                        'Cell_11': [batch_size, 11, 11, 4320],
                        'global_pool': [batch_size, 4320],
                        # Logits and predictions
                        'AuxLogits': [batch_size, 1000],
                        'Predictions': [batch_size, 1000],
                        'Logits': [batch_size, 1000],
                       }
    self.assertEqual(len(end_points), 17)
    self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
    for endpoint_name in endpoints_shapes:
139
      tf.logging.info('Endpoint name: {}'.format(endpoint_name))
maximneumann's avatar
maximneumann committed
140
141
142
143
144
      expected_shape = endpoints_shapes[endpoint_name]
      self.assertIn(endpoint_name, end_points)
      self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
                           expected_shape)

145
146
147
148
  def testAllEndPointsShapesMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
149
    inputs = tf.random.uniform((batch_size, height, width, 3))
150
    tf.train.create_global_step()
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
      _, end_points = pnasnet.build_pnasnet_mobile(inputs, num_classes)

    endpoints_shapes = {
        'Stem': [batch_size, 28, 28, 135],
        'Cell_0': [batch_size, 28, 28, 270],
        'Cell_1': [batch_size, 28, 28, 270],
        'Cell_2': [batch_size, 28, 28, 270],
        'Cell_3': [batch_size, 14, 14, 540],
        'Cell_4': [batch_size, 14, 14, 540],
        'Cell_5': [batch_size, 14, 14, 540],
        'Cell_6': [batch_size, 7, 7, 1080],
        'Cell_7': [batch_size, 7, 7, 1080],
        'Cell_8': [batch_size, 7, 7, 1080],
        'global_pool': [batch_size, 1080],
        # Logits and predictions
        'AuxLogits': [batch_size, num_classes],
        'Predictions': [batch_size, num_classes],
        'Logits': [batch_size, num_classes],
    }
    self.assertEqual(len(end_points), 14)
    self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
    for endpoint_name in endpoints_shapes:
174
      tf.logging.info('Endpoint name: {}'.format(endpoint_name))
175
176
177
178
179
      expected_shape = endpoints_shapes[endpoint_name]
      self.assertIn(endpoint_name, end_points)
      self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
                           expected_shape)

maximneumann's avatar
maximneumann committed
180
181
182
183
184
  def testNoAuxHeadLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
    for use_aux_head in (True, False):
185
      tf.reset_default_graph()
186
      inputs = tf.random.uniform((batch_size, height, width, 3))
187
      tf.train.create_global_step()
maximneumann's avatar
maximneumann committed
188
189
190
191
192
193
194
      config = pnasnet.large_imagenet_config()
      config.set_hparam('use_aux_head', int(use_aux_head))
      with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
        _, end_points = pnasnet.build_pnasnet_large(inputs, num_classes,
                                                    config=config)
      self.assertEqual('AuxLogits' in end_points, use_aux_head)

195
196
197
198
199
  def testNoAuxHeadMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
    for use_aux_head in (True, False):
200
      tf.reset_default_graph()
201
      inputs = tf.random.uniform((batch_size, height, width, 3))
202
      tf.train.create_global_step()
203
204
205
206
207
208
209
      config = pnasnet.mobile_imagenet_config()
      config.set_hparam('use_aux_head', int(use_aux_head))
      with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
        _, end_points = pnasnet.build_pnasnet_mobile(
            inputs, num_classes, config=config)
      self.assertEqual('AuxLogits' in end_points, use_aux_head)

maximneumann's avatar
maximneumann committed
210
211
212
213
  def testOverrideHParamsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
214
    inputs = tf.random.uniform((batch_size, height, width, 3))
215
    tf.train.create_global_step()
maximneumann's avatar
maximneumann committed
216
217
218
219
220
221
222
223
    config = pnasnet.large_imagenet_config()
    config.set_hparam('data_format', 'NCHW')
    with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()):
      _, end_points = pnasnet.build_pnasnet_large(
          inputs, num_classes, config=config)
    self.assertListEqual(
        end_points['Stem'].shape.as_list(), [batch_size, 540, 42, 42])

224
225
226
227
  def testOverrideHParamsMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
228
    inputs = tf.random.uniform((batch_size, height, width, 3))
229
    tf.train.create_global_step()
230
231
232
233
234
235
236
237
    config = pnasnet.mobile_imagenet_config()
    config.set_hparam('data_format', 'NCHW')
    with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
      _, end_points = pnasnet.build_pnasnet_mobile(
          inputs, num_classes, config=config)
    self.assertListEqual(end_points['Stem'].shape.as_list(),
                         [batch_size, 135, 28, 28])

238
239
240
241
242
  def testUseBoundedAcitvationMobileModel(self):
    batch_size = 1
    height, width = 224, 224
    num_classes = 1000
    for use_bounded_activation in (True, False):
243
      tf.reset_default_graph()
244
      inputs = tf.random.uniform((batch_size, height, width, 3))
245
246
247
248
249
      config = pnasnet.mobile_imagenet_config()
      config.set_hparam('use_bounded_activation', use_bounded_activation)
      with slim.arg_scope(pnasnet.pnasnet_mobile_arg_scope()):
        _, _ = pnasnet.build_pnasnet_mobile(
            inputs, num_classes, config=config)
250
      for node in tf.get_default_graph().as_graph_def().node:
251
252
        if node.op.startswith('Relu'):
          self.assertEqual(node.op == 'Relu6', use_bounded_activation)
maximneumann's avatar
maximneumann committed
253
254
255

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