| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- import time
- import torch
- import numpy as np
- import random
- import datetime
- from collections import defaultdict, deque
- from pathlib import Path
- # ---------------------- Common functions ----------------------
- def setup_seed(seed=42):
- torch.manual_seed(seed)
- torch.cuda.manual_seed_all(seed)
- np.random.seed(seed)
- random.seed(seed)
- torch.backends.cudnn.deterministic = True
- def accuracy(output, target, topk=(1,)):
- """Computes the accuracy over the k top predictions for the specified values of k"""
- with torch.no_grad():
- maxk = max(topk)
- batch_size = target.size(0)
- _, pred = output.topk(maxk, 1, True, True)
- pred = pred.t()
- correct = pred.eq(target.reshape(1, -1).expand_as(pred))
- res = []
- for k in topk:
- correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
- res.append(correct_k.mul_(100.0 / batch_size))
- return res
- class SmoothedValue(object):
- """Track a series of values and provide access to smoothed values over a
- window or the global series average.
- """
- def __init__(self, window_size=20, fmt=None):
- if fmt is None:
- fmt = "{median:.4f} ({global_avg:.4f})"
- self.deque = deque(maxlen=window_size)
- self.total = 0.0
- self.count = 0
- self.fmt = fmt
- def update(self, value, n=1):
- self.deque.append(value)
- self.count += n
- self.total += value * n
- @property
- def median(self):
- d = torch.tensor(list(self.deque))
- return d.median().item()
- @property
- def avg(self):
- d = torch.tensor(list(self.deque), dtype=torch.float32)
- return d.mean().item()
- @property
- def global_avg(self):
- return self.total / self.count
- @property
- def max(self):
- return max(self.deque)
- @property
- def value(self):
- return self.deque[-1]
- def __str__(self):
- return self.fmt.format(
- median=self.median,
- avg=self.avg,
- global_avg=self.global_avg,
- max=self.max,
- value=self.value)
- class MetricLogger(object):
- def __init__(self, delimiter="\t"):
- self.meters = defaultdict(SmoothedValue)
- self.delimiter = delimiter
- def update(self, **kwargs):
- for k, v in kwargs.items():
- if v is None:
- continue
- if isinstance(v, torch.Tensor):
- v = v.item()
- assert isinstance(v, (float, int))
- self.meters[k].update(v)
- def __getattr__(self, attr):
- if attr in self.meters:
- return self.meters[attr]
- if attr in self.__dict__:
- return self.__dict__[attr]
- raise AttributeError("'{}' object has no attribute '{}'".format(
- type(self).__name__, attr))
- def __str__(self):
- loss_str = []
- for name, meter in self.meters.items():
- loss_str.append(
- "{}: {}".format(name, str(meter))
- )
- return self.delimiter.join(loss_str)
- def add_meter(self, name, meter):
- self.meters[name] = meter
- def log_every(self, iterable, print_freq, header=None):
- i = 0
- if not header:
- header = ''
- start_time = time.time()
- end = time.time()
- iter_time = SmoothedValue(fmt='{avg:.4f}')
- data_time = SmoothedValue(fmt='{avg:.4f}')
- space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
- log_msg = [
- header,
- '[{0' + space_fmt + '}/{1}]',
- 'eta: {eta}',
- '{meters}',
- 'time: {time}',
- 'data: {data}'
- ]
- if torch.cuda.is_available():
- log_msg.append('max mem: {memory:.0f}')
- log_msg = self.delimiter.join(log_msg)
- MB = 1024.0 * 1024.0
- for obj in iterable:
- data_time.update(time.time() - end)
- yield obj
- iter_time.update(time.time() - end)
- if i % print_freq == 0 or i == len(iterable) - 1:
- eta_seconds = iter_time.global_avg * (len(iterable) - i)
- eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
- if torch.cuda.is_available():
- print(log_msg.format(
- i, len(iterable), eta=eta_string,
- meters=str(self),
- time=str(iter_time), data=str(data_time),
- memory=torch.cuda.max_memory_allocated() / MB))
- else:
- print(log_msg.format(
- i, len(iterable), eta=eta_string,
- meters=str(self),
- time=str(iter_time), data=str(data_time)))
- i += 1
- end = time.time()
- total_time = time.time() - start_time
- total_time_str = str(datetime.timedelta(seconds=int(total_time)))
- print('{} Total time: {} ({:.4f} s / it)'.format(
- header, total_time_str, total_time / len(iterable)))
- # ---------------------- Model functions ----------------------
- def load_model(args, model, optimizer, lr_scheduler):
- if args.resume and args.resume.lower() != 'none':
- print("=================== Load checkpoint ===================")
- if args.resume.startswith('https'):
- checkpoint = torch.hub.load_state_dict_from_url(
- args.resume, map_location='cpu', check_hash=True)
- else:
- checkpoint = torch.load(args.resume, map_location='cpu')
- model.load_state_dict(checkpoint['model'])
- print("Resume checkpoint %s" % args.resume)
-
- if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
- print('- Load optimizer from the checkpoint. ')
- optimizer.load_state_dict(checkpoint['optimizer'])
- args.start_epoch = checkpoint['epoch'] + 1
- if 'lr_scheduler' in checkpoint:
- print('- Load lr scheduler from the checkpoint. ')
- lr_scheduler.load_state_dict(checkpoint.pop("lr_scheduler"))
- def save_model(args, epoch, model, optimizer, lr_scheduler, acc1=None, mae_task=False):
- output_dir = Path(args.output_dir)
- epoch_name = str(epoch)
- if acc1 is not None:
- checkpoint_paths = [output_dir / ('checkpoint-{}-Acc1-{:.2f}.pth'.format(epoch_name, acc1))]
- else:
- checkpoint_paths = [output_dir / ('checkpoint-{}.pth'.format(epoch_name))]
- for checkpoint_path in checkpoint_paths:
- to_save = {
- 'model': model.state_dict(),
- 'optimizer': optimizer.state_dict(),
- 'lr_scheduler': lr_scheduler.state_dict(),
- 'epoch': epoch,
- 'args': args,
- }
- if mae_task:
- to_save['encoder'] = model.mae_encoder.state_dict()
- torch.save(to_save, checkpoint_path)
- # ---------------------- Patch operations ----------------------
- def patchify(imgs, patch_size):
- """
- imgs: (B, 3, H, W)
- x: (N, L, patch_size**2 *3)
- """
- p = patch_size
- assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0
- h = w = imgs.shape[2] // p
- x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p))
- x = torch.einsum('nchpwq->nhwpqc', x)
- x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3))
- return x
- def unpatchify(x, patch_size):
- """
- x: (B, N, patch_size**2 *3)
- imgs: (B, 3, H, W)
- """
- p = patch_size
- h = w = int(x.shape[1]**.5)
- assert h * w == x.shape[1]
-
- x = x.reshape(shape=(x.shape[0], h, w, p, p, 3))
- x = torch.einsum('nhwpqc->nchpwq', x)
- imgs = x.reshape(shape=(x.shape[0], 3, h * p, h * p))
- return imgs
|