nasnet_test.py 18.6 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.
# ==============================================================================
"""Tests for slim.nasnet."""
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
22
23
24
25
26
27
28
29
30
31

from nets.nasnet import nasnet


class NASNetTest(tf.test.TestCase):

  def testBuildLogitsCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = 10
32
    inputs = tf.random.uniform((batch_size, height, width, 3))
33
    tf.train.create_global_step()
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
      logits, end_points = nasnet.build_nasnet_cifar(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 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
64
65
    with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
      logits, end_points = nasnet.build_nasnet_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 testBuildLogitsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
66
    inputs = tf.random.uniform((batch_size, height, width, 3))
67
    tf.train.create_global_step()
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    with slim.arg_scope(nasnet.nasnet_large_arg_scope()):
      logits, end_points = nasnet.build_nasnet_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])

  def testBuildPreLogitsCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = None
83
    inputs = tf.random.uniform((batch_size, height, width, 3))
84
    tf.train.create_global_step()
85
86
87
88
89
90
91
92
93
94
95
    with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
      net, end_points = nasnet.build_nasnet_cifar(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, 768])

  def testBuildPreLogitsMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = None
96
    inputs = tf.random.uniform((batch_size, height, width, 3))
97
    tf.train.create_global_step()
98
99
100
101
102
103
104
105
106
107
108
    with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
      net, end_points = nasnet.build_nasnet_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, 1056])

  def testBuildPreLogitsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = None
109
    inputs = tf.random.uniform((batch_size, height, width, 3))
110
    tf.train.create_global_step()
111
112
113
114
115
116
117
118
119
120
121
    with slim.arg_scope(nasnet.nasnet_large_arg_scope()):
      net, end_points = nasnet.build_nasnet_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, 4032])

  def testAllEndPointsShapesCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = 10
122
    inputs = tf.random.uniform((batch_size, height, width, 3))
123
    tf.train.create_global_step()
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
      _, end_points = nasnet.build_nasnet_cifar(inputs, num_classes)
    endpoints_shapes = {'Stem': [batch_size, 32, 32, 96],
                        'Cell_0': [batch_size, 32, 32, 192],
                        'Cell_1': [batch_size, 32, 32, 192],
                        'Cell_2': [batch_size, 32, 32, 192],
                        'Cell_3': [batch_size, 32, 32, 192],
                        'Cell_4': [batch_size, 32, 32, 192],
                        'Cell_5': [batch_size, 32, 32, 192],
                        'Cell_6': [batch_size, 16, 16, 384],
                        'Cell_7': [batch_size, 16, 16, 384],
                        'Cell_8': [batch_size, 16, 16, 384],
                        'Cell_9': [batch_size, 16, 16, 384],
                        'Cell_10': [batch_size, 16, 16, 384],
                        'Cell_11': [batch_size, 16, 16, 384],
                        'Cell_12': [batch_size, 8, 8, 768],
                        'Cell_13': [batch_size, 8, 8, 768],
                        'Cell_14': [batch_size, 8, 8, 768],
                        'Cell_15': [batch_size, 8, 8, 768],
                        'Cell_16': [batch_size, 8, 8, 768],
                        'Cell_17': [batch_size, 8, 8, 768],
                        'Reduction_Cell_0': [batch_size, 16, 16, 256],
                        'Reduction_Cell_1': [batch_size, 8, 8, 512],
                        'global_pool': [batch_size, 768],
                        # Logits and predictions
                        'AuxLogits': [batch_size, num_classes],
                        'Logits': [batch_size, num_classes],
                        'Predictions': [batch_size, num_classes]}
    self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
    for endpoint_name in endpoints_shapes:
154
      tf.logging.info('Endpoint name: {}'.format(endpoint_name))
155
156
157
158
159
      expected_shape = endpoints_shapes[endpoint_name]
      self.assertTrue(endpoint_name in end_points)
      self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
                           expected_shape)

pkulzc's avatar
pkulzc committed
160
161
162
163
164
  def testNoAuxHeadCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = 10
    for use_aux_head in (True, False):
165
      tf.reset_default_graph()
166
      inputs = tf.random.uniform((batch_size, height, width, 3))
167
      tf.train.create_global_step()
168
169
      config = nasnet.cifar_config()
      config.set_hparam('use_aux_head', int(use_aux_head))
pkulzc's avatar
pkulzc committed
170
171
      with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
        _, end_points = nasnet.build_nasnet_cifar(inputs, num_classes,
172
                                                  config=config)
pkulzc's avatar
pkulzc committed
173
174
      self.assertEqual('AuxLogits' in end_points, use_aux_head)

175
176
177
178
  def testAllEndPointsShapesMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
179
    inputs = tf.random.uniform((batch_size, height, width, 3))
180
    tf.train.create_global_step()
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
      _, end_points = nasnet.build_nasnet_mobile(inputs, num_classes)
    endpoints_shapes = {'Stem': [batch_size, 28, 28, 88],
                        'Cell_0': [batch_size, 28, 28, 264],
                        'Cell_1': [batch_size, 28, 28, 264],
                        'Cell_2': [batch_size, 28, 28, 264],
                        'Cell_3': [batch_size, 28, 28, 264],
                        'Cell_4': [batch_size, 14, 14, 528],
                        'Cell_5': [batch_size, 14, 14, 528],
                        'Cell_6': [batch_size, 14, 14, 528],
                        'Cell_7': [batch_size, 14, 14, 528],
                        'Cell_8': [batch_size, 7, 7, 1056],
                        'Cell_9': [batch_size, 7, 7, 1056],
                        'Cell_10': [batch_size, 7, 7, 1056],
                        'Cell_11': [batch_size, 7, 7, 1056],
                        'Reduction_Cell_0': [batch_size, 14, 14, 352],
                        'Reduction_Cell_1': [batch_size, 7, 7, 704],
                        'global_pool': [batch_size, 1056],
                        # Logits and predictions
                        'AuxLogits': [batch_size, num_classes],
                        'Logits': [batch_size, num_classes],
                        'Predictions': [batch_size, num_classes]}
    self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
    for endpoint_name in endpoints_shapes:
205
      tf.logging.info('Endpoint name: {}'.format(endpoint_name))
206
207
208
209
210
      expected_shape = endpoints_shapes[endpoint_name]
      self.assertTrue(endpoint_name in end_points)
      self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
                           expected_shape)

pkulzc's avatar
pkulzc committed
211
212
213
214
215
  def testNoAuxHeadMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
    for use_aux_head in (True, False):
216
      tf.reset_default_graph()
217
      inputs = tf.random.uniform((batch_size, height, width, 3))
218
      tf.train.create_global_step()
219
220
      config = nasnet.mobile_imagenet_config()
      config.set_hparam('use_aux_head', int(use_aux_head))
pkulzc's avatar
pkulzc committed
221
222
      with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
        _, end_points = nasnet.build_nasnet_mobile(inputs, num_classes,
223
                                                   config=config)
pkulzc's avatar
pkulzc committed
224
225
      self.assertEqual('AuxLogits' in end_points, use_aux_head)

226
227
228
229
  def testAllEndPointsShapesLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
230
    inputs = tf.random.uniform((batch_size, height, width, 3))
231
    tf.train.create_global_step()
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    with slim.arg_scope(nasnet.nasnet_large_arg_scope()):
      _, end_points = nasnet.build_nasnet_large(inputs, num_classes)
    endpoints_shapes = {'Stem': [batch_size, 42, 42, 336],
                        'Cell_0': [batch_size, 42, 42, 1008],
                        'Cell_1': [batch_size, 42, 42, 1008],
                        'Cell_2': [batch_size, 42, 42, 1008],
                        'Cell_3': [batch_size, 42, 42, 1008],
                        'Cell_4': [batch_size, 42, 42, 1008],
                        'Cell_5': [batch_size, 42, 42, 1008],
                        'Cell_6': [batch_size, 21, 21, 2016],
                        'Cell_7': [batch_size, 21, 21, 2016],
                        'Cell_8': [batch_size, 21, 21, 2016],
                        'Cell_9': [batch_size, 21, 21, 2016],
                        'Cell_10': [batch_size, 21, 21, 2016],
                        'Cell_11': [batch_size, 21, 21, 2016],
                        'Cell_12': [batch_size, 11, 11, 4032],
                        'Cell_13': [batch_size, 11, 11, 4032],
                        'Cell_14': [batch_size, 11, 11, 4032],
                        'Cell_15': [batch_size, 11, 11, 4032],
                        'Cell_16': [batch_size, 11, 11, 4032],
                        'Cell_17': [batch_size, 11, 11, 4032],
                        'Reduction_Cell_0': [batch_size, 21, 21, 1344],
                        'Reduction_Cell_1': [batch_size, 11, 11, 2688],
                        'global_pool': [batch_size, 4032],
                        # Logits and predictions
                        'AuxLogits': [batch_size, num_classes],
                        'Logits': [batch_size, num_classes],
                        'Predictions': [batch_size, num_classes]}
    self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
    for endpoint_name in endpoints_shapes:
262
      tf.logging.info('Endpoint name: {}'.format(endpoint_name))
263
264
265
266
267
      expected_shape = endpoints_shapes[endpoint_name]
      self.assertTrue(endpoint_name in end_points)
      self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
                           expected_shape)

pkulzc's avatar
pkulzc committed
268
269
270
271
272
  def testNoAuxHeadLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
    for use_aux_head in (True, False):
273
      tf.reset_default_graph()
274
      inputs = tf.random.uniform((batch_size, height, width, 3))
275
      tf.train.create_global_step()
276
277
      config = nasnet.large_imagenet_config()
      config.set_hparam('use_aux_head', int(use_aux_head))
pkulzc's avatar
pkulzc committed
278
279
      with slim.arg_scope(nasnet.nasnet_large_arg_scope()):
        _, end_points = nasnet.build_nasnet_large(inputs, num_classes,
280
                                                  config=config)
pkulzc's avatar
pkulzc committed
281
282
      self.assertEqual('AuxLogits' in end_points, use_aux_head)

283
284
285
286
  def testVariablesSetDeviceMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
287
    inputs = tf.random.uniform((batch_size, height, width, 3))
288
    tf.train.create_global_step()
289
    # Force all Variables to reside on the device.
290
    with tf.variable_scope('on_cpu'), tf.device('/cpu:0'):
291
292
      with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
        nasnet.build_nasnet_mobile(inputs, num_classes)
293
    with tf.variable_scope('on_gpu'), tf.device('/gpu:0'):
294
295
      with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
        nasnet.build_nasnet_mobile(inputs, num_classes)
296
297
    for v in tf.get_collection(
        tf.GraphKeys.GLOBAL_VARIABLES, scope='on_cpu'):
298
      self.assertDeviceEqual(v.device, '/cpu:0')
299
300
    for v in tf.get_collection(
        tf.GraphKeys.GLOBAL_VARIABLES, scope='on_gpu'):
301
302
303
304
305
306
307
      self.assertDeviceEqual(v.device, '/gpu:0')

  def testUnknownBatchSizeMobileModel(self):
    batch_size = 1
    height, width = 224, 224
    num_classes = 1000
    with self.test_session() as sess:
308
      inputs = tf.placeholder(tf.float32, (None, height, width, 3))
309
310
311
312
      with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
        logits, _ = nasnet.build_nasnet_mobile(inputs, num_classes)
      self.assertListEqual(logits.get_shape().as_list(),
                           [None, num_classes])
313
      images = tf.random.uniform((batch_size, height, width, 3))
314
      sess.run(tf.global_variables_initializer())
315
316
317
318
319
320
321
322
      output = sess.run(logits, {inputs: images.eval()})
      self.assertEquals(output.shape, (batch_size, num_classes))

  def testEvaluationMobileModel(self):
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    with self.test_session() as sess:
323
      eval_inputs = tf.random.uniform((batch_size, height, width, 3))
324
325
326
327
      with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
        logits, _ = nasnet.build_nasnet_mobile(eval_inputs,
                                               num_classes,
                                               is_training=False)
328
      predictions = tf.argmax(input=logits, axis=1)
329
      sess.run(tf.global_variables_initializer())
330
331
332
      output = sess.run(predictions)
      self.assertEquals(output.shape, (batch_size,))

333
334
335
336
  def testOverrideHParamsCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = 10
337
    inputs = tf.random.uniform((batch_size, height, width, 3))
338
    tf.train.create_global_step()
339
340
341
342
343
344
345
346
347
348
349
350
    config = nasnet.cifar_config()
    config.set_hparam('data_format', 'NCHW')
    with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
      _, end_points = nasnet.build_nasnet_cifar(
          inputs, num_classes, config=config)
    self.assertListEqual(
        end_points['Stem'].shape.as_list(), [batch_size, 96, 32, 32])

  def testOverrideHParamsMobileModel(self):
    batch_size = 5
    height, width = 224, 224
    num_classes = 1000
351
    inputs = tf.random.uniform((batch_size, height, width, 3))
352
    tf.train.create_global_step()
353
354
355
356
357
358
359
360
361
362
363
364
    config = nasnet.mobile_imagenet_config()
    config.set_hparam('data_format', 'NCHW')
    with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()):
      _, end_points = nasnet.build_nasnet_mobile(
          inputs, num_classes, config=config)
    self.assertListEqual(
        end_points['Stem'].shape.as_list(), [batch_size, 88, 28, 28])

  def testOverrideHParamsLargeModel(self):
    batch_size = 5
    height, width = 331, 331
    num_classes = 1000
365
    inputs = tf.random.uniform((batch_size, height, width, 3))
366
    tf.train.create_global_step()
367
368
369
370
371
372
373
374
    config = nasnet.large_imagenet_config()
    config.set_hparam('data_format', 'NCHW')
    with slim.arg_scope(nasnet.nasnet_large_arg_scope()):
      _, end_points = nasnet.build_nasnet_large(
          inputs, num_classes, config=config)
    self.assertListEqual(
        end_points['Stem'].shape.as_list(), [batch_size, 336, 42, 42])

375
376
377
378
  def testCurrentStepCifarModel(self):
    batch_size = 5
    height, width = 32, 32
    num_classes = 10
379
    inputs = tf.random.uniform((batch_size, height, width, 3))
380
    global_step = tf.train.create_global_step()
381
382
383
384
385
386
387
388
389
390
391
392
    with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
      logits, end_points = nasnet.build_nasnet_cifar(inputs,
                                                     num_classes,
                                                     current_step=global_step)
    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])
393

394
395
396
397
398
  def testUseBoundedAcitvationCifarModel(self):
    batch_size = 1
    height, width = 32, 32
    num_classes = 10
    for use_bounded_activation in (True, False):
399
      tf.reset_default_graph()
400
      inputs = tf.random.uniform((batch_size, height, width, 3))
401
402
403
404
405
      config = nasnet.cifar_config()
      config.set_hparam('use_bounded_activation', use_bounded_activation)
      with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()):
        _, _ = nasnet.build_nasnet_cifar(
            inputs, num_classes, config=config)
406
      for node in tf.get_default_graph().as_graph_def().node:
407
408
409
        if node.op.startswith('Relu'):
          self.assertEqual(node.op == 'Relu6', use_bounded_activation)

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