torch_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. # YOLOv5 PyTorch utils
  2. import datetime
  3. import logging
  4. import math
  5. import os
  6. import platform
  7. import subprocess
  8. import time
  9. from contextlib import contextmanager
  10. from copy import deepcopy
  11. from pathlib import Path
  12. import torch
  13. import torch.backends.cudnn as cudnn
  14. import torch.nn as nn
  15. import torch.nn.functional as F
  16. import torchvision
  17. try:
  18. import thop # for FLOPS computation
  19. except ImportError:
  20. thop = None
  21. logger = logging.getLogger(__name__)
  22. @contextmanager
  23. def torch_distributed_zero_first(local_rank: int):
  24. """
  25. Decorator to make all processes in distributed training wait for each local_master to do something.
  26. """
  27. if local_rank not in [-1, 0]:
  28. torch.distributed.barrier()
  29. yield
  30. if local_rank == 0:
  31. torch.distributed.barrier()
  32. def init_torch_seeds(seed=0):
  33. # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
  34. torch.manual_seed(seed)
  35. if seed == 0: # slower, more reproducible
  36. cudnn.benchmark, cudnn.deterministic = False, True
  37. else: # faster, less reproducible
  38. cudnn.benchmark, cudnn.deterministic = True, False
  39. def date_modified(path=__file__):
  40. # return human-readable file modification date, i.e. '2021-3-26'
  41. t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
  42. return f'{t.year}-{t.month}-{t.day}'
  43. def git_describe(path=Path(__file__).parent): # path must be a directory
  44. # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
  45. s = f'git -C {path} describe --tags --long --always'
  46. try:
  47. return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
  48. except subprocess.CalledProcessError as e:
  49. return '' # not a git repository
  50. def select_device(device='', batch_size=None):
  51. # device = 'cpu' or '0' or '0,1,2,3'
  52. s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
  53. cpu = device.lower() == 'cpu'
  54. if cpu:
  55. os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
  56. elif device: # non-cpu device requested
  57. os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
  58. assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
  59. cuda = not cpu and torch.cuda.is_available()
  60. if cuda:
  61. devices = device.split(',') if device else range(torch.cuda.device_count()) # i.e. 0,1,6,7
  62. n = len(devices) # device count
  63. if n > 1 and batch_size: # check batch_size is divisible by device_count
  64. assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
  65. space = ' ' * len(s)
  66. for i, d in enumerate(devices):
  67. p = torch.cuda.get_device_properties(i)
  68. s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
  69. else:
  70. s += 'CPU\n'
  71. logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
  72. return torch.device('cuda:0' if cuda else 'cpu')
  73. def time_synchronized():
  74. # pytorch-accurate time
  75. if torch.cuda.is_available():
  76. torch.cuda.synchronize()
  77. return time.time()
  78. def profile(x, ops, n=100, device=None):
  79. # profile a pytorch module or list of modules. Example usage:
  80. # x = torch.randn(16, 3, 640, 640) # input
  81. # m1 = lambda x: x * torch.sigmoid(x)
  82. # m2 = nn.SiLU()
  83. # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
  84. device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
  85. x = x.to(device)
  86. x.requires_grad = True
  87. print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
  88. print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
  89. for m in ops if isinstance(ops, list) else [ops]:
  90. m = m.to(device) if hasattr(m, 'to') else m # device
  91. m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
  92. dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
  93. try:
  94. flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
  95. except:
  96. flops = 0
  97. for _ in range(n):
  98. t[0] = time_synchronized()
  99. y = m(x)
  100. t[1] = time_synchronized()
  101. try:
  102. _ = y.sum().backward()
  103. t[2] = time_synchronized()
  104. except: # no backward method
  105. t[2] = float('nan')
  106. dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
  107. dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
  108. s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
  109. s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
  110. p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
  111. print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
  112. def is_parallel(model):
  113. return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
  114. def intersect_dicts(da, db, exclude=()):
  115. # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
  116. 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}
  117. def initialize_weights(model):
  118. for m in model.modules():
  119. t = type(m)
  120. if t is nn.Conv2d:
  121. pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  122. elif t is nn.BatchNorm2d:
  123. m.eps = 1e-3
  124. m.momentum = 0.03
  125. elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
  126. m.inplace = True
  127. def find_modules(model, mclass=nn.Conv2d):
  128. # Finds layer indices matching module class 'mclass'
  129. return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
  130. def sparsity(model):
  131. # Return global model sparsity
  132. a, b = 0., 0.
  133. for p in model.parameters():
  134. a += p.numel()
  135. b += (p == 0).sum()
  136. return b / a
  137. def prune(model, amount=0.3):
  138. # Prune model to requested global sparsity
  139. import torch.nn.utils.prune as prune
  140. print('Pruning model... ', end='')
  141. for name, m in model.named_modules():
  142. if isinstance(m, nn.Conv2d):
  143. prune.l1_unstructured(m, name='weight', amount=amount) # prune
  144. prune.remove(m, 'weight') # make permanent
  145. print(' %.3g global sparsity' % sparsity(model))
  146. def fuse_conv_and_bn(conv, bn):
  147. # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
  148. fusedconv = nn.Conv2d(conv.in_channels,
  149. conv.out_channels,
  150. kernel_size=conv.kernel_size,
  151. stride=conv.stride,
  152. padding=conv.padding,
  153. groups=conv.groups,
  154. bias=True).requires_grad_(False).to(conv.weight.device)
  155. # prepare filters
  156. w_conv = conv.weight.clone().view(conv.out_channels, -1)
  157. w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
  158. fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
  159. # prepare spatial bias
  160. b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
  161. b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
  162. fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
  163. return fusedconv
  164. def model_info(model, verbose=False, img_size=640):
  165. # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
  166. n_p = sum(x.numel() for x in model.parameters()) # number parameters
  167. n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
  168. if verbose:
  169. print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
  170. for i, (name, p) in enumerate(model.named_parameters()):
  171. name = name.replace('module_list.', '')
  172. print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
  173. (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
  174. try: # FLOPS
  175. from thop import profile
  176. stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
  177. img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
  178. flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
  179. img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
  180. fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
  181. except (ImportError, Exception):
  182. fs = ''
  183. logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
  184. def load_classifier(name='resnet101', n=2):
  185. # Loads a pretrained model reshaped to n-class output
  186. model = torchvision.models.__dict__[name](pretrained=True)
  187. # ResNet model properties
  188. # input_size = [3, 224, 224]
  189. # input_space = 'RGB'
  190. # input_range = [0, 1]
  191. # mean = [0.485, 0.456, 0.406]
  192. # std = [0.229, 0.224, 0.225]
  193. # Reshape output to n classes
  194. filters = model.fc.weight.shape[1]
  195. model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
  196. model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
  197. model.fc.out_features = n
  198. return model
  199. def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
  200. # scales img(bs,3,y,x) by ratio constrained to gs-multiple
  201. if ratio == 1.0:
  202. return img
  203. else:
  204. h, w = img.shape[2:]
  205. s = (int(h * ratio), int(w * ratio)) # new size
  206. img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
  207. if not same_shape: # pad/crop img
  208. h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
  209. return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
  210. def copy_attr(a, b, include=(), exclude=()):
  211. # Copy attributes from b to a, options to only include [...] and to exclude [...]
  212. for k, v in b.__dict__.items():
  213. if (len(include) and k not in include) or k.startswith('_') or k in exclude:
  214. continue
  215. else:
  216. setattr(a, k, v)
  217. class ModelEMA:
  218. """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
  219. Keep a moving average of everything in the model state_dict (parameters and buffers).
  220. This is intended to allow functionality like
  221. https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
  222. A smoothed version of the weights is necessary for some training schemes to perform well.
  223. This class is sensitive where it is initialized in the sequence of model init,
  224. GPU assignment and distributed training wrappers.
  225. """
  226. def __init__(self, model, decay=0.9999, updates=0):
  227. # Create EMA
  228. self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
  229. # if next(model.parameters()).device.type != 'cpu':
  230. # self.ema.half() # FP16 EMA
  231. self.updates = updates # number of EMA updates
  232. self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
  233. for p in self.ema.parameters():
  234. p.requires_grad_(False)
  235. def update(self, model):
  236. # Update EMA parameters
  237. with torch.no_grad():
  238. self.updates += 1
  239. d = self.decay(self.updates)
  240. msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
  241. for k, v in self.ema.state_dict().items():
  242. if v.dtype.is_floating_point:
  243. v *= d
  244. v += (1. - d) * msd[k].detach()
  245. def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
  246. # Update EMA attributes
  247. copy_attr(self.ema, model, include, exclude)