misc.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import time
  2. import torch
  3. import numpy as np
  4. import random
  5. import datetime
  6. from collections import defaultdict, deque
  7. from pathlib import Path
  8. # ---------------------- Common functions ----------------------
  9. def setup_seed(seed=42):
  10. torch.manual_seed(seed)
  11. torch.cuda.manual_seed_all(seed)
  12. np.random.seed(seed)
  13. random.seed(seed)
  14. torch.backends.cudnn.deterministic = True
  15. def accuracy(output, target, topk=(1,)):
  16. """Computes the accuracy over the k top predictions for the specified values of k"""
  17. with torch.no_grad():
  18. maxk = max(topk)
  19. batch_size = target.size(0)
  20. _, pred = output.topk(maxk, 1, True, True)
  21. pred = pred.t()
  22. correct = pred.eq(target.reshape(1, -1).expand_as(pred))
  23. res = []
  24. for k in topk:
  25. correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
  26. res.append(correct_k.mul_(100.0 / batch_size))
  27. return res
  28. class SmoothedValue(object):
  29. """Track a series of values and provide access to smoothed values over a
  30. window or the global series average.
  31. """
  32. def __init__(self, window_size=20, fmt=None):
  33. if fmt is None:
  34. fmt = "{median:.4f} ({global_avg:.4f})"
  35. self.deque = deque(maxlen=window_size)
  36. self.total = 0.0
  37. self.count = 0
  38. self.fmt = fmt
  39. def update(self, value, n=1):
  40. self.deque.append(value)
  41. self.count += n
  42. self.total += value * n
  43. @property
  44. def median(self):
  45. d = torch.tensor(list(self.deque))
  46. return d.median().item()
  47. @property
  48. def avg(self):
  49. d = torch.tensor(list(self.deque), dtype=torch.float32)
  50. return d.mean().item()
  51. @property
  52. def global_avg(self):
  53. return self.total / self.count
  54. @property
  55. def max(self):
  56. return max(self.deque)
  57. @property
  58. def value(self):
  59. return self.deque[-1]
  60. def __str__(self):
  61. return self.fmt.format(
  62. median=self.median,
  63. avg=self.avg,
  64. global_avg=self.global_avg,
  65. max=self.max,
  66. value=self.value)
  67. class MetricLogger(object):
  68. def __init__(self, delimiter="\t"):
  69. self.meters = defaultdict(SmoothedValue)
  70. self.delimiter = delimiter
  71. def update(self, **kwargs):
  72. for k, v in kwargs.items():
  73. if v is None:
  74. continue
  75. if isinstance(v, torch.Tensor):
  76. v = v.item()
  77. assert isinstance(v, (float, int))
  78. self.meters[k].update(v)
  79. def __getattr__(self, attr):
  80. if attr in self.meters:
  81. return self.meters[attr]
  82. if attr in self.__dict__:
  83. return self.__dict__[attr]
  84. raise AttributeError("'{}' object has no attribute '{}'".format(
  85. type(self).__name__, attr))
  86. def __str__(self):
  87. loss_str = []
  88. for name, meter in self.meters.items():
  89. loss_str.append(
  90. "{}: {}".format(name, str(meter))
  91. )
  92. return self.delimiter.join(loss_str)
  93. def add_meter(self, name, meter):
  94. self.meters[name] = meter
  95. def log_every(self, iterable, print_freq, header=None):
  96. i = 0
  97. if not header:
  98. header = ''
  99. start_time = time.time()
  100. end = time.time()
  101. iter_time = SmoothedValue(fmt='{avg:.4f}')
  102. data_time = SmoothedValue(fmt='{avg:.4f}')
  103. space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
  104. log_msg = [
  105. header,
  106. '[{0' + space_fmt + '}/{1}]',
  107. 'eta: {eta}',
  108. '{meters}',
  109. 'time: {time}',
  110. 'data: {data}'
  111. ]
  112. if torch.cuda.is_available():
  113. log_msg.append('max mem: {memory:.0f}')
  114. log_msg = self.delimiter.join(log_msg)
  115. MB = 1024.0 * 1024.0
  116. for obj in iterable:
  117. data_time.update(time.time() - end)
  118. yield obj
  119. iter_time.update(time.time() - end)
  120. if i % print_freq == 0 or i == len(iterable) - 1:
  121. eta_seconds = iter_time.global_avg * (len(iterable) - i)
  122. eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
  123. if torch.cuda.is_available():
  124. print(log_msg.format(
  125. i, len(iterable), eta=eta_string,
  126. meters=str(self),
  127. time=str(iter_time), data=str(data_time),
  128. memory=torch.cuda.max_memory_allocated() / MB))
  129. else:
  130. print(log_msg.format(
  131. i, len(iterable), eta=eta_string,
  132. meters=str(self),
  133. time=str(iter_time), data=str(data_time)))
  134. i += 1
  135. end = time.time()
  136. total_time = time.time() - start_time
  137. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  138. print('{} Total time: {} ({:.4f} s / it)'.format(
  139. header, total_time_str, total_time / len(iterable)))
  140. # ---------------------- Model functions ----------------------
  141. def load_model(args, model, optimizer, lr_scheduler):
  142. if args.resume and args.resume.lower() != 'none':
  143. print("=================== Load checkpoint ===================")
  144. if args.resume.startswith('https'):
  145. checkpoint = torch.hub.load_state_dict_from_url(
  146. args.resume, map_location='cpu', check_hash=True)
  147. else:
  148. checkpoint = torch.load(args.resume, map_location='cpu')
  149. model.load_state_dict(checkpoint['model'])
  150. print("Resume checkpoint %s" % args.resume)
  151. if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
  152. print('- Load optimizer from the checkpoint. ')
  153. optimizer.load_state_dict(checkpoint['optimizer'])
  154. args.start_epoch = checkpoint['epoch'] + 1
  155. if 'lr_scheduler' in checkpoint:
  156. print('- Load lr scheduler from the checkpoint. ')
  157. lr_scheduler.load_state_dict(checkpoint.pop("lr_scheduler"))
  158. def save_model(args, epoch, model, optimizer, lr_scheduler, acc1=None, mae_task=False):
  159. output_dir = Path(args.output_dir)
  160. epoch_name = str(epoch)
  161. if acc1 is not None:
  162. checkpoint_paths = [output_dir / ('checkpoint-{}-Acc1-{:.2f}.pth'.format(epoch_name, acc1))]
  163. else:
  164. checkpoint_paths = [output_dir / ('checkpoint-{}.pth'.format(epoch_name))]
  165. for checkpoint_path in checkpoint_paths:
  166. to_save = {
  167. 'model': model.state_dict(),
  168. 'optimizer': optimizer.state_dict(),
  169. 'lr_scheduler': lr_scheduler.state_dict(),
  170. 'epoch': epoch,
  171. 'args': args,
  172. }
  173. if mae_task:
  174. to_save['encoder'] = model.mae_encoder.state_dict()
  175. torch.save(to_save, checkpoint_path)
  176. # ---------------------- Patch operations ----------------------
  177. def patchify(imgs, patch_size):
  178. """
  179. imgs: (B, 3, H, W)
  180. x: (N, L, patch_size**2 *3)
  181. """
  182. p = patch_size
  183. assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0
  184. h = w = imgs.shape[2] // p
  185. x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p))
  186. x = torch.einsum('nchpwq->nhwpqc', x)
  187. x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3))
  188. return x
  189. def unpatchify(x, patch_size):
  190. """
  191. x: (B, N, patch_size**2 *3)
  192. imgs: (B, 3, H, W)
  193. """
  194. p = patch_size
  195. h = w = int(x.shape[1]**.5)
  196. assert h * w == x.shape[1]
  197. x = x.reshape(shape=(x.shape[0], h, w, p, p, 3))
  198. x = torch.einsum('nhwpqc->nchpwq', x)
  199. imgs = x.reshape(shape=(x.shape[0], 3, h * p, h * p))
  200. return imgs