You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

243 lines
9.4KB

  1. # PyTorch utils
  2. import logging
  3. import os
  4. import time
  5. from contextlib import contextmanager
  6. from copy import deepcopy
  7. import math
  8. import torch
  9. import torch.backends.cudnn as cudnn
  10. import torch.nn as nn
  11. import torch.nn.functional as F
  12. import torchvision
  13. logger = logging.getLogger(__name__)
  14. @contextmanager
  15. def torch_distributed_zero_first(local_rank: int):
  16. """
  17. Decorator to make all processes in distributed training wait for each local_master to do something.
  18. """
  19. if local_rank not in [-1, 0]:
  20. torch.distributed.barrier()
  21. yield
  22. if local_rank == 0:
  23. torch.distributed.barrier()
  24. def init_torch_seeds(seed=0):
  25. # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
  26. torch.manual_seed(seed)
  27. if seed == 0: # slower, more reproducible
  28. cudnn.deterministic = True
  29. cudnn.benchmark = False
  30. else: # faster, less reproducible
  31. cudnn.deterministic = False
  32. cudnn.benchmark = True
  33. def select_device(device='', batch_size=None):
  34. # device = 'cpu' or '0' or '0,1,2,3'
  35. cpu_request = device.lower() == 'cpu'
  36. if device and not cpu_request: # if device requested other than 'cpu'
  37. os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
  38. assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity
  39. cuda = False if cpu_request else torch.cuda.is_available()
  40. if cuda:
  41. c = 1024 ** 2 # bytes to MB
  42. ng = torch.cuda.device_count()
  43. if ng > 1 and batch_size: # check that batch_size is compatible with device_count
  44. assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng)
  45. x = [torch.cuda.get_device_properties(i) for i in range(ng)]
  46. s = f'Using torch {torch.__version__} '
  47. for i in range(0, ng):
  48. if i == 1:
  49. s = ' ' * len(s)
  50. logger.info("%sCUDA:%g (%s, %dMB)" % (s, i, x[i].name, x[i].total_memory / c))
  51. else:
  52. logger.info(f'Using torch {torch.__version__} CPU')
  53. logger.info('') # skip a line
  54. return torch.device('cuda:0' if cuda else 'cpu')
  55. def time_synchronized():
  56. torch.cuda.synchronize() if torch.cuda.is_available() else None
  57. return time.time()
  58. def is_parallel(model):
  59. return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
  60. def intersect_dicts(da, db, exclude=()):
  61. # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
  62. return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
  63. def initialize_weights(model):
  64. for m in model.modules():
  65. t = type(m)
  66. if t is nn.Conv2d:
  67. pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  68. elif t is nn.BatchNorm2d:
  69. m.eps = 1e-3
  70. m.momentum = 0.03
  71. elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
  72. m.inplace = True
  73. def find_modules(model, mclass=nn.Conv2d):
  74. # Finds layer indices matching module class 'mclass'
  75. return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
  76. def sparsity(model):
  77. # Return global model sparsity
  78. a, b = 0., 0.
  79. for p in model.parameters():
  80. a += p.numel()
  81. b += (p == 0).sum()
  82. return b / a
  83. def prune(model, amount=0.3):
  84. # Prune model to requested global sparsity
  85. import torch.nn.utils.prune as prune
  86. print('Pruning model... ', end='')
  87. for name, m in model.named_modules():
  88. if isinstance(m, nn.Conv2d):
  89. prune.l1_unstructured(m, name='weight', amount=amount) # prune
  90. prune.remove(m, 'weight') # make permanent
  91. print(' %.3g global sparsity' % sparsity(model))
  92. def fuse_conv_and_bn(conv, bn):
  93. # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
  94. fusedconv = nn.Conv2d(conv.in_channels,
  95. conv.out_channels,
  96. kernel_size=conv.kernel_size,
  97. stride=conv.stride,
  98. padding=conv.padding,
  99. groups=conv.groups,
  100. bias=True).requires_grad_(False).to(conv.weight.device)
  101. # prepare filters
  102. w_conv = conv.weight.clone().view(conv.out_channels, -1)
  103. w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
  104. fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
  105. # prepare spatial bias
  106. b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
  107. b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
  108. fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
  109. return fusedconv
  110. def model_info(model, verbose=False, img_size=640):
  111. # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
  112. n_p = sum(x.numel() for x in model.parameters()) # number parameters
  113. n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
  114. if verbose:
  115. print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
  116. for i, (name, p) in enumerate(model.named_parameters()):
  117. name = name.replace('module_list.', '')
  118. print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
  119. (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
  120. try: # FLOPS
  121. from thop import profile
  122. stride = int(model.stride.max()) if hasattr(model, 'stride') else 32
  123. img = torch.zeros((1, 3, stride, stride), device=next(model.parameters()).device) # input
  124. flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride FLOPS
  125. img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
  126. fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 FLOPS
  127. except (ImportError, Exception):
  128. fs = ''
  129. logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
  130. def load_classifier(name='resnet101', n=2):
  131. # Loads a pretrained model reshaped to n-class output
  132. model = torchvision.models.__dict__[name](pretrained=True)
  133. # ResNet model properties
  134. # input_size = [3, 224, 224]
  135. # input_space = 'RGB'
  136. # input_range = [0, 1]
  137. # mean = [0.485, 0.456, 0.406]
  138. # std = [0.229, 0.224, 0.225]
  139. # Reshape output to n classes
  140. filters = model.fc.weight.shape[1]
  141. model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
  142. model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
  143. model.fc.out_features = n
  144. return model
  145. def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio
  146. # scales img(bs,3,y,x) by ratio
  147. if ratio == 1.0:
  148. return img
  149. else:
  150. h, w = img.shape[2:]
  151. s = (int(h * ratio), int(w * ratio)) # new size
  152. img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
  153. if not same_shape: # pad/crop img
  154. gs = 32 # (pixels) grid size
  155. h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
  156. return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
  157. def copy_attr(a, b, include=(), exclude=()):
  158. # Copy attributes from b to a, options to only include [...] and to exclude [...]
  159. for k, v in b.__dict__.items():
  160. if (len(include) and k not in include) or k.startswith('_') or k in exclude:
  161. continue
  162. else:
  163. setattr(a, k, v)
  164. class ModelEMA:
  165. """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
  166. Keep a moving average of everything in the model state_dict (parameters and buffers).
  167. This is intended to allow functionality like
  168. https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
  169. A smoothed version of the weights is necessary for some training schemes to perform well.
  170. This class is sensitive where it is initialized in the sequence of model init,
  171. GPU assignment and distributed training wrappers.
  172. """
  173. def __init__(self, model, decay=0.9999, updates=0):
  174. # Create EMA
  175. self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
  176. # if next(model.parameters()).device.type != 'cpu':
  177. # self.ema.half() # FP16 EMA
  178. self.updates = updates # number of EMA updates
  179. self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
  180. for p in self.ema.parameters():
  181. p.requires_grad_(False)
  182. def update(self, model):
  183. # Update EMA parameters
  184. with torch.no_grad():
  185. self.updates += 1
  186. d = self.decay(self.updates)
  187. msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
  188. for k, v in self.ema.state_dict().items():
  189. if v.dtype.is_floating_point:
  190. v *= d
  191. v += (1. - d) * msd[k].detach()
  192. def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
  193. # Update EMA attributes
  194. copy_attr(self.ema, model, include, exclude)