model_lib_v2.py 48.8 KB
Newer Older
pkulzc's avatar
pkulzc committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Copyright 2019 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.
# ==============================================================================
r"""Constructs model, inputs, and training environment."""

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

import copy
22
import os
23
import pprint
pkulzc's avatar
pkulzc committed
24
25
import time

26
import numpy as np
27
import tensorflow.compat.v1 as tf
pkulzc's avatar
pkulzc committed
28
29
30
31
32
33

from object_detection import eval_util
from object_detection import inputs
from object_detection import model_lib
from object_detection.builders import optimizer_builder
from object_detection.core import standard_fields as fields
34
from object_detection.protos import train_pb2
pkulzc's avatar
pkulzc committed
35
36
37
from object_detection.utils import config_util
from object_detection.utils import label_map_util
from object_detection.utils import ops
38
from object_detection.utils import variables_helper
39
40
from object_detection.utils import visualization_utils as vutils

pkulzc's avatar
pkulzc committed
41
42

MODEL_BUILD_UTIL_MAP = model_lib.MODEL_BUILD_UTIL_MAP
43
NUM_STEPS_PER_ITERATION = 100
44
LOG_EVERY = 100
pkulzc's avatar
pkulzc committed
45
46


47
48
49
50
51
52
RESTORE_MAP_ERROR_TEMPLATE = (
    'Since we are restoring a v2 style checkpoint'
    ' restore_map was expected to return a (str -> Model) mapping,'
    ' but we received a ({} -> {}) mapping instead.'
)

pkulzc's avatar
pkulzc committed
53
54

def _compute_losses_and_predictions_dicts(
55
    model, features, labels, training_step=None,
56
    add_regularization_loss=True):
pkulzc's avatar
pkulzc committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  """Computes the losses dict and predictions dict for a model on inputs.

  Args:
    model: a DetectionModel (based on Keras).
    features: Dictionary of feature tensors from the input dataset.
      Should be in the format output by `inputs.train_input` and
      `inputs.eval_input`.
        features[fields.InputDataFields.image] is a [batch_size, H, W, C]
          float32 tensor with preprocessed images.
        features[HASH_KEY] is a [batch_size] int32 tensor representing unique
          identifiers for the images.
        features[fields.InputDataFields.true_image_shape] is a [batch_size, 3]
          int32 tensor representing the true image shapes, as preprocessed
          images could be padded.
        features[fields.InputDataFields.original_image] (optional) is a
          [batch_size, H, W, C] float32 tensor with original images.
    labels: A dictionary of groundtruth tensors post-unstacking. The original
      labels are of the form returned by `inputs.train_input` and
      `inputs.eval_input`. The shapes may have been modified by unstacking with
      `model_lib.unstack_batch`. However, the dictionary includes the following
      fields.
        labels[fields.InputDataFields.num_groundtruth_boxes] is a
          int32 tensor indicating the number of valid groundtruth boxes
          per image.
        labels[fields.InputDataFields.groundtruth_boxes] is a float32 tensor
          containing the corners of the groundtruth boxes.
        labels[fields.InputDataFields.groundtruth_classes] is a float32
          one-hot tensor of classes.
        labels[fields.InputDataFields.groundtruth_weights] is a float32 tensor
          containing groundtruth weights for the boxes.
        -- Optional --
        labels[fields.InputDataFields.groundtruth_instance_masks] is a
          float32 tensor containing only binary values, which represent
          instance masks for objects.
91
92
        labels[fields.InputDataFields.groundtruth_instance_mask_weights] is a
          float32 tensor containing weights for the instance masks.
pkulzc's avatar
pkulzc committed
93
94
        labels[fields.InputDataFields.groundtruth_keypoints] is a
          float32 tensor containing keypoints for each box.
95
96
97
98
99
100
        labels[fields.InputDataFields.groundtruth_dp_num_points] is an int32
          tensor with the number of sampled DensePose points per object.
        labels[fields.InputDataFields.groundtruth_dp_part_ids] is an int32
          tensor with the DensePose part ids (0-indexed) per object.
        labels[fields.InputDataFields.groundtruth_dp_surface_coords] is a
          float32 tensor with the DensePose surface coordinates.
101
102
103
104
        labels[fields.InputDataFields.groundtruth_group_of] is a tf.bool tensor
          containing group_of annotations.
        labels[fields.InputDataFields.groundtruth_labeled_classes] is a float32
          k-hot tensor of classes.
105
106
        labels[fields.InputDataFields.groundtruth_track_ids] is a int32
          tensor of track IDs.
107
108
109
110
        labels[fields.InputDataFields.groundtruth_keypoint_depths] is a
          float32 tensor containing keypoint depths information.
        labels[fields.InputDataFields.groundtruth_keypoint_depth_weights] is a
          float32 tensor containing the weights of the keypoint depth feature.
111
    training_step: int, the current training step.
pkulzc's avatar
pkulzc committed
112
113
114
115
116
117
118
119
120
    add_regularization_loss: Whether or not to include the model's
      regularization loss in the losses dictionary.

  Returns:
    A tuple containing the losses dictionary (with the total loss under
    the key 'Loss/total_loss'), and the predictions dictionary produced by
    `model.predict`.

  """
121
  model_lib.provide_groundtruth(model, labels, training_step=training_step)
pkulzc's avatar
pkulzc committed
122
123
  preprocessed_images = features[fields.InputDataFields.image]

124
125
  prediction_dict = model.predict(
      preprocessed_images,
Kaushik Shivakumar's avatar
Kaushik Shivakumar committed
126
127
      features[fields.InputDataFields.true_image_shape],
      **model.get_side_inputs(features))
128
  prediction_dict = ops.bfloat16_to_float32_nested(prediction_dict)
pkulzc's avatar
pkulzc committed
129
130
131
132
133
134
135
136
137
138

  losses_dict = model.loss(
      prediction_dict, features[fields.InputDataFields.true_image_shape])
  losses = [loss_tensor for loss_tensor in losses_dict.values()]
  if add_regularization_loss:
    # TODO(kaftan): As we figure out mixed precision & bfloat 16, we may
    ## need to convert these regularization losses from bfloat16 to float32
    ## as well.
    regularization_losses = model.regularization_losses()
    if regularization_losses:
139
140
      regularization_losses = ops.bfloat16_to_float32_nested(
          regularization_losses)
pkulzc's avatar
pkulzc committed
141
142
143
144
145
146
147
148
149
150
151
      regularization_loss = tf.add_n(
          regularization_losses, name='regularization_loss')
      losses.append(regularization_loss)
      losses_dict['Loss/regularization_loss'] = regularization_loss

  total_loss = tf.add_n(losses, name='total_loss')
  losses_dict['Loss/total_loss'] = total_loss

  return losses_dict, prediction_dict


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def _ensure_model_is_built(model, input_dataset, unpad_groundtruth_tensors):
  """Ensures that model variables are all built, by running on a dummy input.

  Args:
    model: A DetectionModel to be built.
    input_dataset: The tf.data Dataset the model is being trained on. Needed to
      get the shapes for the dummy loss computation.
    unpad_groundtruth_tensors: A parameter passed to unstack_batch.
  """
  features, labels = iter(input_dataset).next()

  @tf.function
  def _dummy_computation_fn(features, labels):
    model._is_training = False  # pylint: disable=protected-access
    tf.keras.backend.set_learning_phase(False)

    labels = model_lib.unstack_batch(
        labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors)

171
172
    return _compute_losses_and_predictions_dicts(model, features, labels,
                                                 training_step=0)
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

  strategy = tf.compat.v2.distribute.get_strategy()
  if hasattr(tf.distribute.Strategy, 'run'):
    strategy.run(
        _dummy_computation_fn, args=(
            features,
            labels,
        ))
  else:
    strategy.experimental_run_v2(
        _dummy_computation_fn, args=(
            features,
            labels,
        ))


189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def normalize_dict(values_dict, num_replicas):

  num_replicas = tf.constant(num_replicas, dtype=tf.float32)
  return {key: tf.math.divide(loss, num_replicas) for key, loss
          in values_dict.items()}


def reduce_dict(strategy, reduction_dict, reduction_op):
  # TODO(anjalisridhar): explore if it is safe to remove the # num_replicas
  # scaling of the loss and switch this to a ReduceOp.Mean
  return {
      name: strategy.reduce(reduction_op, loss, axis=None)
      for name, loss in reduction_dict.items()
  }


pkulzc's avatar
pkulzc committed
205
206
207
208
209
210
211
212
213
# TODO(kaftan): Explore removing learning_rate from this method & returning
## The full losses dict instead of just total_loss, then doing all summaries
## saving in a utility method called by the outer training loop.
# TODO(kaftan): Explore adding gradient summaries
def eager_train_step(detection_model,
                     features,
                     labels,
                     unpad_groundtruth_tensors,
                     optimizer,
214
                     training_step,
pkulzc's avatar
pkulzc committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
                     add_regularization_loss=True,
                     clip_gradients_value=None,
                     num_replicas=1.0):
  """Process a single training batch.

  This method computes the loss for the model on a single training batch,
  while tracking the gradients with a gradient tape. It then updates the
  model variables with the optimizer, clipping the gradients if
  clip_gradients_value is present.

  This method can run eagerly or inside a tf.function.

  Args:
    detection_model: A DetectionModel (based on Keras) to train.
    features: Dictionary of feature tensors from the input dataset.
      Should be in the format output by `inputs.train_input.
        features[fields.InputDataFields.image] is a [batch_size, H, W, C]
          float32 tensor with preprocessed images.
        features[HASH_KEY] is a [batch_size] int32 tensor representing unique
          identifiers for the images.
        features[fields.InputDataFields.true_image_shape] is a [batch_size, 3]
          int32 tensor representing the true image shapes, as preprocessed
          images could be padded.
        features[fields.InputDataFields.original_image] (optional, not used
          during training) is a
          [batch_size, H, W, C] float32 tensor with original images.
    labels: A dictionary of groundtruth tensors. This method unstacks
      these labels using model_lib.unstack_batch. The stacked labels are of
      the form returned by `inputs.train_input` and `inputs.eval_input`.
        labels[fields.InputDataFields.num_groundtruth_boxes] is a [batch_size]
          int32 tensor indicating the number of valid groundtruth boxes
          per image.
        labels[fields.InputDataFields.groundtruth_boxes] is a
          [batch_size, num_boxes, 4] float32 tensor containing the corners of
          the groundtruth boxes.
        labels[fields.InputDataFields.groundtruth_classes] is a
          [batch_size, num_boxes, num_classes] float32 one-hot tensor of
          classes. num_classes includes the background class.
        labels[fields.InputDataFields.groundtruth_weights] is a
          [batch_size, num_boxes] float32 tensor containing groundtruth weights
          for the boxes.
        -- Optional --
        labels[fields.InputDataFields.groundtruth_instance_masks] is a
          [batch_size, num_boxes, H, W] float32 tensor containing only binary
          values, which represent instance masks for objects.
260
261
262
        labels[fields.InputDataFields.groundtruth_instance_mask_weights] is a
          [batch_size, num_boxes] float32 tensor containing weights for the
          instance masks.
pkulzc's avatar
pkulzc committed
263
264
265
        labels[fields.InputDataFields.groundtruth_keypoints] is a
          [batch_size, num_boxes, num_keypoints, 2] float32 tensor containing
          keypoints for each box.
266
267
268
269
270
271
272
273
274
275
276
        labels[fields.InputDataFields.groundtruth_dp_num_points] is a
          [batch_size, num_boxes] int32 tensor with the number of DensePose
          sampled points per instance.
        labels[fields.InputDataFields.groundtruth_dp_part_ids] is a
          [batch_size, num_boxes, max_sampled_points] int32 tensor with the
          part ids (0-indexed) for each instance.
        labels[fields.InputDataFields.groundtruth_dp_surface_coords] is a
          [batch_size, num_boxes, max_sampled_points, 4] float32 tensor with the
          surface coordinates for each point. Each surface coordinate is of the
          form (y, x, v, u) where (y, x) are normalized image locations and
          (v, u) are part-relative normalized surface coordinates.
277
278
        labels[fields.InputDataFields.groundtruth_labeled_classes] is a float32
          k-hot tensor of classes.
279
280
        labels[fields.InputDataFields.groundtruth_track_ids] is a int32
          tensor of track IDs.
281
282
283
284
        labels[fields.InputDataFields.groundtruth_keypoint_depths] is a
          float32 tensor containing keypoint depths information.
        labels[fields.InputDataFields.groundtruth_keypoint_depth_weights] is a
          float32 tensor containing the weights of the keypoint depth feature.
pkulzc's avatar
pkulzc committed
285
286
    unpad_groundtruth_tensors: A parameter passed to unstack_batch.
    optimizer: The training optimizer that will update the variables.
287
    training_step: int, the training step number.
pkulzc's avatar
pkulzc committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    add_regularization_loss: Whether or not to include the model's
      regularization loss in the losses dictionary.
    clip_gradients_value: If this is present, clip the gradients global norm
      at this value using `tf.clip_by_global_norm`.
    num_replicas: The number of replicas in the current distribution strategy.
      This is used to scale the total loss so that training in a distribution
      strategy works correctly.

  Returns:
    The total loss observed at this training step
  """
  # """Execute a single training step in the TF v2 style loop."""
  is_training = True

  detection_model._is_training = is_training  # pylint: disable=protected-access
  tf.keras.backend.set_learning_phase(is_training)

  labels = model_lib.unstack_batch(
      labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors)

  with tf.GradientTape() as tape:
    losses_dict, _ = _compute_losses_and_predictions_dicts(
310
311
312
        detection_model, features, labels,
        training_step=training_step,
        add_regularization_loss=add_regularization_loss)
pkulzc's avatar
pkulzc committed
313

314
    losses_dict = normalize_dict(losses_dict, num_replicas)
pkulzc's avatar
pkulzc committed
315
316
317

  trainable_variables = detection_model.trainable_variables

318
  total_loss = losses_dict['Loss/total_loss']
pkulzc's avatar
pkulzc committed
319
320
321
322
323
  gradients = tape.gradient(total_loss, trainable_variables)

  if clip_gradients_value:
    gradients, _ = tf.clip_by_global_norm(gradients, clip_gradients_value)
  optimizer.apply_gradients(zip(gradients, trainable_variables))
324
325

  return losses_dict
pkulzc's avatar
pkulzc committed
326
327


328
329
330
331
def validate_tf_v2_checkpoint_restore_map(checkpoint_restore_map):
  """Ensure that given dict is a valid TF v2 style restore map.

  Args:
332
333
    checkpoint_restore_map: A nested dict mapping strings to
      tf.keras.Model objects.
334
335
336
337
338
339
340
341

  Raises:
    ValueError: If they keys in checkpoint_restore_map are not strings or if
      the values are not keras Model objects.

  """

  for key, value in checkpoint_restore_map.items():
342
343
344
    if not (isinstance(key, str) and
            (isinstance(value, tf.Module)
             or isinstance(value, tf.train.Checkpoint))):
345
346
347
348
349
350
      if isinstance(key, str) and isinstance(value, dict):
        validate_tf_v2_checkpoint_restore_map(value)
      else:
        raise TypeError(
            RESTORE_MAP_ERROR_TEMPLATE.format(key.__class__.__name__,
                                              value.__class__.__name__))
351
352


353
354
355
356
357
358
def is_object_based_checkpoint(checkpoint_path):
  """Returns true if `checkpoint_path` points to an object-based checkpoint."""
  var_names = [var[0] for var in tf.train.list_variables(checkpoint_path)]
  return '_CHECKPOINTABLE_OBJECT_GRAPH' in var_names


359
360
361
def load_fine_tune_checkpoint(model, checkpoint_path, checkpoint_type,
                              checkpoint_version, run_model_on_dummy_input,
                              input_dataset, unpad_groundtruth_tensors):
pkulzc's avatar
pkulzc committed
362
363
364
365
366
367
  """Load a fine tuning classification or detection checkpoint.

  To make sure the model variables are all built, this method first executes
  the model by computing a dummy loss. (Models might not have built their
  variables before their first execution)

368
  It then loads an object-based classification or detection checkpoint.
pkulzc's avatar
pkulzc committed
369
370
371
372
373
374
375
376
377
378
379

  This method updates the model in-place and does not return a value.

  Args:
    model: A DetectionModel (based on Keras) to load a fine-tuning
      checkpoint for.
    checkpoint_path: Directory with checkpoints file or path to checkpoint.
    checkpoint_type: Whether to restore from a full detection
      checkpoint (with compatible variable names) or to restore from a
      classification checkpoint for initialization prior to training.
      Valid values: `detection`, `classification`.
380
    checkpoint_version: train_pb2.CheckpointVersion.V1 or V2 enum indicating
381
382
      whether to load checkpoints in V1 style or V2 style.  In this binary
      we only support V2 style (object-based) checkpoints.
383
384
385
    run_model_on_dummy_input: Whether to run the model on a dummy input in order
      to ensure that all model variables have been built successfully before
      loading the fine_tune_checkpoint.
pkulzc's avatar
pkulzc committed
386
387
388
    input_dataset: The tf.data Dataset the model is being trained on. Needed
      to get the shapes for the dummy loss computation.
    unpad_groundtruth_tensors: A parameter passed to unstack_batch.
389
390
391
392
393

  Raises:
    IOError: if `checkpoint_path` does not point at a valid object-based
      checkpoint
    ValueError: if `checkpoint_version` is not train_pb2.CheckpointVersion.V2
pkulzc's avatar
pkulzc committed
394
  """
395
396
397
398
399
  if not is_object_based_checkpoint(checkpoint_path):
    raise IOError('Checkpoint is expected to be an object-based checkpoint.')
  if checkpoint_version == train_pb2.CheckpointVersion.V1:
    raise ValueError('Checkpoint version should be V2')

400
401
  if run_model_on_dummy_input:
    _ensure_model_is_built(model, input_dataset, unpad_groundtruth_tensors)
402

403
404
405
406
  restore_from_objects_dict = model.restore_from_objects(
      fine_tune_checkpoint_type=checkpoint_type)
  validate_tf_v2_checkpoint_restore_map(restore_from_objects_dict)
  ckpt = tf.train.Checkpoint(**restore_from_objects_dict)
407
408
  ckpt.restore(
      checkpoint_path).expect_partial().assert_existing_objects_matched()
409
410


411
def get_filepath(strategy, filepath):
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
  """Get appropriate filepath for worker.

  Args:
    strategy: A tf.distribute.Strategy object.
    filepath: A path to where the Checkpoint object is stored.

  Returns:
    A temporary filepath for non-chief workers to use or the original filepath
    for the chief.
  """
  if strategy.extended.should_checkpoint:
    return filepath
  else:
    # TODO(vighneshb) Replace with the public API when TF exposes it.
    task_id = strategy.extended._task_id  # pylint:disable=protected-access
    return os.path.join(filepath, 'temp_worker_{:03d}'.format(task_id))


430
def clean_temporary_directories(strategy, filepath):
431
432
433
434
435
436
437
438
439
440
441
  """Temporary directory clean up for MultiWorker Mirrored Strategy.

  This is needed for all non-chief workers.

  Args:
    strategy: A tf.distribute.Strategy object.
    filepath: The filepath for the temporary directory.
  """
  if not strategy.extended.should_checkpoint:
    if tf.io.gfile.exists(filepath) and tf.io.gfile.isdir(filepath):
      tf.io.gfile.rmtree(filepath)
pkulzc's avatar
pkulzc committed
442
443
444
445
446
447
448
449
450


def train_loop(
    pipeline_config_path,
    model_dir,
    config_override=None,
    train_steps=None,
    use_tpu=False,
    save_final_config=False,
451
    checkpoint_every_n=1000,
452
    checkpoint_max_to_keep=7,
453
    record_summaries=True,
Pankaj Kanwar's avatar
Pankaj Kanwar committed
454
    performance_summary_exporter=None,
455
    num_steps_per_iteration=NUM_STEPS_PER_ITERATION,
456
    **kwargs):
pkulzc's avatar
pkulzc committed
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
  """Trains a model using eager + functions.

  This method:
    1. Processes the pipeline configs
    2. (Optionally) saves the as-run config
    3. Builds the model & optimizer
    4. Gets the training input data
    5. Loads a fine-tuning detection or classification checkpoint if requested
    6. Loops over the train data, executing distributed training steps inside
       tf.functions.
    7. Checkpoints the model every `checkpoint_every_n` training steps.
    8. Logs the training metrics as TensorBoard summaries.

  Args:
    pipeline_config_path: A path to a pipeline config file.
    model_dir:
      The directory to save checkpoints and summaries to.
    config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to
      override the config from `pipeline_config_path`.
    train_steps: Number of training steps. If None, the number of training steps
      is set from the `TrainConfig` proto.
    use_tpu: Boolean, whether training and evaluation should run on TPU.
    save_final_config: Whether to save final config (obtained after applying
      overrides) to `model_dir`.
    checkpoint_every_n:
      Checkpoint every n training steps.
483
484
    checkpoint_max_to_keep:
      int, the number of most recent checkpoints to keep in the model directory.
485
486
487
488
489
490
    record_summaries: Boolean, whether or not to record summaries defined by
      the model or the training pipeline. This does not impact the summaries
      of the loss values which are always recorded. Examples of summaries
      that are controlled by this flag include:
        - Image summaries of training images.
        - Intermediate tensors which maybe logged by meta architectures.
Pankaj Kanwar's avatar
Pankaj Kanwar committed
491
    performance_summary_exporter: function for exporting performance metrics.
492
493
    num_steps_per_iteration: int, The number of training steps to perform
      in each iteration.
pkulzc's avatar
pkulzc committed
494
495
496
497
498
499
500
501
502
    **kwargs: Additional keyword arguments for configuration override.
  """
  ## Parse the configs
  get_configs_from_pipeline_file = MODEL_BUILD_UTIL_MAP[
      'get_configs_from_pipeline_file']
  merge_external_params_with_configs = MODEL_BUILD_UTIL_MAP[
      'merge_external_params_with_configs']
  create_pipeline_proto_from_configs = MODEL_BUILD_UTIL_MAP[
      'create_pipeline_proto_from_configs']
Pankaj Kanwar's avatar
Pankaj Kanwar committed
503
  steps_per_sec_list = []
pkulzc's avatar
pkulzc committed
504
505
506
507
508
509
510
511

  configs = get_configs_from_pipeline_file(
      pipeline_config_path, config_override=config_override)
  kwargs.update({
      'train_steps': train_steps,
      'use_bfloat16': configs['train_config'].use_bfloat16 and use_tpu
  })
  configs = merge_external_params_with_configs(
512
      configs, None, kwargs_dict=kwargs)
pkulzc's avatar
pkulzc committed
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  model_config = configs['model']
  train_config = configs['train_config']
  train_input_config = configs['train_input_config']

  unpad_groundtruth_tensors = train_config.unpad_groundtruth_tensors
  add_regularization_loss = train_config.add_regularization_loss
  clip_gradients_value = None
  if train_config.gradient_clipping_by_norm > 0:
    clip_gradients_value = train_config.gradient_clipping_by_norm

  # update train_steps from config but only when non-zero value is provided
  if train_steps is None and train_config.num_steps != 0:
    train_steps = train_config.num_steps

527
  if kwargs['use_bfloat16']:
528
    tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16')
529

530
531
532
533
  if train_config.load_all_detection_checkpoint_vars:
    raise ValueError('train_pb2.load_all_detection_checkpoint_vars '
                     'unsupported in TF2')

534
  config_util.update_fine_tune_checkpoint_type(train_config)
pkulzc's avatar
pkulzc committed
535
  fine_tune_checkpoint_type = train_config.fine_tune_checkpoint_type
536
  fine_tune_checkpoint_version = train_config.fine_tune_checkpoint_version
pkulzc's avatar
pkulzc committed
537
538
539

  # Write the as-run pipeline config to disk.
  if save_final_config:
540
    tf.logging.info('Saving pipeline config file to directory %s', model_dir)
pkulzc's avatar
pkulzc committed
541
542
543
544
    pipeline_config_final = create_pipeline_proto_from_configs(configs)
    config_util.save_pipeline_config(pipeline_config_final, model_dir)

  # Build the model, optimizer, and training input
545
  strategy = tf.compat.v2.distribute.get_strategy()
pkulzc's avatar
pkulzc committed
546
  with strategy.scope():
547
    detection_model = MODEL_BUILD_UTIL_MAP['detection_model_fn_base'](
548
549
        model_config=model_config, is_training=True,
        add_summaries=record_summaries)
pkulzc's avatar
pkulzc committed
550

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    def train_dataset_fn(input_context):
      """Callable to create train input."""
      # Create the inputs.
      train_input = inputs.train_input(
          train_config=train_config,
          train_input_config=train_input_config,
          model_config=model_config,
          model=detection_model,
          input_context=input_context)
      train_input = train_input.repeat()
      return train_input

    train_input = strategy.experimental_distribute_datasets_from_function(
        train_dataset_fn)


    global_step = tf.Variable(
        0, trainable=False, dtype=tf.compat.v2.dtypes.int64, name='global_step',
        aggregation=tf.compat.v2.VariableAggregation.ONLY_FIRST_REPLICA)
pkulzc's avatar
pkulzc committed
570
571
    optimizer, (learning_rate,) = optimizer_builder.build(
        train_config.optimizer, global_step=global_step)
572
573
574
575
576

    # We run the detection_model on dummy inputs in order to ensure that the
    # model and all its variables have been properly constructed. Specifically,
    # this is currently necessary prior to (potentially) creating shadow copies
    # of the model variables for the EMA optimizer.
577
    if train_config.optimizer.use_moving_average:
578
579
      _ensure_model_is_built(detection_model, train_input,
                             unpad_groundtruth_tensors)
580
      optimizer.shadow_copy(detection_model)
pkulzc's avatar
pkulzc committed
581
582
583
584
585
586
587

    if callable(learning_rate):
      learning_rate_fn = learning_rate
    else:
      learning_rate_fn = lambda: learning_rate

  ## Train the model
588
589
  # Get the appropriate filepath (temporary or not) based on whether the worker
  # is the chief.
590
591
  summary_writer_filepath = get_filepath(strategy,
                                         os.path.join(model_dir, 'train'))
592
593
594

  summary_writer = tf.compat.v2.summary.create_file_writer(
      summary_writer_filepath)
595

pkulzc's avatar
pkulzc committed
596
597
  with summary_writer.as_default():
    with strategy.scope():
598
599
600
      with tf.compat.v2.summary.record_if(
          lambda: global_step % num_steps_per_iteration == 0):
        # Load a fine-tuning checkpoint.
601
        if train_config.fine_tune_checkpoint:
602
603
604
          variables_helper.ensure_checkpoint_supported(
              train_config.fine_tune_checkpoint, fine_tune_checkpoint_type,
              model_dir)
605
606
607
608
609
          load_fine_tune_checkpoint(
              detection_model, train_config.fine_tune_checkpoint,
              fine_tune_checkpoint_type, fine_tune_checkpoint_version,
              train_config.run_fine_tune_checkpoint_dummy_computation,
              train_input, unpad_groundtruth_tensors)
610
611
612
613

        ckpt = tf.compat.v2.train.Checkpoint(
            step=global_step, model=detection_model, optimizer=optimizer)

614
        manager_dir = get_filepath(strategy, model_dir)
615
616
617
618
619
620
621
622
623
624
625
626
627
        if not strategy.extended.should_checkpoint:
          checkpoint_max_to_keep = 1
        manager = tf.compat.v2.train.CheckpointManager(
            ckpt, manager_dir, max_to_keep=checkpoint_max_to_keep)

        # We use the following instead of manager.latest_checkpoint because
        # manager_dir does not point to the model directory when we are running
        # in a worker.
        latest_checkpoint = tf.train.latest_checkpoint(model_dir)
        ckpt.restore(latest_checkpoint)

        def train_step_fn(features, labels):
          """Single train step."""
628
629
630
631
632
633
634
635

          if record_summaries:
            tf.compat.v2.summary.image(
                name='train_input_images',
                step=global_step,
                data=features[fields.InputDataFields.image],
                max_outputs=3)
          losses_dict = eager_train_step(
636
637
638
639
640
              detection_model,
              features,
              labels,
              unpad_groundtruth_tensors,
              optimizer,
641
              training_step=global_step,
642
643
644
645
              add_regularization_loss=add_regularization_loss,
              clip_gradients_value=clip_gradients_value,
              num_replicas=strategy.num_replicas_in_sync)
          global_step.assign_add(1)
646
          return losses_dict
647
648
649

        def _sample_and_train(strategy, train_step_fn, data_iterator):
          features, labels = data_iterator.next()
650
          if hasattr(tf.distribute.Strategy, 'run'):
651
            per_replica_losses_dict = strategy.run(
652
653
                train_step_fn, args=(features, labels))
          else:
654
655
656
657
658
659
            per_replica_losses_dict = (
                strategy.experimental_run_v2(
                    train_step_fn, args=(features, labels)))

          return reduce_dict(
              strategy, per_replica_losses_dict, tf.distribute.ReduceOp.SUM)
660
661
662
663
664
665
666

        @tf.function
        def _dist_train_step(data_iterator):
          """A distributed train step."""

          if num_steps_per_iteration > 1:
            for _ in tf.range(num_steps_per_iteration - 1):
667
668
669
              # Following suggestion on yaqs/5402607292645376
              with tf.name_scope(''):
                _sample_and_train(strategy, train_step_fn, data_iterator)
670
671
672
673

          return _sample_and_train(strategy, train_step_fn, data_iterator)

        train_input_iter = iter(train_input)
674
675
676
677

        if int(global_step.value()) == 0:
          manager.save()

678
679
680
681
682
683
684
        checkpointed_step = int(global_step.value())
        logged_step = global_step.value()

        last_step_time = time.time()
        for _ in range(global_step.value(), train_steps,
                       num_steps_per_iteration):

685
          losses_dict = _dist_train_step(train_input_iter)
686
687
688

          time_taken = time.time() - last_step_time
          last_step_time = time.time()
Pankaj Kanwar's avatar
Pankaj Kanwar committed
689
          steps_per_sec = num_steps_per_iteration * 1.0 / time_taken
690
691

          tf.compat.v2.summary.scalar(
Pankaj Kanwar's avatar
Pankaj Kanwar committed
692
693
694
              'steps_per_sec', steps_per_sec, step=global_step)

          steps_per_sec_list.append(steps_per_sec)
695

696
697
698
699
700
701
          logged_dict = losses_dict.copy()
          logged_dict['learning_rate'] = learning_rate_fn()

          for key, val in logged_dict.items():
            tf.compat.v2.summary.scalar(key, val, step=global_step)

702
          if global_step.value() - logged_step >= LOG_EVERY:
703
704
            logged_dict_np = {name: value.numpy() for name, value in
                              logged_dict.items()}
705
            tf.logging.info(
706
707
708
                'Step {} per-step time {:.3f}s'.format(
                    global_step.value(), time_taken / num_steps_per_iteration))
            tf.logging.info(pprint.pformat(logged_dict_np, width=40))
709
710
711
712
713
714
715
716
717
718
            logged_step = global_step.value()

          if ((int(global_step.value()) - checkpointed_step) >=
              checkpoint_every_n):
            manager.save()
            checkpointed_step = int(global_step.value())

  # Remove the checkpoint directories of the non-chief workers that
  # MultiWorkerMirroredStrategy forces us to save during sync distributed
  # training.
719
720
  clean_temporary_directories(strategy, manager_dir)
  clean_temporary_directories(strategy, summary_writer_filepath)
Pankaj Kanwar's avatar
Pankaj Kanwar committed
721
722
723
724
725
726
  # TODO(pkanwar): add accuracy metrics.
  if performance_summary_exporter is not None:
    metrics = {
        'steps_per_sec': np.mean(steps_per_sec_list),
        'steps_per_sec_p50': np.median(steps_per_sec_list),
        'steps_per_sec_max': max(steps_per_sec_list),
727
        'last_batch_loss': float(losses_dict['Loss/total_loss'])
Pankaj Kanwar's avatar
Pankaj Kanwar committed
728
729
730
    }
    mixed_precision = 'bf16' if kwargs['use_bfloat16'] else 'fp32'
    performance_summary_exporter(metrics, mixed_precision)
pkulzc's avatar
pkulzc committed
731
732


733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def prepare_eval_dict(detections, groundtruth, features):
  """Prepares eval dictionary containing detections and groundtruth.

  Takes in `detections` from the model, `groundtruth` and `features` returned
  from the eval tf.data.dataset and creates a dictionary of tensors suitable
  for detection eval modules.

  Args:
    detections: A dictionary of tensors returned by `model.postprocess`.
    groundtruth: `inputs.eval_input` returns an eval dataset of (features,
      labels) tuple. `groundtruth` must be set to `labels`.
      Please note that:
        * fields.InputDataFields.groundtruth_classes must be 0-indexed and
          in its 1-hot representation.
        * fields.InputDataFields.groundtruth_verified_neg_classes must be
          0-indexed and in its multi-hot repesentation.
        * fields.InputDataFields.groundtruth_not_exhaustive_classes must be
          0-indexed and in its multi-hot repesentation.
        * fields.InputDataFields.groundtruth_labeled_classes must be
          0-indexed and in its multi-hot repesentation.
    features: `inputs.eval_input` returns an eval dataset of (features, labels)
      tuple. This argument must be set to a dictionary containing the following
      keys and their corresponding values from `features` --
        * fields.InputDataFields.image
        * fields.InputDataFields.original_image
        * fields.InputDataFields.original_image_spatial_shape
        * fields.InputDataFields.true_image_shape
        * inputs.HASH_KEY

  Returns:
    eval_dict: A dictionary of tensors to pass to eval module.
    class_agnostic: Whether to evaluate detection in class agnostic mode.
  """

  groundtruth_boxes = groundtruth[fields.InputDataFields.groundtruth_boxes]
  groundtruth_boxes_shape = tf.shape(groundtruth_boxes)
  # For class-agnostic models, groundtruth one-hot encodings collapse to all
  # ones.
  class_agnostic = (
      fields.DetectionResultFields.detection_classes not in detections)
  if class_agnostic:
    groundtruth_classes_one_hot = tf.ones(
        [groundtruth_boxes_shape[0], groundtruth_boxes_shape[1], 1])
  else:
    groundtruth_classes_one_hot = groundtruth[
        fields.InputDataFields.groundtruth_classes]
  label_id_offset = 1  # Applying label id offset (b/63711816)
  groundtruth_classes = (
      tf.argmax(groundtruth_classes_one_hot, axis=2) + label_id_offset)
  groundtruth[fields.InputDataFields.groundtruth_classes] = groundtruth_classes

  label_id_offset_paddings = tf.constant([[0, 0], [1, 0]])
  if fields.InputDataFields.groundtruth_verified_neg_classes in groundtruth:
    groundtruth[
        fields.InputDataFields.groundtruth_verified_neg_classes] = tf.pad(
            groundtruth[
                fields.InputDataFields.groundtruth_verified_neg_classes],
            label_id_offset_paddings)
  if fields.InputDataFields.groundtruth_not_exhaustive_classes in groundtruth:
    groundtruth[
        fields.InputDataFields.groundtruth_not_exhaustive_classes] = tf.pad(
            groundtruth[
                fields.InputDataFields.groundtruth_not_exhaustive_classes],
            label_id_offset_paddings)
  if fields.InputDataFields.groundtruth_labeled_classes in groundtruth:
    groundtruth[fields.InputDataFields.groundtruth_labeled_classes] = tf.pad(
        groundtruth[fields.InputDataFields.groundtruth_labeled_classes],
        label_id_offset_paddings)

  use_original_images = fields.InputDataFields.original_image in features
  if use_original_images:
    eval_images = features[fields.InputDataFields.original_image]
    true_image_shapes = features[fields.InputDataFields.true_image_shape][:, :3]
    original_image_spatial_shapes = features[
        fields.InputDataFields.original_image_spatial_shape]
  else:
    eval_images = features[fields.InputDataFields.image]
    true_image_shapes = None
    original_image_spatial_shapes = None

  eval_dict = eval_util.result_dict_for_batched_example(
      eval_images,
      features[inputs.HASH_KEY],
      detections,
      groundtruth,
      class_agnostic=class_agnostic,
      scale_to_absolute=True,
      original_image_spatial_shapes=original_image_spatial_shapes,
      true_image_shapes=true_image_shapes)

  return eval_dict, class_agnostic


def concat_replica_results(tensor_dict):
  new_tensor_dict = {}
  for key, values in tensor_dict.items():
    new_tensor_dict[key] = tf.concat(values, axis=0)
  return new_tensor_dict


pkulzc's avatar
pkulzc committed
833
834
835
836
837
838
def eager_eval_loop(
    detection_model,
    configs,
    eval_dataset,
    use_tpu=False,
    postprocess_on_cpu=False,
Ronny Votel's avatar
Ronny Votel committed
839
840
    global_step=None,
    ):
pkulzc's avatar
pkulzc committed
841
842
843
844
  """Evaluate the model eagerly on the evaluation dataset.

  This method will compute the evaluation metrics specified in the configs on
  the entire evaluation dataset, then return the metrics. It will also log
845
  the metrics to TensorBoard.
pkulzc's avatar
pkulzc committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861

  Args:
    detection_model: A DetectionModel (based on Keras) to evaluate.
    configs: Object detection configs that specify the evaluators that should
      be used, as well as whether regularization loss should be included and
      if bfloat16 should be used on TPUs.
    eval_dataset: Dataset containing evaluation data.
    use_tpu: Whether a TPU is being used to execute the model for evaluation.
    postprocess_on_cpu: Whether model postprocessing should happen on
      the CPU when using a TPU to execute the model.
    global_step: A variable containing the training step this model was trained
      to. Used for logging purposes.

  Returns:
    A dict of evaluation metrics representing the results of this evaluation.
  """
862
  del postprocess_on_cpu
pkulzc's avatar
pkulzc committed
863
864
865
866
867
868
869
870
871
872
873
  train_config = configs['train_config']
  eval_input_config = configs['eval_input_config']
  eval_config = configs['eval_config']
  add_regularization_loss = train_config.add_regularization_loss

  is_training = False
  detection_model._is_training = is_training  # pylint: disable=protected-access
  tf.keras.backend.set_learning_phase(is_training)

  evaluator_options = eval_util.evaluator_options_from_eval_config(
      eval_config)
874
  batch_size = eval_config.batch_size
pkulzc's avatar
pkulzc committed
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902

  class_agnostic_category_index = (
      label_map_util.create_class_agnostic_category_index())
  class_agnostic_evaluators = eval_util.get_evaluators(
      eval_config,
      list(class_agnostic_category_index.values()),
      evaluator_options)

  class_aware_evaluators = None
  if eval_input_config.label_map_path:
    class_aware_category_index = (
        label_map_util.create_category_index_from_labelmap(
            eval_input_config.label_map_path))
    class_aware_evaluators = eval_util.get_evaluators(
        eval_config,
        list(class_aware_category_index.values()),
        evaluator_options)

  evaluators = None
  loss_metrics = {}

  @tf.function
  def compute_eval_dict(features, labels):
    """Compute the evaluation result on an image."""
    # For evaling on train data, it is necessary to check whether groundtruth
    # must be unpadded.
    boxes_shape = (
        labels[fields.InputDataFields.groundtruth_boxes].get_shape().as_list())
903
904
905
    unpad_groundtruth_tensors = (boxes_shape[1] is not None
                                 and not use_tpu
                                 and batch_size == 1)
906
    groundtruth_dict = labels
pkulzc's avatar
pkulzc committed
907
908
909
910
    labels = model_lib.unstack_batch(
        labels, unpad_groundtruth_tensors=unpad_groundtruth_tensors)

    losses_dict, prediction_dict = _compute_losses_and_predictions_dicts(
911
912
        detection_model, features, labels, training_step=None,
        add_regularization_loss=add_regularization_loss)
913
914
915
916
917
918
919
920
921
922
923
924
925
926
    prediction_dict = detection_model.postprocess(
        prediction_dict, features[fields.InputDataFields.true_image_shape])
    eval_features = {
        fields.InputDataFields.image:
            features[fields.InputDataFields.image],
        fields.InputDataFields.original_image:
            features[fields.InputDataFields.original_image],
        fields.InputDataFields.original_image_spatial_shape:
            features[fields.InputDataFields.original_image_spatial_shape],
        fields.InputDataFields.true_image_shape:
            features[fields.InputDataFields.true_image_shape],
        inputs.HASH_KEY: features[inputs.HASH_KEY],
    }
    return losses_dict, prediction_dict, groundtruth_dict, eval_features
pkulzc's avatar
pkulzc committed
927

928
929
930
931
932
933
  agnostic_categories = label_map_util.create_class_agnostic_category_index()
  per_class_categories = label_map_util.create_category_index_from_labelmap(
      eval_input_config.label_map_path)
  keypoint_edges = [
      (kp.start, kp.end) for kp in eval_config.keypoint_edge]

934
  strategy = tf.compat.v2.distribute.get_strategy()
935

936
937
938
939
940
  for i, (features, labels) in enumerate(eval_dataset):
    try:
      (losses_dict, prediction_dict, groundtruth_dict,
       eval_features) = strategy.run(
           compute_eval_dict, args=(features, labels))
941
942
    except Exception as exc:  # pylint:disable=broad-except
      tf.logging.info('Encountered %s exception.', exc)
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
      tf.logging.info('A replica probably exhausted all examples. Skipping '
                      'pending examples on other replicas.')
      break
    (local_prediction_dict, local_groundtruth_dict,
     local_eval_features) = tf.nest.map_structure(
         strategy.experimental_local_results,
         [prediction_dict, groundtruth_dict, eval_features])
    local_prediction_dict = concat_replica_results(local_prediction_dict)
    local_groundtruth_dict = concat_replica_results(local_groundtruth_dict)
    local_eval_features = concat_replica_results(local_eval_features)

    eval_dict, class_agnostic = prepare_eval_dict(local_prediction_dict,
                                                  local_groundtruth_dict,
                                                  local_eval_features)
    for loss_key, loss_tensor in iter(losses_dict.items()):
      losses_dict[loss_key] = strategy.reduce(tf.distribute.ReduceOp.MEAN,
                                              loss_tensor, None)
960
961
962
963
964
    if class_agnostic:
      category_index = agnostic_categories
    else:
      category_index = per_class_categories

965
966
    if i % 100 == 0:
      tf.logging.info('Finished eval step %d', i)
pkulzc's avatar
pkulzc committed
967

968
    use_original_images = fields.InputDataFields.original_image in features
969
    if (use_original_images and i < eval_config.num_visualizations):
970
971
972
973
974
975
976
      sbys_image_list = vutils.draw_side_by_side_evaluation_image(
          eval_dict,
          category_index=category_index,
          max_boxes_to_draw=eval_config.max_num_boxes_to_visualize,
          min_score_thresh=eval_config.min_score_threshold,
          use_normalized_coordinates=False,
          keypoint_edges=keypoint_edges or None)
977
      for j, sbys_image in enumerate(sbys_image_list):
978
        tf.compat.v2.summary.image(
979
            name='eval_side_by_side_{}_{}'.format(i, j),
980
            step=global_step,
981
            data=sbys_image,
982
            max_outputs=eval_config.num_visualizations)
983
984
985
986
987
988
989
990
991
      if eval_util.has_densepose(eval_dict):
        dp_image_list = vutils.draw_densepose_visualizations(
            eval_dict)
        for j, dp_image in enumerate(dp_image_list):
          tf.compat.v2.summary.image(
              name='densepose_detections_{}_{}'.format(i, j),
              step=global_step,
              data=dp_image,
              max_outputs=eval_config.num_visualizations)
992

pkulzc's avatar
pkulzc committed
993
994
995
996
997
998
999
1000
1001
1002
1003
    if evaluators is None:
      if class_agnostic:
        evaluators = class_agnostic_evaluators
      else:
        evaluators = class_aware_evaluators

    for evaluator in evaluators:
      evaluator.add_eval_dict(eval_dict)

    for loss_key, loss_tensor in iter(losses_dict.items()):
      if loss_key not in loss_metrics:
1004
1005
        loss_metrics[loss_key] = []
      loss_metrics[loss_key].append(loss_tensor)
pkulzc's avatar
pkulzc committed
1006
1007
1008
1009
1010
1011

  eval_metrics = {}

  for evaluator in evaluators:
    eval_metrics.update(evaluator.evaluate())
  for loss_key in loss_metrics:
1012
    eval_metrics[loss_key] = tf.reduce_mean(loss_metrics[loss_key])
pkulzc's avatar
pkulzc committed
1013
1014

  eval_metrics = {str(k): v for k, v in eval_metrics.items()}
Ronny Votel's avatar
Ronny Votel committed
1015
  tf.logging.info('Eval metrics at step %d', global_step.numpy())
pkulzc's avatar
pkulzc committed
1016
1017
  for k in eval_metrics:
    tf.compat.v2.summary.scalar(k, eval_metrics[k], step=global_step)
1018
    tf.logging.info('\t+ %s: %f', k, eval_metrics[k])
pkulzc's avatar
pkulzc committed
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
  return eval_metrics


def eval_continuously(
    pipeline_config_path,
    config_override=None,
    train_steps=None,
    sample_1_of_n_eval_examples=1,
    sample_1_of_n_eval_on_train_examples=1,
    use_tpu=False,
    override_eval_num_epochs=True,
    postprocess_on_cpu=False,
    model_dir=None,
    checkpoint_dir=None,
    wait_interval=180,
1034
    timeout=3600,
1035
    eval_index=0,
1036
    save_final_config=False,
pkulzc's avatar
pkulzc committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
    **kwargs):
  """Run continuous evaluation of a detection model eagerly.

  This method builds the model, and continously restores it from the most
  recent training checkpoint in the checkpoint directory & evaluates it
  on the evaluation data.

  Args:
    pipeline_config_path: A path to a pipeline config file.
    config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to
      override the config from `pipeline_config_path`.
    train_steps: Number of training steps. If None, the number of training steps
      is set from the `TrainConfig` proto.
    sample_1_of_n_eval_examples: Integer representing how often an eval example
      should be sampled. If 1, will sample all examples.
    sample_1_of_n_eval_on_train_examples: Similar to
      `sample_1_of_n_eval_examples`, except controls the sampling of training
      data for evaluation.
    use_tpu: Boolean, whether training and evaluation should run on TPU.
    override_eval_num_epochs: Whether to overwrite the number of epochs to 1 for
      eval_input.
    postprocess_on_cpu: When use_tpu and postprocess_on_cpu are true,
      postprocess is scheduled on the host cpu.
1060
1061
1062
1063
1064
1065
    model_dir: Directory to output resulting evaluation summaries to.
    checkpoint_dir: Directory that contains the training checkpoints.
    wait_interval: The mimmum number of seconds to wait before checking for a
      new checkpoint.
    timeout: The maximum number of seconds to wait for a checkpoint. Execution
      will terminate if no new checkpoints are found after these many seconds.
1066
1067
    eval_index: int, If given, only evaluate the dataset at the given
      index. By default, evaluates dataset at 0'th index.
1068
1069
    save_final_config: Whether to save the pipeline config file to the model
      directory.
pkulzc's avatar
pkulzc committed
1070
1071
1072
1073
    **kwargs: Additional keyword arguments for configuration override.
  """
  get_configs_from_pipeline_file = MODEL_BUILD_UTIL_MAP[
      'get_configs_from_pipeline_file']
Ronny Votel's avatar
Ronny Votel committed
1074
1075
  create_pipeline_proto_from_configs = MODEL_BUILD_UTIL_MAP[
      'create_pipeline_proto_from_configs']
pkulzc's avatar
pkulzc committed
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
  merge_external_params_with_configs = MODEL_BUILD_UTIL_MAP[
      'merge_external_params_with_configs']

  configs = get_configs_from_pipeline_file(
      pipeline_config_path, config_override=config_override)
  kwargs.update({
      'sample_1_of_n_eval_examples': sample_1_of_n_eval_examples,
      'use_bfloat16': configs['train_config'].use_bfloat16 and use_tpu
  })
  if train_steps is not None:
    kwargs['train_steps'] = train_steps
  if override_eval_num_epochs:
    kwargs.update({'eval_num_epochs': 1})
    tf.logging.warning(
        'Forced number of epochs for all eval validations to be 1.')
  configs = merge_external_params_with_configs(
1092
      configs, None, kwargs_dict=kwargs)
1093
  if model_dir and save_final_config:
1094
    tf.logging.info('Saving pipeline config file to directory %s', model_dir)
Ronny Votel's avatar
Ronny Votel committed
1095
1096
1097
    pipeline_config_final = create_pipeline_proto_from_configs(configs)
    config_util.save_pipeline_config(pipeline_config_final, model_dir)

pkulzc's avatar
pkulzc committed
1098
1099
1100
1101
1102
1103
1104
1105
  model_config = configs['model']
  train_input_config = configs['train_input_config']
  eval_config = configs['eval_config']
  eval_input_configs = configs['eval_input_configs']
  eval_on_train_input_config = copy.deepcopy(train_input_config)
  eval_on_train_input_config.sample_1_of_n_examples = (
      sample_1_of_n_eval_on_train_examples)
  if override_eval_num_epochs and eval_on_train_input_config.num_epochs != 1:
1106
1107
1108
1109
1110
    tf.logging.warning(
        ('Expected number of evaluation epochs is 1, but '
         'instead encountered `eval_on_train_input_config'
         '.num_epochs` = %d. Overwriting `num_epochs` to 1.'),
        eval_on_train_input_config.num_epochs)
pkulzc's avatar
pkulzc committed
1111
1112
    eval_on_train_input_config.num_epochs = 1

1113
  if kwargs['use_bfloat16']:
1114
    tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16')
1115

1116
1117
1118
1119
1120
  eval_input_config = eval_input_configs[eval_index]
  strategy = tf.compat.v2.distribute.get_strategy()
  with strategy.scope():
    detection_model = MODEL_BUILD_UTIL_MAP['detection_model_fn_base'](
        model_config=model_config, is_training=True)
pkulzc's avatar
pkulzc committed
1121

1122
1123
1124
1125
1126
1127
  eval_input = strategy.experimental_distribute_dataset(
      inputs.eval_input(
          eval_config=eval_config,
          eval_input_config=eval_input_config,
          model_config=model_config,
          model=detection_model))
Vighnesh Birodkar's avatar
Vighnesh Birodkar committed
1128

pkulzc's avatar
pkulzc committed
1129
1130
1131
  global_step = tf.compat.v2.Variable(
      0, trainable=False, dtype=tf.compat.v2.dtypes.int64)

1132
1133
1134
  optimizer, _ = optimizer_builder.build(
      configs['train_config'].optimizer, global_step=global_step)

1135
1136
  for latest_checkpoint in tf.train.checkpoints_iterator(
      checkpoint_dir, timeout=timeout, min_interval_secs=wait_interval):
pkulzc's avatar
pkulzc committed
1137
    ckpt = tf.compat.v2.train.Checkpoint(
1138
1139
        step=global_step, model=detection_model, optimizer=optimizer)

1140
1141
1142
1143
    # We run the detection_model on dummy inputs in order to ensure that the
    # model and all its variables have been properly constructed. Specifically,
    # this is currently necessary prior to (potentially) creating shadow copies
    # of the model variables for the EMA optimizer.
1144
    if eval_config.use_moving_averages:
1145
1146
1147
      unpad_groundtruth_tensors = (eval_config.batch_size == 1 and not use_tpu)
      _ensure_model_is_built(detection_model, eval_input,
                             unpad_groundtruth_tensors)
1148
      optimizer.shadow_copy(detection_model)
1149
1150
1151

    ckpt.restore(latest_checkpoint).expect_partial()

1152
1153
1154
    if eval_config.use_moving_averages:
      optimizer.swap_weights()

1155
1156
1157
1158
1159
1160
1161
1162
1163
    summary_writer = tf.compat.v2.summary.create_file_writer(
        os.path.join(model_dir, 'eval', eval_input_config.name))
    with summary_writer.as_default():
      eager_eval_loop(
          detection_model,
          configs,
          eval_input,
          use_tpu=use_tpu,
          postprocess_on_cpu=postprocess_on_cpu,
Ronny Votel's avatar
Ronny Votel committed
1164
1165
          global_step=global_step,
          )
1166
1167
1168
1169

    if global_step.numpy() == configs['train_config'].num_steps:
      tf.logging.info('Exiting evaluation at step %d', global_step.numpy())
      return