utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import multiprocessing
  15. import os
  16. import pickle
  17. import random
  18. import shutil
  19. import sys
  20. from functools import wraps
  21. from pathlib import Path
  22. import horovod.tensorflow as hvd
  23. import numpy as np
  24. import tensorflow as tf
  25. from tqdm import tqdm
  26. def hvd_init():
  27. hvd.init()
  28. gpus = tf.config.experimental.list_physical_devices("GPU")
  29. for gpu in gpus:
  30. tf.config.experimental.set_memory_growth(gpu, True)
  31. if gpus:
  32. tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], "GPU")
  33. def set_tf_flags(args):
  34. os.environ["CUDA_CACHE_DISABLE"] = "1"
  35. os.environ["HOROVOD_GPU_ALLREDUCE"] = "NCCL"
  36. os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
  37. os.environ["TF_GPU_THREAD_MODE"] = "gpu_private"
  38. os.environ["TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT"] = "0"
  39. os.environ["TF_ADJUST_HUE_FUSED"] = "1"
  40. os.environ["TF_ADJUST_SATURATION_FUSED"] = "1"
  41. os.environ["TF_ENABLE_WINOGRAD_NONFUSED"] = "1"
  42. os.environ["TF_SYNC_ON_FINISH"] = "0"
  43. os.environ["TF_AUTOTUNE_THRESHOLD"] = "2"
  44. os.environ["TF_ENABLE_AUTO_MIXED_PRECISION"] = "0"
  45. if args.xla:
  46. tf.config.optimizer.set_jit(True)
  47. tf.config.optimizer.set_experimental_options({"remapping": False})
  48. tf.config.threading.set_intra_op_parallelism_threads(1)
  49. tf.config.threading.set_inter_op_parallelism_threads(max(2, (multiprocessing.cpu_count() // hvd.size()) - 2))
  50. if args.amp:
  51. tf.keras.mixed_precision.set_global_policy("mixed_float16")
  52. def is_main_process():
  53. return hvd.rank() == 0
  54. def progress_bar(iterable, *args, quiet, **kwargs):
  55. if quiet or not is_main_process():
  56. return iterable
  57. return tqdm(iterable, *args, **kwargs)
  58. def rank_zero_only(fn):
  59. @wraps(fn)
  60. def wrapped_fn(*args, **kwargs):
  61. if is_main_process():
  62. return fn(*args, **kwargs)
  63. return wrapped_fn
  64. def set_seed(seed):
  65. seed = seed or random.randrange(2 ** 31)
  66. np.random.seed(seed)
  67. tf.random.set_seed(seed)
  68. def get_task_code(args):
  69. return f"{args.task}_{args.dim}d_tf2"
  70. def get_config_file(args):
  71. task_code = get_task_code(args)
  72. path = os.path.join(args.data, "config.pkl")
  73. if not os.path.exists(path):
  74. path = os.path.join(args.data, task_code, "config.pkl")
  75. return pickle.load(open(path, "rb"))
  76. def get_tta_flips(dim):
  77. if dim == 2:
  78. return [[1], [2], [1, 2]]
  79. else:
  80. return [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
  81. def make_empty_dir(path, force=False):
  82. path = Path(path)
  83. if path.exists():
  84. if not path.is_dir():
  85. print(f"Output path {path} exists and is not a directory." "Please remove it and try again.")
  86. sys.exit(1)
  87. else:
  88. if not force:
  89. decision = input(f"Output path {path} exists. Continue and replace it? [Y/n]: ")
  90. if decision.strip().lower() not in ["", "y"]:
  91. sys.exit(1)
  92. shutil.rmtree(path, ignore_errors=True)
  93. path.mkdir(parents=True)