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.

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