performance.py 3.61 KB
Newer Older
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3
4
5
6
7
8
9
10
11
12
13
#
# 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.
Hongkun Yu's avatar
Hongkun Yu committed
14

15
16
"""Functions and classes related to training performance."""

17
from absl import logging
18
19
20
21
22
23
import tensorflow as tf


def configure_optimizer(optimizer,
                        use_float16=False,
                        use_graph_rewrite=False,
Pankaj Kanwar's avatar
Pankaj Kanwar committed
24
                        loss_scale='dynamic',
25
                        use_experimental_api=False):
26
  """Configures optimizer object with performance options."""
27
28
29
  if use_experimental_api:
    logging.warning('Passing use_experimental_api=True is deprecated. The '
                    'argument will be removed in the future.')
30
  if use_float16:
Pankaj Kanwar's avatar
Pankaj Kanwar committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    # TODO(b/171936854): Move all methods to non-experimental api.
    if use_experimental_api:
      # Wraps optimizer with a LossScaleOptimizer. This is done automatically
      # in compile() with the "mixed_float16" policy, but since we do not call
      # compile(), we must wrap the optimizer manually.
      optimizer = (
          tf.keras.mixed_precision.experimental.LossScaleOptimizer(
              optimizer, loss_scale=loss_scale))
    elif loss_scale == 'dynamic':
      optimizer = tf.keras.mixed_precision.LossScaleOptimizer(optimizer)
    else:
      # loss_scale is a number. We interpret that as a fixed loss scale.
      optimizer = tf.keras.mixed_precision.LossScaleOptimizer(
          optimizer, dynamic=False, initial_scale=loss_scale)
45
46
  if use_graph_rewrite:
    # Note: the model dtype must be 'float32', which will ensure
47
48
49
50
51
    # tf.keras.mixed_precision and enable_mixed_precision_graph_rewrite do not
    # double up.
    optimizer = (
        tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite(
            optimizer))
52
53
54
  return optimizer


Pankaj Kanwar's avatar
Pankaj Kanwar committed
55
def set_mixed_precision_policy(dtype, loss_scale=None,
56
                               use_experimental_api=False):
57
  """Sets mix precision policy."""
58
59
60
  if use_experimental_api:
    logging.warning('Passing use_experimental_api=True is deprecated. The '
                    'argument will be removed in the future.')
Reed Wanderman-Milne's avatar
Reed Wanderman-Milne committed
61
62
63
64
65
  assert use_experimental_api or loss_scale is None, (
      'loss_scale cannot be specified if use_experimental_api is False. If the '
      'non-experimental API is used, specify the loss scaling configuration '
      'when creating the LossScaleOptimizer instead.'
  )
66
  if dtype == tf.float16:
Pankaj Kanwar's avatar
Pankaj Kanwar committed
67
68
69
70
71
72
73
    # TODO(b/171936854): Move all methods to non-experimental api.
    if use_experimental_api:
      policy = tf.keras.mixed_precision.experimental.Policy(
          'mixed_float16', loss_scale=loss_scale)
      tf.keras.mixed_precision.experimental.set_policy(policy)
    else:
      tf.keras.mixed_precision.set_global_policy('mixed_float16')
74
  elif dtype == tf.bfloat16:
Pankaj Kanwar's avatar
Pankaj Kanwar committed
75
76
77
78
    if use_experimental_api:
      tf.keras.mixed_precision.experimental.set_policy('mixed_bfloat16')
    else:
      tf.keras.mixed_precision.set_global_policy('mixed_bfloat16')
79
  elif dtype == tf.float32:
Pankaj Kanwar's avatar
Pankaj Kanwar committed
80
81
82
83
    if use_experimental_api:
      tf.keras.mixed_precision.experimental.set_policy('float32')
    else:
      tf.keras.mixed_precision.set_global_policy('float32')
84
  else:
Hongkun Yu's avatar
Hongkun Yu committed
85
    raise ValueError('Unexpected dtype: %s' % dtype)