performance.py 2.19 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
17
18
19
20
21
22
"""Functions and classes related to training performance."""

import tensorflow as tf


def configure_optimizer(optimizer,
                        use_float16=False,
                        use_graph_rewrite=False,
23
                        loss_scale=None):
24
25
  """Configures optimizer object with performance options."""
  if use_float16:
26
    if loss_scale in (None, 'dynamic'):
Pankaj Kanwar's avatar
Pankaj Kanwar committed
27
28
29
30
31
      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)
32
33
  if use_graph_rewrite:
    # Note: the model dtype must be 'float32', which will ensure
34
35
36
37
38
    # 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))
39
40
41
  return optimizer


Reed Wanderman-Milne's avatar
Reed Wanderman-Milne committed
42
43
44
45
46
47
def set_mixed_precision_policy(dtype, loss_scale=None):
  """Sets the global `tf.keras.mixed_precision.Policy`."""
  # TODO(b/191894773): Remove loss_scale argument
  assert loss_scale is None, (
      'The loss_scale argument must be None. The argument exists for '
      'historical reasons and will be removed soon.')
48
  if dtype == tf.float16:
Reed Wanderman-Milne's avatar
Reed Wanderman-Milne committed
49
    tf.keras.mixed_precision.set_global_policy('mixed_float16')
50
  elif dtype == tf.bfloat16:
Reed Wanderman-Milne's avatar
Reed Wanderman-Milne committed
51
    tf.keras.mixed_precision.set_global_policy('mixed_bfloat16')
52
  elif dtype == tf.float32:
Reed Wanderman-Milne's avatar
Reed Wanderman-Milne committed
53
    tf.keras.mixed_precision.set_global_policy('float32')
54
  else:
Hongkun Yu's avatar
Hongkun Yu committed
55
    raise ValueError('Unexpected dtype: %s' % dtype)