fp16_utils.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import tensorflow as tf
  17. import numpy as np
  18. def float32_variable_storage_getter(getter, name, shape=None, dtype=None,
  19. initializer=None, regularizer=None,
  20. trainable=True,
  21. *args, **kwargs):
  22. """Custom variable getter that forces trainable variables to be stored in
  23. float32 precision and then casts them to the training precision.
  24. """
  25. storage_dtype = tf.float32 if trainable else dtype
  26. variable = getter(name, shape, dtype=storage_dtype,
  27. initializer=initializer, regularizer=regularizer,
  28. trainable=trainable,
  29. *args, **kwargs)
  30. if trainable and dtype != tf.float32:
  31. variable = tf.cast(variable, dtype)
  32. return variable