utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import datetime
  2. import os
  3. import time
  4. from collections import defaultdict, deque
  5. import torch
  6. import torch.distributed as dist
  7. import torch.nn.functional as F
  8. class SmoothedValue:
  9. """Track a series of values and provide access to smoothed values over a
  10. window or the global series average.
  11. """
  12. def __init__(self, window_size=20, fmt="{median:.4f} ({global_avg:.4f})"):
  13. self.deque = deque(maxlen=window_size)
  14. self.total = 0.0
  15. self.count = 0
  16. self.fmt = fmt
  17. def update(self, value, n=1):
  18. self.deque.append(value)
  19. self.count += n
  20. self.total += value * n
  21. def synchronize_between_processes(self):
  22. """
  23. Warning: does not synchronize the deque!
  24. """
  25. t = reduce_across_processes([self.count, self.total])
  26. t = t.tolist()
  27. self.count = int(t[0])
  28. self.total = t[1]
  29. @property
  30. def median(self):
  31. d = torch.tensor(list(self.deque))
  32. return d.median().item()
  33. @property
  34. def avg(self):
  35. d = torch.tensor(list(self.deque), dtype=torch.float32)
  36. return d.mean().item()
  37. @property
  38. def global_avg(self):
  39. return self.total / self.count
  40. @property
  41. def max(self):
  42. return max(self.deque)
  43. @property
  44. def value(self):
  45. return self.deque[-1]
  46. def __str__(self):
  47. return self.fmt.format(
  48. median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
  49. )
  50. class MetricLogger:
  51. def __init__(self, delimiter="\t"):
  52. self.meters = defaultdict(SmoothedValue)
  53. self.delimiter = delimiter
  54. def update(self, **kwargs):
  55. for k, v in kwargs.items():
  56. if isinstance(v, torch.Tensor):
  57. v = v.item()
  58. if not isinstance(v, (float, int)):
  59. raise TypeError(
  60. f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
  61. )
  62. self.meters[k].update(v)
  63. def __getattr__(self, attr):
  64. if attr in self.meters:
  65. return self.meters[attr]
  66. if attr in self.__dict__:
  67. return self.__dict__[attr]
  68. raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
  69. def __str__(self):
  70. loss_str = []
  71. for name, meter in self.meters.items():
  72. loss_str.append(f"{name}: {str(meter)}")
  73. return self.delimiter.join(loss_str)
  74. def synchronize_between_processes(self):
  75. for meter in self.meters.values():
  76. meter.synchronize_between_processes()
  77. def add_meter(self, name, **kwargs):
  78. self.meters[name] = SmoothedValue(**kwargs)
  79. def log_every(self, iterable, print_freq=5, header=None):
  80. i = 0
  81. if not header:
  82. header = ""
  83. start_time = time.time()
  84. end = time.time()
  85. iter_time = SmoothedValue(fmt="{avg:.4f}")
  86. data_time = SmoothedValue(fmt="{avg:.4f}")
  87. space_fmt = ":" + str(len(str(len(iterable)))) + "d"
  88. if torch.cuda.is_available():
  89. log_msg = self.delimiter.join(
  90. [
  91. header,
  92. "[{0" + space_fmt + "}/{1}]",
  93. "eta: {eta}",
  94. "{meters}",
  95. "time: {time}",
  96. "data: {data}",
  97. "max mem: {memory:.0f}",
  98. ]
  99. )
  100. else:
  101. log_msg = self.delimiter.join(
  102. [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
  103. )
  104. MB = 1024.0 * 1024.0
  105. for obj in iterable:
  106. data_time.update(time.time() - end)
  107. yield obj
  108. iter_time.update(time.time() - end)
  109. if print_freq is not None and i % print_freq == 0:
  110. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  111. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  112. if torch.cuda.is_available():
  113. print(
  114. log_msg.format(
  115. i,
  116. len(iterable),
  117. eta=eta_string,
  118. meters=str(self),
  119. time=str(iter_time),
  120. data=str(data_time),
  121. memory=torch.cuda.max_memory_allocated() / MB,
  122. )
  123. )
  124. else:
  125. print(
  126. log_msg.format(
  127. i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
  128. )
  129. )
  130. i += 1
  131. end = time.time()
  132. total_time = time.time() - start_time
  133. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  134. print(f"{header} Total time: {total_time_str}")
  135. def compute_metrics(flow_pred, flow_gt, valid_flow_mask=None):
  136. epe = ((flow_pred - flow_gt) ** 2).sum(dim=1).sqrt()
  137. flow_norm = (flow_gt**2).sum(dim=1).sqrt()
  138. if valid_flow_mask is not None:
  139. epe = epe[valid_flow_mask]
  140. flow_norm = flow_norm[valid_flow_mask]
  141. relative_epe = epe / flow_norm
  142. metrics = {
  143. "epe": epe.mean().item(),
  144. "1px": (epe < 1).float().mean().item(),
  145. "3px": (epe < 3).float().mean().item(),
  146. "5px": (epe < 5).float().mean().item(),
  147. "f1": ((epe > 3) & (relative_epe > 0.05)).float().mean().item() * 100,
  148. }
  149. return metrics, epe.numel()
  150. def sequence_loss(flow_preds, flow_gt, valid_flow_mask, gamma=0.8, max_flow=400):
  151. """Loss function defined over sequence of flow predictions"""
  152. if gamma > 1:
  153. raise ValueError(f"Gamma should be < 1, got {gamma}.")
  154. # exclude invalid pixels and extremely large diplacements
  155. flow_norm = torch.sum(flow_gt**2, dim=1).sqrt()
  156. valid_flow_mask = valid_flow_mask & (flow_norm < max_flow)
  157. valid_flow_mask = valid_flow_mask[:, None, :, :]
  158. flow_preds = torch.stack(flow_preds) # shape = (num_flow_updates, batch_size, 2, H, W)
  159. abs_diff = (flow_preds - flow_gt).abs()
  160. abs_diff = (abs_diff * valid_flow_mask).mean(axis=(1, 2, 3, 4))
  161. num_predictions = flow_preds.shape[0]
  162. weights = gamma ** torch.arange(num_predictions - 1, -1, -1).to(flow_gt.device)
  163. flow_loss = (abs_diff * weights).sum()
  164. return flow_loss
  165. class InputPadder:
  166. """Pads images such that dimensions are divisible by 8"""
  167. # TODO: Ideally, this should be part of the eval transforms preset, instead
  168. # of being part of the validation code. It's not obvious what a good
  169. # solution would be, because we need to unpad the predicted flows according
  170. # to the input images' size, and in some datasets (Kitti) images can have
  171. # variable sizes.
  172. def __init__(self, dims, mode="sintel"):
  173. self.ht, self.wd = dims[-2:]
  174. pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8
  175. pad_wd = (((self.wd // 8) + 1) * 8 - self.wd) % 8
  176. if mode == "sintel":
  177. self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2]
  178. else:
  179. self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, 0, pad_ht]
  180. def pad(self, *inputs):
  181. return [F.pad(x, self._pad, mode="replicate") for x in inputs]
  182. def unpad(self, x):
  183. ht, wd = x.shape[-2:]
  184. c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]
  185. return x[..., c[0] : c[1], c[2] : c[3]]
  186. def _redefine_print(is_main):
  187. """disables printing when not in main process"""
  188. import builtins as __builtin__
  189. builtin_print = __builtin__.print
  190. def print(*args, **kwargs):
  191. force = kwargs.pop("force", False)
  192. if is_main or force:
  193. builtin_print(*args, **kwargs)
  194. __builtin__.print = print
  195. def setup_ddp(args):
  196. # Set the local_rank, rank, and world_size values as args fields
  197. # This is done differently depending on how we're running the script. We
  198. # currently support either torchrun or the custom run_with_submitit.py
  199. # If you're confused (like I was), this might help a bit
  200. # https://discuss.pytorch.org/t/what-is-the-difference-between-rank-and-local-rank/61940/2
  201. if all(key in os.environ for key in ("LOCAL_RANK", "RANK", "WORLD_SIZE")):
  202. # if we're here, the script was called with torchrun. Otherwise,
  203. # these args will be set already by the run_with_submitit script
  204. args.local_rank = int(os.environ["LOCAL_RANK"])
  205. args.rank = int(os.environ["RANK"])
  206. args.world_size = int(os.environ["WORLD_SIZE"])
  207. elif "gpu" in args:
  208. # if we're here, the script was called by run_with_submitit.py
  209. args.local_rank = args.gpu
  210. else:
  211. print("Not using distributed mode!")
  212. args.distributed = False
  213. args.world_size = 1
  214. return
  215. args.distributed = True
  216. _redefine_print(is_main=(args.rank == 0))
  217. torch.cuda.set_device(args.local_rank)
  218. dist.init_process_group(
  219. backend="nccl",
  220. rank=args.rank,
  221. world_size=args.world_size,
  222. init_method=args.dist_url,
  223. )
  224. torch.distributed.barrier()
  225. def reduce_across_processes(val):
  226. t = torch.tensor(val, device="cuda")
  227. dist.barrier()
  228. dist.all_reduce(t)
  229. return t
  230. def freeze_batch_norm(model):
  231. for m in model.modules():
  232. if isinstance(m, torch.nn.BatchNorm2d):
  233. m.eval()