imagenet_main.py 13.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.
# ==============================================================================
15
"""Runs a ResNet model on the ImageNet dataset."""
16
17
18
19
20
21
22

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

23
24
from absl import app as absl_app
from absl import flags
25
from absl import logging
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
26
from six.moves import range
27
import tensorflow as tf
28

29
30
31
from official.r1.resnet import imagenet_preprocessing
from official.r1.resnet import resnet_model
from official.r1.resnet import resnet_run_loop
32
from official.utils.flags import core as flags_core
33
from official.utils.logs import logger
34

35
36
37
DEFAULT_IMAGE_SIZE = 224
NUM_CHANNELS = 3
NUM_CLASSES = 1001
38

39
NUM_IMAGES = {
40
41
42
    'train': 1281167,
    'validation': 50000,
}
43

44
_NUM_TRAIN_FILES = 1024
45
_SHUFFLE_BUFFER = 10000
46

47
DATASET_NAME = 'ImageNet'
48

49
50
51
###############################################################################
# Data processing
###############################################################################
52
def get_filenames(is_training, data_dir):
53
54
55
  """Return filenames for dataset."""
  if is_training:
    return [
56
        os.path.join(data_dir, 'train-%05d-of-01024' % i)
57
        for i in range(_NUM_TRAIN_FILES)]
58
59
  else:
    return [
60
        os.path.join(data_dir, 'validation-%05d-of-00128' % i)
Neal Wu's avatar
Neal Wu committed
61
        for i in range(128)]
62
63


64
65
66
def _parse_example_proto(example_serialized):
  """Parses an Example proto containing a training example of an image.

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  The output of the build_image_data.py image preprocessing script is a dataset
  containing serialized Example protocol buffers. Each Example proto contains
  the following fields (values are included as examples):

    image/height: 462
    image/width: 581
    image/colorspace: 'RGB'
    image/channels: 3
    image/class/label: 615
    image/class/synset: 'n03623198'
    image/class/text: 'knee pad'
    image/object/bbox/xmin: 0.1
    image/object/bbox/xmax: 0.9
    image/object/bbox/ymin: 0.2
    image/object/bbox/ymax: 0.6
    image/object/bbox/label: 615
    image/format: 'JPEG'
    image/filename: 'ILSVRC2012_val_00041207.JPEG'
    image/encoded: <JPEG encoded string>
86
87
88
89
90
91
92

  Args:
    example_serialized: scalar Tensor tf.string containing a serialized
      Example protocol buffer.

  Returns:
    image_buffer: Tensor tf.string containing the contents of a JPEG file.
93
94
95
96
    label: Tensor tf.int32 containing the label.
    bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
      where each coordinate is [0, 1) and the coordinates are arranged as
      [ymin, xmin, ymax, xmax].
97
98
99
  """
  # Dense features in Example proto.
  feature_map = {
100
      'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string,
101
                                             default_value=''),
102
103
104
105
      'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64,
                                                 default_value=-1),
      'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string,
                                                default_value=''),
106
  }
107
  sparse_float32 = tf.io.VarLenFeature(dtype=tf.float32)
108
109
110
111
112
113
  # Sparse features in Example proto.
  feature_map.update(
      {k: sparse_float32 for k in ['image/object/bbox/xmin',
                                   'image/object/bbox/ymin',
                                   'image/object/bbox/xmax',
                                   'image/object/bbox/ymax']})
114

115
116
  features = tf.io.parse_single_example(serialized=example_serialized,
                                        features=feature_map)
117
  label = tf.cast(features['image/class/label'], dtype=tf.int32)
118

119
120
121
122
123
124
125
126
127
128
129
  xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0)
  ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0)
  xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0)
  ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0)

  # Note that we impose an ordering of (y, x) just to make life difficult.
  bbox = tf.concat([ymin, xmin, ymax, xmax], 0)

  # Force the variable number of bounding boxes into the shape
  # [1, num_boxes, coords].
  bbox = tf.expand_dims(bbox, 0)
130
  bbox = tf.transpose(a=bbox, perm=[0, 2, 1])
131
132

  return features['image/encoded'], label, bbox
133
134


135
def parse_record(raw_record, is_training, dtype):
136
137
138
139
140
141
142
143
144
  """Parses a record containing a training example of an image.

  The input record is parsed into a label and image, and the image is passed
  through preprocessing steps (cropping, flipping, and so on).

  Args:
    raw_record: scalar Tensor tf.string containing a serialized
      Example protocol buffer.
    is_training: A boolean denoting whether the input is for training.
145
    dtype: data type to use for images/features.
146

147
148
  Returns:
    Tuple with processed image tensor and one-hot-encoded label tensor.
149
150
151
152
153
154
  """
  image_buffer, label, bbox = _parse_example_proto(raw_record)

  image = imagenet_preprocessing.preprocess_image(
      image_buffer=image_buffer,
      bbox=bbox,
155
156
157
      output_height=DEFAULT_IMAGE_SIZE,
      output_width=DEFAULT_IMAGE_SIZE,
      num_channels=NUM_CHANNELS,
158
      is_training=is_training)
159
  image = tf.cast(image, dtype)
160

161
  return image, label
162
163


164
165
166
167
168
169
170
def input_fn(is_training,
             data_dir,
             batch_size,
             num_epochs=1,
             dtype=tf.float32,
             datasets_num_private_threads=None,
             parse_record_fn=parse_record,
171
             input_context=None,
172
             drop_remainder=False,
Rachel Lim's avatar
Rachel Lim committed
173
             tf_data_experimental_slack=False):
174
  """Input function which provides batches for train or eval.
Karmel Allison's avatar
Karmel Allison committed
175

176
177
178
179
180
  Args:
    is_training: A boolean denoting whether the input is for training.
    data_dir: The directory containing the input data.
    batch_size: The number of samples per batch.
    num_epochs: The number of epochs to repeat the dataset.
181
    dtype: Data type to use for images/features
Toby Boyd's avatar
Toby Boyd committed
182
    datasets_num_private_threads: Number of private threads for tf.data.
Priya Gupta's avatar
Priya Gupta committed
183
    parse_record_fn: Function to use for parsing the records.
184
185
    input_context: A `tf.distribute.InputContext` object passed in by
      `tf.distribute.Strategy`.
186
187
    drop_remainder: A boolean indicates whether to drop the remainder of the
      batches. If True, the batch dimension will be static.
188
189
    tf_data_experimental_slack: Whether to enable tf.data's
      `experimental_slack` option.
190
191
192
193
194
195

  Returns:
    A dataset that can be used for iteration.
  """
  filenames = get_filenames(is_training, data_dir)
  dataset = tf.data.Dataset.from_tensor_slices(filenames)
196

197
  if input_context:
198
    logging.info(
199
200
        'Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d',
        input_context.input_pipeline_id, input_context.num_input_pipelines)
201
202
203
    dataset = dataset.shard(input_context.num_input_pipelines,
                            input_context.input_pipeline_id)

204
  if is_training:
205
206
    # Shuffle the input files
    dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES)
207

208
  # Convert to individual records.
Haoyu Zhang's avatar
Haoyu Zhang committed
209
210
211
212
213
214
215
  # cycle_length = 10 means that up to 10 files will be read and deserialized in
  # parallel. You may want to increase this number if you have a large number of
  # CPU cores.
  dataset = dataset.interleave(
      tf.data.TFRecordDataset,
      cycle_length=10,
      num_parallel_calls=tf.data.experimental.AUTOTUNE)
216

217
  return resnet_run_loop.process_record_dataset(
Taylor Robie's avatar
Taylor Robie committed
218
219
220
221
      dataset=dataset,
      is_training=is_training,
      batch_size=batch_size,
      shuffle_buffer=_SHUFFLE_BUFFER,
Priya Gupta's avatar
Priya Gupta committed
222
      parse_record_fn=parse_record_fn,
Taylor Robie's avatar
Taylor Robie committed
223
      num_epochs=num_epochs,
Toby Boyd's avatar
Toby Boyd committed
224
225
      dtype=dtype,
      datasets_num_private_threads=datasets_num_private_threads,
226
227
      drop_remainder=drop_remainder,
      tf_data_experimental_slack=tf_data_experimental_slack,
228
  )
229
230


Toby Boyd's avatar
Toby Boyd committed
231
def get_synth_input_fn(dtype):
232
  return resnet_run_loop.get_synth_input_fn(
233
      DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_SIZE, NUM_CHANNELS, NUM_CLASSES,
Toby Boyd's avatar
Toby Boyd committed
234
      dtype=dtype)
235
236


237
238
239
###############################################################################
# Running the model
###############################################################################
240
class ImagenetModel(resnet_model.Model):
Karmel Allison's avatar
Karmel Allison committed
241
  """Model class with appropriate defaults for Imagenet data."""
242

243
  def __init__(self, resnet_size, data_format=None, num_classes=NUM_CLASSES,
244
               resnet_version=resnet_model.DEFAULT_VERSION,
245
               dtype=resnet_model.DEFAULT_DTYPE):
Neal Wu's avatar
Neal Wu committed
246
247
248
249
250
251
252
    """These are the parameters that work for Imagenet data.

    Args:
      resnet_size: The number of convolutional layers needed in the model.
      data_format: Either 'channels_first' or 'channels_last', specifying which
        data format to use when setting up the model.
      num_classes: The number of output classes needed from the model. This
253
        enables users to extend the same model to their own datasets.
254
255
      resnet_version: Integer representing which version of the ResNet network
        to use. See README for details. Valid values: [1, 2]
256
      dtype: The TensorFlow dtype to use for calculations.
Neal Wu's avatar
Neal Wu committed
257
    """
258
259
260

    # For bigger models, we want to use "bottleneck" layers
    if resnet_size < 50:
261
      bottleneck = False
262
    else:
263
      bottleneck = True
264
265
266

    super(ImagenetModel, self).__init__(
        resnet_size=resnet_size,
267
        bottleneck=bottleneck,
268
        num_classes=num_classes,
269
270
271
272
273
274
275
        num_filters=64,
        kernel_size=7,
        conv_stride=2,
        first_pool_size=3,
        first_pool_stride=2,
        block_sizes=_get_block_sizes(resnet_size),
        block_strides=[1, 2, 2, 2],
276
        resnet_version=resnet_version,
277
278
279
        data_format=data_format,
        dtype=dtype
    )
280
281
282


def _get_block_sizes(resnet_size):
Karmel Allison's avatar
Karmel Allison committed
283
284
285
  """Retrieve the size of each block_layer in the ResNet model.

  The number of block layers used for the Resnet model varies according
286
287
  to the size of the model. This helper grabs the layer set we want, throwing
  an error if a non-standard size has been selected.
Karmel Allison's avatar
Karmel Allison committed
288
289
290
291
292
293
294
295
296

  Args:
    resnet_size: The number of convolutional layers needed in the model.

  Returns:
    A list of block sizes to use in building the model.

  Raises:
    KeyError: if invalid resnet_size is received.
297
298
299
300
301
302
303
304
  """
  choices = {
      18: [2, 2, 2, 2],
      34: [3, 4, 6, 3],
      50: [3, 4, 6, 3],
      101: [3, 4, 23, 3],
      152: [3, 8, 36, 3],
      200: [3, 24, 36, 3]
305
306
  }

307
308
309
310
311
  try:
    return choices[resnet_size]
  except KeyError:
    err = ('Could not find layers for selected Resnet size.\n'
           'Size received: {}; sizes allowed: {}.'.format(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
312
               resnet_size, list(choices.keys())))
313
    raise ValueError(err)
314
315


316
317
def imagenet_model_fn(features, labels, mode, params):
  """Our model_fn for ResNet to be used with our Estimator."""
318
319
320
321
322
323
324
325
326
327

  # Warmup and higher lr may not be valid for fine tuning with small batches
  # and smaller numbers of training images.
  if params['fine_tune']:
    warmup = False
    base_lr = .1
  else:
    warmup = True
    base_lr = .128

328
  learning_rate_fn = resnet_run_loop.learning_rate_with_decay(
329
330
331
332
      batch_size=params['batch_size'] * params.get('num_workers', 1),
      batch_denom=256, num_images=NUM_IMAGES['train'],
      boundary_epochs=[30, 60, 80, 90], decay_rates=[1, 0.1, 0.01, 0.001, 1e-4],
      warmup=warmup, base_lr=base_lr)
333

334
335
336
337
338
339
  return resnet_run_loop.resnet_model_fn(
      features=features,
      labels=labels,
      mode=mode,
      model_class=ImagenetModel,
      resnet_size=params['resnet_size'],
pkanwar23's avatar
pkanwar23 committed
340
      weight_decay=flags.FLAGS.weight_decay,
341
342
343
      learning_rate_fn=learning_rate_fn,
      momentum=0.9,
      data_format=params['data_format'],
344
      resnet_version=params['resnet_version'],
345
346
      loss_scale=params['loss_scale'],
      loss_filter_fn=None,
Zac Wellmer's avatar
Zac Wellmer committed
347
      dtype=params['dtype'],
pkanwar23's avatar
pkanwar23 committed
348
349
      fine_tune=params['fine_tune'],
      label_smoothing=flags.FLAGS.label_smoothing
350
  )
351
352


353
def define_imagenet_flags():
354
  resnet_run_loop.define_resnet_flags(
355
      resnet_size_choices=['18', '34', '50', '101', '152', '200'],
356
357
      dynamic_loss_scale=True,
      fp16_implementation=True)
358
  flags.adopt_module_key_flags(resnet_run_loop)
Toby Boyd's avatar
Toby Boyd committed
359
  flags_core.set_defaults(train_epochs=90)
360

361

362
363
364
365
366
def run_imagenet(flags_obj):
  """Run ResNet ImageNet training and eval loop.

  Args:
    flags_obj: An object containing parsed flag values.
367
368
369
370
371
372

  Returns:
    Dict of results of the run.  Contains the keys `eval_results` and
      `train_hooks`. `eval_results` contains accuracy (top_1) and
      accuracy_top_5. `train_hooks` is a list the instances of hooks used during
      training.
373
  """
Toby Boyd's avatar
Toby Boyd committed
374
375
376
  input_function = (flags_obj.use_synthetic_data and
                    get_synth_input_fn(flags_core.get_tf_dtype(flags_obj)) or
                    input_fn)
377

378
  result = resnet_run_loop.resnet_main(
379
      flags_obj, imagenet_model_fn, input_function, DATASET_NAME,
380
      shape=[DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_SIZE, NUM_CHANNELS])
381

382
383
  return result

384

385
def main(_):
386
387
  with logger.benchmark_context(flags.FLAGS):
    run_imagenet(flags.FLAGS)
388
389


390
if __name__ == '__main__':
391
  logging.set_verbosity(logging.INFO)
392
  define_imagenet_flags()
393
  absl_app.run(main)