resnet_run_loop.py 32.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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.
# ==============================================================================
"""Contains utility and supporting functions for ResNet.

  This module contains ResNet code which does not directly build layers. This
includes dataset management, hyperparameter and optimizer code, and argument
parsing. Code for defining the ResNet layers can be found in resnet_model.py.
"""

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

26
import functools
Taylor Robie's avatar
Taylor Robie committed
27
import math
Toby Boyd's avatar
Toby Boyd committed
28
import multiprocessing
29
30
import os

31
# pylint: disable=g-bad-import-order
32
from absl import flags
33
import tensorflow as tf
34
35

from official.resnet import resnet_model
36
from official.utils.flags import core as flags_core
37
from official.utils.export import export
38
39
from official.utils.logs import hooks_helper
from official.utils.logs import logger
40
from official.resnet import imagenet_preprocessing
41
from official.utils.misc import distribution_utils
42
from official.utils.misc import model_helpers
43
44
45
46
47


################################################################################
# Functions for input processing.
################################################################################
Toby Boyd's avatar
Toby Boyd committed
48
49
50
51
52
53
54
55
56
def process_record_dataset(dataset,
                           is_training,
                           batch_size,
                           shuffle_buffer,
                           parse_record_fn,
                           num_epochs=1,
                           dtype=tf.float32,
                           datasets_num_private_threads=None,
                           num_parallel_batches=1):
Karmel Allison's avatar
Karmel Allison committed
57
  """Given a Dataset with raw records, return an iterator over the records.
58
59
60
61
62
63
64
65
66
67
68

  Args:
    dataset: A Dataset representing raw records
    is_training: A boolean denoting whether the input is for training.
    batch_size: The number of samples per batch.
    shuffle_buffer: The buffer size to use when shuffling records. A larger
      value results in better randomness, but smaller values reduce startup
      time and use less memory.
    parse_record_fn: A function that takes a raw record and returns the
      corresponding (image, label) pair.
    num_epochs: The number of epochs to repeat the dataset.
69
    dtype: Data type to use for images/features.
Toby Boyd's avatar
Toby Boyd committed
70
71
72
    datasets_num_private_threads: Number of threads for a private
      threadpool created for all datasets computation.
    num_parallel_batches: Number of parallel batches for tf.data.
73
74
75
76

  Returns:
    Dataset of (image, label) pairs ready for iteration.
  """
77
78
79
80
81
82
83
84
  # Defines a specific size thread pool for tf.data operations.
  if datasets_num_private_threads:
    options = tf.data.Options()
    options.experimental_threading.private_threadpool_size = (
        datasets_num_private_threads)
    dataset = dataset.with_options(options)
    tf.compat.v1.logging.info('datasets_num_private_threads: %s',
                              datasets_num_private_threads)
85

86
87
  # Prefetches a batch at a time to smooth out the time taken to load input
  # files for shuffling and processing.
88
89
  dataset = dataset.prefetch(buffer_size=batch_size)
  if is_training:
90
    # Shuffles records before repeating to respect epoch boundaries.
91
92
    dataset = dataset.shuffle(buffer_size=shuffle_buffer)

93
  # Repeats the dataset for the number of epochs to train.
94
95
  dataset = dataset.repeat(num_epochs)

96
  # Parses the raw records into images and labels.
97
  dataset = dataset.apply(
98
      tf.data.experimental.map_and_batch(
99
          lambda value: parse_record_fn(value, is_training, dtype),
100
          batch_size=batch_size,
Toby Boyd's avatar
Toby Boyd committed
101
          num_parallel_batches=num_parallel_batches,
102
          drop_remainder=False))
103
104
105
106

  # Operations between the final prefetch and the get_next call to the iterator
  # will happen synchronously during run time. We prefetch here again to
  # background all of the above processing work and keep it out of the
107
108
109
  # critical training path. Setting buffer_size to tf.contrib.data.AUTOTUNE
  # allows DistributionStrategies to adjust how many batches to fetch based
  # on how many devices are present.
110
  dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
111
112
113
114

  return dataset


Toby Boyd's avatar
Toby Boyd committed
115
116
117
def get_synth_input_fn(height, width, num_channels, num_classes,
                       dtype=tf.float32):
  """Returns an input function that returns a dataset with random data.
118

Toby Boyd's avatar
Toby Boyd committed
119
120
121
122
  This input_fn returns a data set that iterates over a set of random data and
  bypasses all preprocessing, e.g. jpeg decode and copy. The host to device
  copy is still included. This used to find the upper throughput bound when
  tunning the full input pipeline.
123
124
125
126
127
128
129

  Args:
    height: Integer height that will be used to create a fake image tensor.
    width: Integer width that will be used to create a fake image tensor.
    num_channels: Integer depth that will be used to create a fake image tensor.
    num_classes: Number of classes that should be represented in the fake labels
      tensor
Toby Boyd's avatar
Toby Boyd committed
130
    dtype: Data type for features/images.
131
132
133
134
135

  Returns:
    An input_fn that can be used in place of a real one to return a dataset
    that can be used for iteration.
  """
Toby Boyd's avatar
Toby Boyd committed
136
137
138
139
  # pylint: disable=unused-argument
  def input_fn(is_training, data_dir, batch_size, *args, **kwargs):
    """Returns dataset filled with random data."""
    # Synthetic input should be within [0, 255].
140
    inputs = tf.random.truncated_normal(
Toby Boyd's avatar
Toby Boyd committed
141
142
143
144
145
146
        [batch_size] + [height, width, num_channels],
        dtype=dtype,
        mean=127,
        stddev=60,
        name='synthetic_inputs')

147
    labels = tf.random.uniform(
Toby Boyd's avatar
Toby Boyd committed
148
149
150
151
152
153
        [batch_size],
        minval=0,
        maxval=num_classes - 1,
        dtype=tf.int32,
        name='synthetic_labels')
    data = tf.data.Dataset.from_tensors((inputs, labels)).repeat()
154
    data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
Toby Boyd's avatar
Toby Boyd committed
155
    return data
156
157
158
159

  return input_fn


160
def image_bytes_serving_input_fn(image_shape, dtype=tf.float32):
161
162
163
164
165
  """Serving input fn for raw jpeg images."""

  def _preprocess_image(image_bytes):
    """Preprocess a single raw image."""
    # Bounding box around the whole image.
166
    bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=dtype, shape=[1, 1, 4])
167
168
169
170
171
    height, width, num_channels = image_shape
    image = imagenet_preprocessing.preprocess_image(
        image_bytes, bbox, height, width, num_channels, is_training=False)
    return image

172
  image_bytes_list = tf.compat.v1.placeholder(
173
174
      shape=[None], dtype=tf.string, name='input_tensor')
  images = tf.map_fn(
175
      _preprocess_image, image_bytes_list, back_prop=False, dtype=dtype)
176
177
178
179
  return tf.estimator.export.TensorServingInputReceiver(
      images, {'image_bytes': image_bytes_list})


Toby Boyd's avatar
Toby Boyd committed
180
def override_flags_and_set_envars_for_gpu_thread_pool(flags_obj):
Toby Boyd's avatar
Toby Boyd committed
181
  """Override flags and set env_vars for performance.
Toby Boyd's avatar
Toby Boyd committed
182
183
184
185
186
187
188

  These settings exist to test the difference between using stock settings
  and manual tuning. It also shows some of the ENV_VARS that can be tweaked to
  squeeze a few extra examples per second.  These settings are defaulted to the
  current platform of interest, which changes over time.

  On systems with small numbers of cpu cores, e.g. under 8 logical cores,
Toby Boyd's avatar
Toby Boyd committed
189
190
  setting up a gpu thread pool with `tf_gpu_thread_mode=gpu_private` may perform
  poorly.
Toby Boyd's avatar
Toby Boyd committed
191
192
193
194
195

  Args:
    flags_obj: Current flags, which will be adjusted possibly overriding
    what has been set by the user on the command-line.
  """
Toby Boyd's avatar
Toby Boyd committed
196
  cpu_count = multiprocessing.cpu_count()
197
  tf.compat.v1.logging.info('Logical CPU cores: %s', cpu_count)
Toby Boyd's avatar
Toby Boyd committed
198
199
200
201
202
203

  # Sets up thread pool for each GPU for op scheduling.
  per_gpu_thread_count = 1
  total_gpu_thread_count = per_gpu_thread_count * flags_obj.num_gpus
  os.environ['TF_GPU_THREAD_MODE'] = flags_obj.tf_gpu_thread_mode
  os.environ['TF_GPU_THREAD_COUNT'] = str(per_gpu_thread_count)
204
205
206
207
  tf.compat.v1.logging.info('TF_GPU_THREAD_COUNT: %s',
                            os.environ['TF_GPU_THREAD_COUNT'])
  tf.compat.v1.logging.info('TF_GPU_THREAD_MODE: %s',
                            os.environ['TF_GPU_THREAD_MODE'])
Toby Boyd's avatar
Toby Boyd committed
208
209
210
211
212
213
214
215
216

  # Reduces general thread pool by number of threads used for GPU pool.
  main_thread_count = cpu_count - total_gpu_thread_count
  flags_obj.inter_op_parallelism_threads = main_thread_count

  # Sets thread count for tf.data. Logical cores minus threads assign to the
  # private GPU pool along with 2 thread per GPU for event monitoring and
  # sending / receiving tensors.
  num_monitoring_threads = 2 * flags_obj.num_gpus
Toby Boyd's avatar
Toby Boyd committed
217
218
  flags_obj.datasets_num_private_threads = (cpu_count - total_gpu_thread_count
                                            - num_monitoring_threads)
Toby Boyd's avatar
Toby Boyd committed
219
220


221
222
223
224
################################################################################
# Functions for running training/eval/validation loops for the model.
################################################################################
def learning_rate_with_decay(
225
226
    batch_size, batch_denom, num_images, boundary_epochs, decay_rates,
    base_lr=0.1, warmup=False):
227
228
229
230
231
232
233
234
235
236
237
  """Get a learning rate that decays step-wise as training progresses.

  Args:
    batch_size: the number of examples processed in each training batch.
    batch_denom: this value will be used to scale the base learning rate.
      `0.1 * batch size` is divided by this number, such that when
      batch_denom == batch_size, the initial learning rate will be 0.1.
    num_images: total number of images that will be used for training.
    boundary_epochs: list of ints representing the epochs at which we
      decay the learning rate.
    decay_rates: list of floats representing the decay rates to be used
238
239
      for scaling the learning rate. It should have one more element
      than `boundary_epochs`, and all elements should have the same type.
240
241
    base_lr: Initial learning rate scaled based on batch_denom.
    warmup: Run a 5 epoch warmup to the initial lr.
242
243
244
245
246
  Returns:
    Returns a function that takes a single argument - the number of batches
    trained so far (global_step)- and returns the learning rate to be used
    for training the next batch.
  """
247
  initial_learning_rate = base_lr * batch_size / batch_denom
248
249
  batches_per_epoch = num_images / batch_size

Taylor Robie's avatar
Taylor Robie committed
250
251
252
  # Reduce the learning rate at certain epochs.
  # CIFAR-10: divide by 10 at epoch 100, 150, and 200
  # ImageNet: divide by 10 at epoch 30, 60, 80, and 90
253
254
255
256
  boundaries = [int(batches_per_epoch * epoch) for epoch in boundary_epochs]
  vals = [initial_learning_rate * decay for decay in decay_rates]

  def learning_rate_fn(global_step):
257
    """Builds scaled learning rate function with 5 epoch warm up."""
258
    lr = tf.compat.v1.train.piecewise_constant(global_step, boundaries, vals)
259
260
261
262
263
    if warmup:
      warmup_steps = int(batches_per_epoch * 5)
      warmup_lr = (
          initial_learning_rate * tf.cast(global_step, tf.float32) / tf.cast(
              warmup_steps, tf.float32))
264
265
266
      return tf.cond(pred=global_step < warmup_steps,
                     true_fn=lambda: warmup_lr,
                     false_fn=lambda: lr)
267
    return lr
268

pkanwar23's avatar
pkanwar23 committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321


  def poly_rate_fn(global_step):
    """Handles linear scaling rule, gradual warmup, and LR decay.

    The learning rate starts at 0, then it increases linearly per step.  After
    FLAGS.poly_warmup_epochs, we reach the base learning rate (scaled to account
    for batch size). The learning rate is then decayed using a polynomial rate
    decay schedule with power 2.0.

    Args:
    global_step: the current global_step

    Returns:
    returns the current learning rate
    """

    # Learning rate schedule for LARS polynomial schedule
    if flags.FLAGS.batch_size < 8192:
      plr = 5.0
      w_epochs = 5
    elif flags.FLAGS.batch_size < 16384:
      plr = 10.0
      w_epochs = 5
    elif flags.FLAGS.batch_size < 32768:
      plr = 25.0
      w_epochs = 5
    else:
      plr = 32.0
      w_epochs = 14

    w_steps = int(w_epochs * batches_per_epoch)
    wrate = (plr * tf.cast(global_step, tf.float32) / tf.cast(
        w_steps, tf.float32))

    # TODO(pkanwar): use a flag to help calc num_epochs.
    num_epochs = 90
    train_steps = batches_per_epoch * num_epochs

    min_step = tf.constant(1, dtype=tf.int64)
    decay_steps = tf.maximum(min_step, tf.subtract(global_step, w_steps))
    poly_rate = tf.train.polynomial_decay(
        plr,
        decay_steps,
        train_steps - w_steps + 1,
        power=2.0)
    return tf.where(global_step <= w_steps, wrate, poly_rate)

  # For LARS we have a new learning rate schedule
  if flags.FLAGS.enable_lars:
    return poly_rate_fn


322
323
324
325
326
  return learning_rate_fn


def resnet_model_fn(features, labels, mode, model_class,
                    resnet_size, weight_decay, learning_rate_fn, momentum,
327
                    data_format, resnet_version, loss_scale,
Zac Wellmer's avatar
Zac Wellmer committed
328
                    loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE,
pkanwar23's avatar
pkanwar23 committed
329
                    fine_tune=False, label_smoothing=0.0):
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
  """Shared functionality for different resnet model_fns.

  Initializes the ResnetModel representing the model layers
  and uses that model to build the necessary EstimatorSpecs for
  the `mode` in question. For training, this means building losses,
  the optimizer, and the train op that get passed into the EstimatorSpec.
  For evaluation and prediction, the EstimatorSpec is returned without
  a train op, but with the necessary parameters for the given mode.

  Args:
    features: tensor representing input images
    labels: tensor representing class labels for all input images
    mode: current estimator mode; should be one of
      `tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`
    model_class: a class representing a TensorFlow model that has a __call__
      function. We assume here that this is a subclass of ResnetModel.
    resnet_size: A single integer for the size of the ResNet model.
    weight_decay: weight decay loss rate used to regularize learned variables.
    learning_rate_fn: function that returns the current learning rate given
      the current global_step
    momentum: momentum term used for optimization
    data_format: Input format ('channels_last', 'channels_first', or None).
      If set to None, the format is dependent on whether a GPU is available.
353
354
    resnet_version: Integer representing which version of the ResNet network to
      use. See README for details. Valid values: [1, 2]
355
356
    loss_scale: The factor to scale the loss for numerical stability. A detailed
      summary is present in the arg parser help text.
357
358
359
360
    loss_filter_fn: function that takes a string variable name and returns
      True if the var should be included in loss calculation, and False
      otherwise. If None, batch_normalization variables will be excluded
      from the loss.
361
    dtype: the TensorFlow dtype to use for calculations.
Zac Wellmer's avatar
Zac Wellmer committed
362
    fine_tune: If True only train the dense layers(final layers).
363
364
365
366
367
368
369

  Returns:
    EstimatorSpec parameterized according to the input params and the
    current mode.
  """

  # Generate a summary node for the images
370
  tf.compat.v1.summary.image('images', features, max_outputs=6)
371
372
  # Checks that features/images have same data type being used for calculations.
  assert features.dtype == dtype
373

374
375
  model = model_class(resnet_size, data_format, resnet_version=resnet_version,
                      dtype=dtype)
376

377
378
  logits = model(features, mode == tf.estimator.ModeKeys.TRAIN)

379
380
381
382
383
  # This acts as a no-op if the logits are already in fp32 (provided logits are
  # not a SparseTensor). If dtype is is low precision, logits must be cast to
  # fp32 for numerical stability.
  logits = tf.cast(logits, tf.float32)

384
  predictions = {
385
      'classes': tf.argmax(input=logits, axis=1),
386
387
388
389
      'probabilities': tf.nn.softmax(logits, name='softmax_tensor')
  }

  if mode == tf.estimator.ModeKeys.PREDICT:
390
391
392
393
394
395
396
    # Return the predictions and the specification for serving a SavedModel
    return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=predictions,
        export_outputs={
            'predict': tf.estimator.export.PredictOutput(predictions)
        })
397
398

  # Calculate loss, which includes softmax cross entropy and L2 regularization.
pkanwar23's avatar
pkanwar23 committed
399
400
401
402
403
404
405
406
  if label_smoothing != 0.0:
    one_hot_labels = tf.one_hot(labels, 1001)
    cross_entropy = tf.losses.softmax_cross_entropy(
        logits=logits, onehot_labels=one_hot_labels,
        label_smoothing=label_smoothing)
  else:
    cross_entropy = tf.losses.sparse_softmax_cross_entropy(
        logits=logits, labels=labels)
407
408
409

  # Create a tensor named cross_entropy for logging purposes.
  tf.identity(cross_entropy, name='cross_entropy')
410
  tf.compat.v1.summary.scalar('cross_entropy', cross_entropy)
411
412
413

  # If no loss_filter_fn is passed, assume we want the default behavior,
  # which is that batch_normalization variables are excluded from loss.
Karmel Allison's avatar
Karmel Allison committed
414
415
416
  def exclude_batch_norm(name):
    return 'batch_normalization' not in name
  loss_filter_fn = loss_filter_fn or exclude_batch_norm
417

418
419
420
  # Add weight decay to the loss. We need to scale the regularization loss
  # manually as losses other than in tf.losses and tf.keras.losses don't scale
  # automatically.
421
  l2_loss = weight_decay * tf.add_n(
422
      # loss is computed using fp32 for numerical stability.
423
424
      [
          tf.nn.l2_loss(tf.cast(v, tf.float32))
425
          for v in tf.compat.v1.trainable_variables()
426
427
          if loss_filter_fn(v.name)
      ]) / tf.distribute.get_strategy().num_replicas_in_sync
428
  tf.compat.v1.summary.scalar('l2_loss', l2_loss)
429
  loss = cross_entropy + l2_loss
430
431

  if mode == tf.estimator.ModeKeys.TRAIN:
432
    global_step = tf.compat.v1.train.get_or_create_global_step()
433
434
435
436
437

    learning_rate = learning_rate_fn(global_step)

    # Create a tensor named learning_rate for logging purposes
    tf.identity(learning_rate, name='learning_rate')
438
    tf.compat.v1.summary.scalar('learning_rate', learning_rate)
439

pkanwar23's avatar
pkanwar23 committed
440
441
442
443
444
445
446
447
448
449
450
    if flags.FLAGS.enable_lars:
      optimizer = tf.contrib.opt.LARSOptimizer(
          learning_rate,
          momentum=momentum,
          weight_decay=weight_decay,
          skip_list=['batch_normalization', 'bias'])
    else:
      optimizer = tf.compat.v1.train.MomentumOptimizer(
          learning_rate=learning_rate,
          momentum=momentum
      )
451

Zac Wellmer's avatar
Zac Wellmer committed
452
    def _dense_grad_filter(gvs):
453
454
455
456
      """Only apply gradient updates to the final layer.

      This function is used for fine tuning.

Zac Wellmer's avatar
Zac Wellmer committed
457
      Args:
458
        gvs: list of tuples with gradients and variable info
Zac Wellmer's avatar
Zac Wellmer committed
459
      Returns:
460
461
        filtered gradients so that only the dense layer remains
      """
Zac Wellmer's avatar
Zac Wellmer committed
462
463
      return [(g, v) for g, v in gvs if 'dense' in v.name]

464
465
466
467
468
469
    if loss_scale != 1:
      # When computing fp16 gradients, often intermediate tensor values are
      # so small, they underflow to 0. To avoid this, we multiply the loss by
      # loss_scale to make these tensor values loss_scale times bigger.
      scaled_grad_vars = optimizer.compute_gradients(loss * loss_scale)

Zac Wellmer's avatar
Zac Wellmer committed
470
471
472
      if fine_tune:
        scaled_grad_vars = _dense_grad_filter(scaled_grad_vars)

473
474
475
476
477
478
      # Once the gradient computation is complete we can scale the gradients
      # back to the correct scale before passing them to the optimizer.
      unscaled_grad_vars = [(grad / loss_scale, var)
                            for grad, var in scaled_grad_vars]
      minimize_op = optimizer.apply_gradients(unscaled_grad_vars, global_step)
    else:
Zac Wellmer's avatar
Zac Wellmer committed
479
480
481
482
      grad_vars = optimizer.compute_gradients(loss)
      if fine_tune:
        grad_vars = _dense_grad_filter(grad_vars)
      minimize_op = optimizer.apply_gradients(grad_vars, global_step)
483

484
    update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)
485
    train_op = tf.group(minimize_op, update_ops)
486
487
488
  else:
    train_op = None

489
490
491
  accuracy = tf.compat.v1.metrics.accuracy(labels, predictions['classes'])
  accuracy_top_5 = tf.compat.v1.metrics.mean(
      tf.nn.in_top_k(predictions=logits, targets=labels, k=5, name='top_5_op'))
492
493
  metrics = {'accuracy': accuracy,
             'accuracy_top_5': accuracy_top_5}
494
495
496

  # Create a tensor named train_accuracy for logging purposes
  tf.identity(accuracy[1], name='train_accuracy')
497
  tf.identity(accuracy_top_5[1], name='train_accuracy_top_5')
498
499
  tf.compat.v1.summary.scalar('train_accuracy', accuracy[1])
  tf.compat.v1.summary.scalar('train_accuracy_top_5', accuracy_top_5[1])
500
501
502
503
504

  return tf.estimator.EstimatorSpec(
      mode=mode,
      predictions=predictions,
      loss=loss,
505
506
      train_op=train_op,
      eval_metric_ops=metrics)
507
508


509
510
def resnet_main(
    flags_obj, model_function, input_function, dataset_name, shape=None):
511
512
513
  """Shared main loop for ResNet Models.

  Args:
514
515
    flags_obj: An object containing parsed flags. See define_resnet_flags()
      for details.
516
517
518
519
520
    model_function: the function that instantiates the Model and builds the
      ops for train/eval. This will be passed directly into the estimator.
    input_function: the function that processes the dataset and returns a
      dataset that the estimator can train on. This will be wrapped with
      all the relevant flags for running and passed to estimator.
521
522
    dataset_name: the name of the dataset for training and evaluation. This is
      used for logging purpose.
523
    shape: list of ints representing the shape of the images used for training.
524
      This is only used if flags_obj.export_dir is passed.
525
526
527

  Returns:
    Dict of results of the run.
528
  """
Karmel Allison's avatar
Karmel Allison committed
529

530
531
  model_helpers.apply_clean(flags.FLAGS)

Toby Boyd's avatar
Toby Boyd committed
532
  # Ensures flag override logic is only executed if explicitly triggered.
Toby Boyd's avatar
Toby Boyd committed
533
  if flags_obj.tf_gpu_thread_mode:
Toby Boyd's avatar
Toby Boyd committed
534
    override_flags_and_set_envars_for_gpu_thread_pool(flags_obj)
Toby Boyd's avatar
Toby Boyd committed
535

536
537
538
539
  # Configures cluster spec for distribution strategy.
  num_workers = distribution_utils.configure_cluster(flags_obj.worker_hosts,
                                                     flags_obj.task_index)

Toby Boyd's avatar
Toby Boyd committed
540
541
  # Creates session config. allow_soft_placement = True, is required for
  # multi-GPU and is not harmful for other modes.
542
  session_config = tf.compat.v1.ConfigProto(
Toby Boyd's avatar
Toby Boyd committed
543
544
545
      inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads,
      intra_op_parallelism_threads=flags_obj.intra_op_parallelism_threads,
      allow_soft_placement=True)
546

547
  distribution_strategy = distribution_utils.get_distribution_strategy(
548
549
      distribution_strategy=flags_obj.distribution_strategy,
      num_gpus=flags_core.get_num_gpus(flags_obj),
550
      num_workers=num_workers,
551
      all_reduce_alg=flags_obj.all_reduce_alg)
552

Toby Boyd's avatar
Toby Boyd committed
553
  # Creates a `RunConfig` that checkpoints every 24 hours which essentially
Toby Boyd's avatar
Toby Boyd committed
554
  # results in checkpoints determined only by `epochs_between_evals`.
555
556
557
558
  # TODO(ayushd,yuefengz): re-enable checkpointing for multi-worker strategy.
  save_checkpoints_secs = (None if distribution_strategy.__class__.__name__ in
                           ['CollectiveAllReduceStrategy',
                            'MultiWorkerMirroredStrategy'] else 60*60*24)
559
  run_config = tf.estimator.RunConfig(
Toby Boyd's avatar
Toby Boyd committed
560
561
      train_distribute=distribution_strategy,
      session_config=session_config,
562
      save_checkpoints_secs=save_checkpoints_secs,
563
      save_checkpoints_steps=None)
564

Toby Boyd's avatar
Toby Boyd committed
565
  # Initializes model with all but the dense layer from pretrained ResNet.
Zac Wellmer's avatar
Zac Wellmer committed
566
567
568
569
570
571
572
  if flags_obj.pretrained_model_checkpoint_path is not None:
    warm_start_settings = tf.estimator.WarmStartSettings(
        flags_obj.pretrained_model_checkpoint_path,
        vars_to_warm_start='^(?!.*dense)')
  else:
    warm_start_settings = None

573
  classifier = tf.estimator.Estimator(
574
      model_fn=model_function, model_dir=flags_obj.model_dir, config=run_config,
Zac Wellmer's avatar
Zac Wellmer committed
575
      warm_start_from=warm_start_settings, params={
576
577
578
          'resnet_size': int(flags_obj.resnet_size),
          'data_format': flags_obj.data_format,
          'batch_size': flags_obj.batch_size,
579
          'resnet_version': int(flags_obj.resnet_version),
580
          'loss_scale': flags_core.get_loss_scale(flags_obj),
Zac Wellmer's avatar
Zac Wellmer committed
581
582
          'dtype': flags_core.get_tf_dtype(flags_obj),
          'fine_tune': flags_obj.fine_tune
583
584
      })

585
586
587
588
  run_params = {
      'batch_size': flags_obj.batch_size,
      'dtype': flags_core.get_tf_dtype(flags_obj),
      'resnet_size': flags_obj.resnet_size,
589
      'resnet_version': flags_obj.resnet_version,
590
591
592
      'synthetic_data': flags_obj.use_synthetic_data,
      'train_epochs': flags_obj.train_epochs,
  }
593
  if flags_obj.use_synthetic_data:
594
    dataset_name = dataset_name + '-synthetic'
595

596
  benchmark_logger = logger.get_benchmark_logger()
597
598
  benchmark_logger.log_run_info('resnet', dataset_name, run_params,
                                test_id=flags_obj.benchmark_test_id)
599

600
  train_hooks = hooks_helper.get_train_hooks(
601
      flags_obj.hooks,
602
      model_dir=flags_obj.model_dir,
603
      batch_size=flags_obj.batch_size)
604

Taylor Robie's avatar
Taylor Robie committed
605
  def input_fn_train(num_epochs):
606
    return input_function(
Toby Boyd's avatar
Toby Boyd committed
607
608
        is_training=True,
        data_dir=flags_obj.data_dir,
609
        batch_size=distribution_utils.per_device_batch_size(
610
            flags_obj.batch_size, flags_core.get_num_gpus(flags_obj)),
Taylor Robie's avatar
Taylor Robie committed
611
        num_epochs=num_epochs,
Toby Boyd's avatar
Toby Boyd committed
612
613
        dtype=flags_core.get_tf_dtype(flags_obj),
        datasets_num_private_threads=flags_obj.datasets_num_private_threads,
Toby Boyd's avatar
Toby Boyd committed
614
        num_parallel_batches=flags_obj.datasets_num_parallel_batches)
615

616
  def input_fn_eval():
617
    return input_function(
Toby Boyd's avatar
Toby Boyd committed
618
619
        is_training=False,
        data_dir=flags_obj.data_dir,
620
        batch_size=distribution_utils.per_device_batch_size(
621
            flags_obj.batch_size, flags_core.get_num_gpus(flags_obj)),
622
623
        num_epochs=1,
        dtype=flags_core.get_tf_dtype(flags_obj))
Taylor Robie's avatar
Taylor Robie committed
624

625
626
627
  train_epochs = (0 if flags_obj.eval_only or not flags_obj.train_epochs else
                  flags_obj.train_epochs)

628
  use_train_and_evaluate = flags_obj.use_train_and_evaluate or (
629
      distribution_strategy.__class__.__name__ == 'CollectiveAllReduceStrategy')
630
631
632
633
634
635
636
637
638
  if use_train_and_evaluate:
    train_spec = tf.estimator.TrainSpec(
        input_fn=lambda: input_fn_train(train_epochs), hooks=train_hooks,
        max_steps=flags_obj.max_train_steps)
    eval_spec = tf.estimator.EvalSpec(input_fn=input_fn_eval,
                                      steps=flags_obj.max_train_steps)
    tf.compat.v1.logging.info('Starting to train and evaluate.')
    eval_results, _ = tf.estimator.train_and_evaluate(classifier, train_spec,
                                                      eval_spec)
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
639
    benchmark_logger.log_evaluation_result(eval_results)
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
  else:
    if train_epochs == 0:
      # If --eval_only is set, perform a single loop with zero train epochs.
      schedule, n_loops = [0], 1
    else:
      # Compute the number of times to loop while training. All but the last
      # pass will train for `epochs_between_evals` epochs, while the last will
      # train for the number needed to reach `training_epochs`. For instance if
      #   train_epochs = 25 and epochs_between_evals = 10
      # schedule will be set to [10, 10, 5]. That is to say, the loop will:
      #   Train for 10 epochs and then evaluate.
      #   Train for another 10 epochs and then evaluate.
      #   Train for a final 5 epochs (to reach 25 epochs) and then evaluate.
      n_loops = math.ceil(train_epochs / flags_obj.epochs_between_evals)
      schedule = [flags_obj.epochs_between_evals for _ in range(int(n_loops))]
      schedule[-1] = train_epochs - sum(schedule[:-1])  # over counting.

    for cycle_index, num_train_epochs in enumerate(schedule):
      tf.compat.v1.logging.info('Starting cycle: %d/%d', cycle_index,
                                int(n_loops))

      if num_train_epochs:
662
663
664
665
        # Since we are calling classifier.train immediately in each loop, the
        # value of num_train_epochs in the lambda function will not be changed
        # before it is used. So it is safe to ignore the pylint error here
        # pylint: disable=cell-var-from-loop
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        classifier.train(input_fn=lambda: input_fn_train(num_train_epochs),
                         hooks=train_hooks, max_steps=flags_obj.max_train_steps)

      # flags_obj.max_train_steps is generally associated with testing and
      # profiling. As a result it is frequently called with synthetic data,
      # which will iterate forever. Passing steps=flags_obj.max_train_steps
      # allows the eval (which is generally unimportant in those circumstances)
      # to terminate.  Note that eval will run for max_train_steps each loop,
      # regardless of the global_step count.
      tf.compat.v1.logging.info('Starting to evaluate.')
      eval_results = classifier.evaluate(input_fn=input_fn_eval,
                                         steps=flags_obj.max_train_steps)

      benchmark_logger.log_evaluation_result(eval_results)

      if model_helpers.past_stop_threshold(
          flags_obj.stop_threshold, eval_results['accuracy']):
        break
684

685
  if flags_obj.export_dir is not None:
686
    # Exports a saved model for the given classifier.
687
    export_dtype = flags_core.get_tf_dtype(flags_obj)
688
    if flags_obj.image_bytes_as_serving_input:
689
690
      input_receiver_fn = functools.partial(
          image_bytes_serving_input_fn, shape, dtype=export_dtype)
691
692
    else:
      input_receiver_fn = export.build_tensor_serving_input_receiver_fn(
693
694
695
          shape, batch_size=flags_obj.batch_size, dtype=export_dtype)
    classifier.export_savedmodel(flags_obj.export_dir, input_receiver_fn,
                                 strip_default_attrs=True)
696
697
698
699
700
701
702

  stats = {}
  stats['eval_results'] = eval_results
  stats['train_hooks'] = train_hooks

  return stats

703

704
705
706
def define_resnet_flags(resnet_size_choices=None):
  """Add flags and validators for ResNet."""
  flags_core.define_base()
Toby Boyd's avatar
Toby Boyd committed
707
708
709
710
  flags_core.define_performance(num_parallel_calls=False,
                                tf_gpu_thread_mode=True,
                                datasets_num_private_threads=True,
                                datasets_num_parallel_batches=True)
711
712
713
  flags_core.define_image()
  flags_core.define_benchmark()
  flags.adopt_module_key_flags(flags_core)
714

715
  flags.DEFINE_enum(
Toby Boyd's avatar
Toby Boyd committed
716
      name='resnet_version', short_name='rv', default='1',
717
      enum_values=['1', '2'],
718
719
      help=flags_core.help_wrap(
          'Version of ResNet. (1 or 2) See README.md for details.'))
Zac Wellmer's avatar
Zac Wellmer committed
720
721
722
723
724
725
726
727
728
  flags.DEFINE_bool(
      name='fine_tune', short_name='ft', default=False,
      help=flags_core.help_wrap(
          'If True do not train any parameters except for the final layer.'))
  flags.DEFINE_string(
      name='pretrained_model_checkpoint_path', short_name='pmcp', default=None,
      help=flags_core.help_wrap(
          'If not None initialize all the network except the final layer with '
          'these values'))
Taylor Robie's avatar
Taylor Robie committed
729
  flags.DEFINE_boolean(
730
      name='eval_only', default=False,
Taylor Robie's avatar
Taylor Robie committed
731
732
      help=flags_core.help_wrap('Skip training and only perform evaluation on '
                                'the latest checkpoint.'))
733
  flags.DEFINE_boolean(
Toby Boyd's avatar
Toby Boyd committed
734
      name='image_bytes_as_serving_input', default=False,
735
736
737
738
739
740
741
      help=flags_core.help_wrap(
          'If True exports savedmodel with serving signature that accepts '
          'JPEG image bytes instead of a fixed size [HxWxC] tensor that '
          'represents the image. The former is easier to use for serving at '
          'the expense of image resize/cropping being done as part of model '
          'inference. Note, this flag only applies to ImageNet and cannot '
          'be used for CIFAR.'))
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
  flags.DEFINE_boolean(
      name='use_train_and_evaluate', default=False,
      help=flags_core.help_wrap(
          'If True, uses `tf.estimator.train_and_evaluate` for the training '
          'and evaluation loop, instead of separate calls to `classifier.train '
          'and `classifier.evaluate`, which is the default behavior.'))
  flags.DEFINE_string(
      name='worker_hosts', default=None,
      help=flags_core.help_wrap(
          'Comma-separated list of worker ip:port pairs for running '
          'multi-worker models with DistributionStrategy.  The user would '
          'start the program on each host with identical value for this flag.'))
  flags.DEFINE_integer(
      name='task_index', default=-1,
      help=flags_core.help_wrap('If multi-worker training, the task_index of '
                                'this worker.'))
pkanwar23's avatar
pkanwar23 committed
758
759
760
761
762
763
764
765
766
767
768
769
770
  flags.DEFINE_bool(
      name='enable_lars', default=False,
      help=flags_core.help_wrap(
          'Enable LARS optimizer for large batch training.'))
  flags.DEFINE_float(
      name='label_smoothing', default=0.0,
      help=flags_core.help_wrap(
          'Label smoothing parameter used in the softmax_cross_entropy'))
  flags.DEFINE_float(
      name='weight_decay', default=1e-4,
      help=flags_core.help_wrap(
          'Weight decay coefficiant for l2 regularization.'))

771
772
773
  choice_kwargs = dict(
      name='resnet_size', short_name='rs', default='50',
      help=flags_core.help_wrap('The size of the ResNet model to use.'))
774

775
776
777
778
  if resnet_size_choices is None:
    flags.DEFINE_string(**choice_kwargs)
  else:
    flags.DEFINE_enum(enum_values=resnet_size_choices, **choice_kwargs)