gpu_environment.py 1.5 KB

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