utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import datetime
  2. import errno
  3. import os
  4. import time
  5. from collections import defaultdict, deque
  6. import torch
  7. import torch.distributed as dist
  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=None):
  13. if fmt is None:
  14. fmt = "{median:.4f} ({global_avg:.4f})"
  15. self.deque = deque(maxlen=window_size)
  16. self.total = 0.0
  17. self.count = 0
  18. self.fmt = fmt
  19. def update(self, value, n=1):
  20. self.deque.append(value)
  21. self.count += n
  22. self.total += value * n
  23. def synchronize_between_processes(self):
  24. """
  25. Warning: does not synchronize the deque!
  26. """
  27. t = reduce_across_processes([self.count, self.total])
  28. t = t.tolist()
  29. self.count = int(t[0])
  30. self.total = t[1]
  31. @property
  32. def median(self):
  33. d = torch.tensor(list(self.deque))
  34. return d.median().item()
  35. @property
  36. def avg(self):
  37. d = torch.tensor(list(self.deque), dtype=torch.float32)
  38. return d.mean().item()
  39. @property
  40. def global_avg(self):
  41. return self.total / self.count
  42. @property
  43. def max(self):
  44. return max(self.deque)
  45. @property
  46. def value(self):
  47. return self.deque[-1]
  48. def __str__(self):
  49. return self.fmt.format(
  50. median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
  51. )
  52. class ConfusionMatrix:
  53. def __init__(self, num_classes):
  54. self.num_classes = num_classes
  55. self.mat = None
  56. def update(self, a, b):
  57. n = self.num_classes
  58. if self.mat is None:
  59. self.mat = torch.zeros((n, n), dtype=torch.int64, device=a.device)
  60. with torch.inference_mode():
  61. k = (a >= 0) & (a < n)
  62. inds = n * a[k].to(torch.int64) + b[k]
  63. self.mat += torch.bincount(inds, minlength=n**2).reshape(n, n)
  64. def reset(self):
  65. self.mat.zero_()
  66. def compute(self):
  67. h = self.mat.float()
  68. acc_global = torch.diag(h).sum() / h.sum()
  69. acc = torch.diag(h) / h.sum(1)
  70. iu = torch.diag(h) / (h.sum(1) + h.sum(0) - torch.diag(h))
  71. return acc_global, acc, iu
  72. def reduce_from_all_processes(self):
  73. reduce_across_processes(self.mat)
  74. def __str__(self):
  75. acc_global, acc, iu = self.compute()
  76. return ("global correct: {:.1f}\naverage row correct: {}\nIoU: {}\nmean IoU: {:.1f}").format(
  77. acc_global.item() * 100,
  78. [f"{i:.1f}" for i in (acc * 100).tolist()],
  79. [f"{i:.1f}" for i in (iu * 100).tolist()],
  80. iu.mean().item() * 100,
  81. )
  82. class MetricLogger:
  83. def __init__(self, delimiter="\t"):
  84. self.meters = defaultdict(SmoothedValue)
  85. self.delimiter = delimiter
  86. def update(self, **kwargs):
  87. for k, v in kwargs.items():
  88. if isinstance(v, torch.Tensor):
  89. v = v.item()
  90. if not isinstance(v, (float, int)):
  91. raise TypeError(
  92. f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
  93. )
  94. self.meters[k].update(v)
  95. def __getattr__(self, attr):
  96. if attr in self.meters:
  97. return self.meters[attr]
  98. if attr in self.__dict__:
  99. return self.__dict__[attr]
  100. raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
  101. def __str__(self):
  102. loss_str = []
  103. for name, meter in self.meters.items():
  104. loss_str.append(f"{name}: {str(meter)}")
  105. return self.delimiter.join(loss_str)
  106. def synchronize_between_processes(self):
  107. for meter in self.meters.values():
  108. meter.synchronize_between_processes()
  109. def add_meter(self, name, meter):
  110. self.meters[name] = meter
  111. def log_every(self, iterable, print_freq, header=None):
  112. i = 0
  113. if not header:
  114. header = ""
  115. start_time = time.time()
  116. end = time.time()
  117. iter_time = SmoothedValue(fmt="{avg:.4f}")
  118. data_time = SmoothedValue(fmt="{avg:.4f}")
  119. space_fmt = ":" + str(len(str(len(iterable)))) + "d"
  120. if torch.cuda.is_available():
  121. log_msg = self.delimiter.join(
  122. [
  123. header,
  124. "[{0" + space_fmt + "}/{1}]",
  125. "eta: {eta}",
  126. "{meters}",
  127. "time: {time}",
  128. "data: {data}",
  129. "max mem: {memory:.0f}",
  130. ]
  131. )
  132. else:
  133. log_msg = self.delimiter.join(
  134. [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
  135. )
  136. MB = 1024.0 * 1024.0
  137. for obj in iterable:
  138. data_time.update(time.time() - end)
  139. yield obj
  140. iter_time.update(time.time() - end)
  141. if i % print_freq == 0:
  142. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  143. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  144. if torch.cuda.is_available():
  145. print(
  146. log_msg.format(
  147. i,
  148. len(iterable),
  149. eta=eta_string,
  150. meters=str(self),
  151. time=str(iter_time),
  152. data=str(data_time),
  153. memory=torch.cuda.max_memory_allocated() / MB,
  154. )
  155. )
  156. else:
  157. print(
  158. log_msg.format(
  159. i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
  160. )
  161. )
  162. i += 1
  163. end = time.time()
  164. total_time = time.time() - start_time
  165. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  166. print(f"{header} Total time: {total_time_str}")
  167. def cat_list(images, fill_value=0):
  168. max_size = tuple(max(s) for s in zip(*[img.shape for img in images]))
  169. batch_shape = (len(images),) + max_size
  170. batched_imgs = images[0].new(*batch_shape).fill_(fill_value)
  171. for img, pad_img in zip(images, batched_imgs):
  172. pad_img[..., : img.shape[-2], : img.shape[-1]].copy_(img)
  173. return batched_imgs
  174. def collate_fn(batch):
  175. images, targets = list(zip(*batch))
  176. batched_imgs = cat_list(images, fill_value=0)
  177. batched_targets = cat_list(targets, fill_value=255)
  178. return batched_imgs, batched_targets
  179. def mkdir(path):
  180. try:
  181. os.makedirs(path)
  182. except OSError as e:
  183. if e.errno != errno.EEXIST:
  184. raise
  185. def setup_for_distributed(is_master):
  186. """
  187. This function disables printing when not in master process
  188. """
  189. import builtins as __builtin__
  190. builtin_print = __builtin__.print
  191. def print(*args, **kwargs):
  192. force = kwargs.pop("force", False)
  193. if is_master or force:
  194. builtin_print(*args, **kwargs)
  195. __builtin__.print = print
  196. def is_dist_avail_and_initialized():
  197. if not dist.is_available():
  198. return False
  199. if not dist.is_initialized():
  200. return False
  201. return True
  202. def get_world_size():
  203. if not is_dist_avail_and_initialized():
  204. return 1
  205. return dist.get_world_size()
  206. def get_rank():
  207. if not is_dist_avail_and_initialized():
  208. return 0
  209. return dist.get_rank()
  210. def is_main_process():
  211. return get_rank() == 0
  212. def save_on_master(*args, **kwargs):
  213. if is_main_process():
  214. torch.save(*args, **kwargs)
  215. def init_distributed_mode(args):
  216. if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
  217. args.rank = int(os.environ["RANK"])
  218. args.world_size = int(os.environ["WORLD_SIZE"])
  219. args.gpu = int(os.environ["LOCAL_RANK"])
  220. # elif "SLURM_PROCID" in os.environ:
  221. # args.rank = int(os.environ["SLURM_PROCID"])
  222. # args.gpu = args.rank % torch.cuda.device_count()
  223. elif hasattr(args, "rank"):
  224. pass
  225. else:
  226. print("Not using distributed mode")
  227. args.distributed = False
  228. return
  229. args.distributed = True
  230. torch.cuda.set_device(args.gpu)
  231. args.dist_backend = "nccl"
  232. print(f"| distributed init (rank {args.rank}): {args.dist_url}", flush=True)
  233. torch.distributed.init_process_group(
  234. backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank
  235. )
  236. torch.distributed.barrier()
  237. setup_for_distributed(args.rank == 0)
  238. def reduce_across_processes(val):
  239. if not is_dist_avail_and_initialized():
  240. # nothing to sync, but we still convert to tensor for consistency with the distributed case.
  241. return torch.tensor(val)
  242. t = torch.tensor(val, device="cuda")
  243. dist.barrier()
  244. dist.all_reduce(t)
  245. return t