train_utils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import logging
  6. import math
  7. import os
  8. import random
  9. import re
  10. from datetime import timedelta
  11. from typing import Optional
  12. import hydra
  13. import numpy as np
  14. import omegaconf
  15. import torch
  16. import torch.distributed as dist
  17. from iopath.common.file_io import g_pathmgr
  18. from omegaconf import OmegaConf
  19. def multiply_all(*args):
  20. return np.prod(np.array(args)).item()
  21. def collect_dict_keys(config):
  22. """This function recursively iterates through a dataset configuration, and collect all the dict_key that are defined"""
  23. val_keys = []
  24. # If the this config points to the collate function, then it has a key
  25. if "_target_" in config and re.match(r".*collate_fn.*", config["_target_"]):
  26. val_keys.append(config["dict_key"])
  27. else:
  28. # Recursively proceed
  29. for v in config.values():
  30. if isinstance(v, type(config)):
  31. val_keys.extend(collect_dict_keys(v))
  32. elif isinstance(v, omegaconf.listconfig.ListConfig):
  33. for item in v:
  34. if isinstance(item, type(config)):
  35. val_keys.extend(collect_dict_keys(item))
  36. return val_keys
  37. class Phase:
  38. TRAIN = "train"
  39. VAL = "val"
  40. def register_omegaconf_resolvers():
  41. OmegaConf.register_new_resolver("get_method", hydra.utils.get_method)
  42. OmegaConf.register_new_resolver("get_class", hydra.utils.get_class)
  43. OmegaConf.register_new_resolver("add", lambda x, y: x + y)
  44. OmegaConf.register_new_resolver("times", multiply_all)
  45. OmegaConf.register_new_resolver("divide", lambda x, y: x / y)
  46. OmegaConf.register_new_resolver("pow", lambda x, y: x**y)
  47. OmegaConf.register_new_resolver("subtract", lambda x, y: x - y)
  48. OmegaConf.register_new_resolver("range", lambda x: list(range(x)))
  49. OmegaConf.register_new_resolver("int", lambda x: int(x))
  50. OmegaConf.register_new_resolver("ceil_int", lambda x: int(math.ceil(x)))
  51. OmegaConf.register_new_resolver("merge", lambda *x: OmegaConf.merge(*x))
  52. def setup_distributed_backend(backend, timeout_mins):
  53. """
  54. Initialize torch.distributed and set the CUDA device.
  55. Expects environment variables to be set as per
  56. https://pytorch.org/docs/stable/distributed.html#environment-variable-initialization
  57. along with the environ variable "LOCAL_RANK" which is used to set the CUDA device.
  58. """
  59. # enable TORCH_NCCL_ASYNC_ERROR_HANDLING to ensure dist nccl ops time out after timeout_mins
  60. # of waiting
  61. os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "1"
  62. logging.info(f"Setting up torch.distributed with a timeout of {timeout_mins} mins")
  63. dist.init_process_group(backend=backend, timeout=timedelta(minutes=timeout_mins))
  64. return dist.get_rank()
  65. def get_machine_local_and_dist_rank():
  66. """
  67. Get the distributed and local rank of the current gpu.
  68. """
  69. local_rank = int(os.environ.get("LOCAL_RANK", None))
  70. distributed_rank = int(os.environ.get("RANK", None))
  71. assert (
  72. local_rank is not None and distributed_rank is not None
  73. ), "Please the set the RANK and LOCAL_RANK environment variables."
  74. return local_rank, distributed_rank
  75. def print_cfg(cfg):
  76. """
  77. Supports printing both Hydra DictConfig and also the AttrDict config
  78. """
  79. logging.info("Training with config:")
  80. logging.info(OmegaConf.to_yaml(cfg))
  81. def set_seeds(seed_value, max_epochs, dist_rank):
  82. """
  83. Set the python random, numpy and torch seed for each gpu. Also set the CUDA
  84. seeds if the CUDA is available. This ensures deterministic nature of the training.
  85. """
  86. # Since in the pytorch sampler, we increment the seed by 1 for every epoch.
  87. seed_value = (seed_value + dist_rank) * max_epochs
  88. logging.info(f"MACHINE SEED: {seed_value}")
  89. random.seed(seed_value)
  90. np.random.seed(seed_value)
  91. torch.manual_seed(seed_value)
  92. if torch.cuda.is_available():
  93. torch.cuda.manual_seed_all(seed_value)
  94. def makedir(dir_path):
  95. """
  96. Create the directory if it does not exist.
  97. """
  98. is_success = False
  99. try:
  100. if not g_pathmgr.exists(dir_path):
  101. g_pathmgr.mkdirs(dir_path)
  102. is_success = True
  103. except BaseException:
  104. logging.info(f"Error creating directory: {dir_path}")
  105. return is_success
  106. def is_dist_avail_and_initialized():
  107. if not dist.is_available():
  108. return False
  109. if not dist.is_initialized():
  110. return False
  111. return True
  112. def get_amp_type(amp_type: Optional[str] = None):
  113. if amp_type is None:
  114. return None
  115. assert amp_type in ["bfloat16", "float16"], "Invalid Amp type."
  116. if amp_type == "bfloat16":
  117. return torch.bfloat16
  118. else:
  119. return torch.float16
  120. def log_env_variables():
  121. env_keys = sorted(list(os.environ.keys()))
  122. st = ""
  123. for k in env_keys:
  124. v = os.environ[k]
  125. st += f"{k}={v}\n"
  126. logging.info("Logging ENV_VARIABLES")
  127. logging.info(st)
  128. class AverageMeter:
  129. """Computes and stores the average and current value"""
  130. def __init__(self, name, device, fmt=":f"):
  131. self.name = name
  132. self.fmt = fmt
  133. self.device = device
  134. self.reset()
  135. def reset(self):
  136. self.val = 0
  137. self.avg = 0
  138. self.sum = 0
  139. self.count = 0
  140. self._allow_updates = True
  141. def update(self, val, n=1):
  142. self.val = val
  143. self.sum += val * n
  144. self.count += n
  145. self.avg = self.sum / self.count
  146. def __str__(self):
  147. fmtstr = "{name}: {val" + self.fmt + "} ({avg" + self.fmt + "})"
  148. return fmtstr.format(**self.__dict__)
  149. class MemMeter:
  150. """Computes and stores the current, avg, and max of peak Mem usage per iteration"""
  151. def __init__(self, name, device, fmt=":f"):
  152. self.name = name
  153. self.fmt = fmt
  154. self.device = device
  155. self.reset()
  156. def reset(self):
  157. self.val = 0 # Per iteration max usage
  158. self.avg = 0 # Avg per iteration max usage
  159. self.peak = 0 # Peak usage for lifetime of program
  160. self.sum = 0
  161. self.count = 0
  162. self._allow_updates = True
  163. def update(self, n=1, reset_peak_usage=True):
  164. self.val = torch.cuda.max_memory_allocated() // 1e9
  165. self.sum += self.val * n
  166. self.count += n
  167. self.avg = self.sum / self.count
  168. self.peak = max(self.peak, self.val)
  169. if reset_peak_usage:
  170. torch.cuda.reset_peak_memory_stats()
  171. def __str__(self):
  172. fmtstr = (
  173. "{name}: {val"
  174. + self.fmt
  175. + "} ({avg"
  176. + self.fmt
  177. + "}/{peak"
  178. + self.fmt
  179. + "})"
  180. )
  181. return fmtstr.format(**self.__dict__)
  182. def human_readable_time(time_seconds):
  183. time = int(time_seconds)
  184. minutes, seconds = divmod(time, 60)
  185. hours, minutes = divmod(minutes, 60)
  186. days, hours = divmod(hours, 24)
  187. return f"{days:02}d {hours:02}h {minutes:02}m"
  188. class DurationMeter:
  189. def __init__(self, name, device, fmt=":f"):
  190. self.name = name
  191. self.device = device
  192. self.fmt = fmt
  193. self.val = 0
  194. def reset(self):
  195. self.val = 0
  196. def update(self, val):
  197. self.val = val
  198. def add(self, val):
  199. self.val += val
  200. def __str__(self):
  201. return f"{self.name}: {human_readable_time(self.val)}"
  202. class ProgressMeter:
  203. def __init__(self, num_batches, meters, real_meters, prefix=""):
  204. self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
  205. self.meters = meters
  206. self.real_meters = real_meters
  207. self.prefix = prefix
  208. def display(self, batch, enable_print=False):
  209. entries = [self.prefix + self.batch_fmtstr.format(batch)]
  210. entries += [str(meter) for meter in self.meters]
  211. entries += [
  212. " | ".join(
  213. [
  214. f"{os.path.join(name, subname)}: {val:.4f}"
  215. for subname, val in meter.compute().items()
  216. ]
  217. )
  218. for name, meter in self.real_meters.items()
  219. ]
  220. logging.info(" | ".join(entries))
  221. if enable_print:
  222. print(" | ".join(entries))
  223. def _get_batch_fmtstr(self, num_batches):
  224. num_digits = len(str(num_batches // 1))
  225. fmt = "{:" + str(num_digits) + "d}"
  226. return "[" + fmt + "/" + fmt.format(num_batches) + "]"
  227. def get_resume_checkpoint(checkpoint_save_dir):
  228. if not g_pathmgr.isdir(checkpoint_save_dir):
  229. return None
  230. ckpt_file = os.path.join(checkpoint_save_dir, "checkpoint.pt")
  231. if not g_pathmgr.isfile(ckpt_file):
  232. return None
  233. return ckpt_file