train_utils.py 8.6 KB

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