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.

332 lines
15KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. YOLO-specific modules
  4. Usage:
  5. $ python path/to/models/yolo.py --cfg yolov5s.yaml
  6. """
  7. import argparse
  8. import os
  9. import platform
  10. import sys
  11. from copy import deepcopy
  12. from pathlib import Path
  13. FILE = Path(__file__).resolve()
  14. ROOT = FILE.parents[1] # YOLOv5 root directory
  15. if str(ROOT) not in sys.path:
  16. sys.path.append(str(ROOT)) # add ROOT to PATH
  17. if platform.system() != 'Windows':
  18. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  19. from models.common import *
  20. from models.experimental import *
  21. from utils.autoanchor import check_anchor_order
  22. from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
  23. from utils.plots import feature_visualization
  24. from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
  25. time_sync)
  26. try:
  27. import thop # for FLOPs computation
  28. except ImportError:
  29. thop = None
  30. class Detect(nn.Module):
  31. stride = None # strides computed during build
  32. onnx_dynamic = False # ONNX export parameter
  33. def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
  34. super().__init__()
  35. self.nc = nc # number of classes
  36. self.no = nc + 5 # number of outputs per anchor
  37. self.nl = len(anchors) # number of detection layers
  38. self.na = len(anchors[0]) // 2 # number of anchors
  39. self.grid = [torch.zeros(1)] * self.nl # init grid
  40. self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
  41. self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
  42. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  43. self.inplace = inplace # use in-place ops (e.g. slice assignment)
  44. def forward(self, x):
  45. z = [] # inference output
  46. for i in range(self.nl):
  47. x[i] = self.m[i](x[i]) # conv
  48. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  49. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  50. if not self.training: # inference
  51. if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
  52. self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
  53. y = x[i].sigmoid()
  54. if self.inplace:
  55. y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
  56. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  57. else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
  58. xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
  59. xy = (xy * 2 + (self.grid[i] - 0.5)) * self.stride[i] # xy
  60. wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
  61. y = torch.cat((xy, wh, conf), 4)
  62. z.append(y.view(bs, -1, self.no))
  63. return x if self.training else (torch.cat(z, 1), x)
  64. def _make_grid(self, nx=20, ny=20, i=0):
  65. d = self.anchors[i].device
  66. shape = 1, self.na, ny, nx, 2 # grid shape
  67. if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
  68. yv, xv = torch.meshgrid(torch.arange(ny, device=d), torch.arange(nx, device=d), indexing='ij')
  69. else:
  70. yv, xv = torch.meshgrid(torch.arange(ny, device=d), torch.arange(nx, device=d))
  71. grid = torch.stack((xv, yv), 2).expand(shape).float()
  72. anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape).float()
  73. return grid, anchor_grid
  74. class Model(nn.Module):
  75. def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
  76. super().__init__()
  77. if isinstance(cfg, dict):
  78. self.yaml = cfg # model dict
  79. else: # is *.yaml
  80. import yaml # for torch hub
  81. self.yaml_file = Path(cfg).name
  82. with open(cfg, encoding='ascii', errors='ignore') as f:
  83. self.yaml = yaml.safe_load(f) # model dict
  84. # Define model
  85. ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
  86. if nc and nc != self.yaml['nc']:
  87. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  88. self.yaml['nc'] = nc # override yaml value
  89. if anchors:
  90. LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
  91. self.yaml['anchors'] = round(anchors) # override yaml value
  92. self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
  93. self.names = [str(i) for i in range(self.yaml['nc'])] # default names
  94. self.inplace = self.yaml.get('inplace', True)
  95. # Build strides, anchors
  96. m = self.model[-1] # Detect()
  97. if isinstance(m, Detect):
  98. s = 256 # 2x min stride
  99. m.inplace = self.inplace
  100. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  101. check_anchor_order(m) # must be in pixel-space (not grid-space)
  102. m.anchors /= m.stride.view(-1, 1, 1)
  103. self.stride = m.stride
  104. self._initialize_biases() # only run once
  105. # Init weights, biases
  106. initialize_weights(self)
  107. self.info()
  108. LOGGER.info('')
  109. def forward(self, x, augment=False, profile=False, visualize=False):
  110. if augment:
  111. return self._forward_augment(x) # augmented inference, None
  112. return self._forward_once(x, profile, visualize) # single-scale inference, train
  113. def _forward_augment(self, x):
  114. img_size = x.shape[-2:] # height, width
  115. s = [1, 0.83, 0.67] # scales
  116. f = [None, 3, None] # flips (2-ud, 3-lr)
  117. y = [] # outputs
  118. for si, fi in zip(s, f):
  119. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  120. yi = self._forward_once(xi)[0] # forward
  121. # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
  122. yi = self._descale_pred(yi, fi, si, img_size)
  123. y.append(yi)
  124. y = self._clip_augmented(y) # clip augmented tails
  125. return torch.cat(y, 1), None # augmented inference, train
  126. def _forward_once(self, x, profile=False, visualize=False):
  127. y, dt = [], [] # outputs
  128. for m in self.model:
  129. if m.f != -1: # if not from previous layer
  130. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  131. if profile:
  132. self._profile_one_layer(m, x, dt)
  133. x = m(x) # run
  134. y.append(x if m.i in self.save else None) # save output
  135. if visualize:
  136. feature_visualization(x, m.type, m.i, save_dir=visualize)
  137. return x
  138. def _descale_pred(self, p, flips, scale, img_size):
  139. # de-scale predictions following augmented inference (inverse operation)
  140. if self.inplace:
  141. p[..., :4] /= scale # de-scale
  142. if flips == 2:
  143. p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
  144. elif flips == 3:
  145. p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
  146. else:
  147. x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
  148. if flips == 2:
  149. y = img_size[0] - y # de-flip ud
  150. elif flips == 3:
  151. x = img_size[1] - x # de-flip lr
  152. p = torch.cat((x, y, wh, p[..., 4:]), -1)
  153. return p
  154. def _clip_augmented(self, y):
  155. # Clip YOLOv5 augmented inference tails
  156. nl = self.model[-1].nl # number of detection layers (P3-P5)
  157. g = sum(4 ** x for x in range(nl)) # grid points
  158. e = 1 # exclude layer count
  159. i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
  160. y[0] = y[0][:, :-i] # large
  161. i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
  162. y[-1] = y[-1][:, i:] # small
  163. return y
  164. def _profile_one_layer(self, m, x, dt):
  165. c = isinstance(m, Detect) # is final layer, copy input as inplace fix
  166. o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
  167. t = time_sync()
  168. for _ in range(10):
  169. m(x.copy() if c else x)
  170. dt.append((time_sync() - t) * 100)
  171. if m == self.model[0]:
  172. LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
  173. LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
  174. if c:
  175. LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
  176. def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
  177. # https://arxiv.org/abs/1708.02002 section 3.3
  178. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  179. m = self.model[-1] # Detect() module
  180. for mi, s in zip(m.m, m.stride): # from
  181. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  182. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  183. b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
  184. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  185. def _print_biases(self):
  186. m = self.model[-1] # Detect() module
  187. for mi in m.m: # from
  188. b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
  189. LOGGER.info(
  190. ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
  191. # def _print_weights(self):
  192. # for m in self.model.modules():
  193. # if type(m) is Bottleneck:
  194. # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
  195. def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
  196. LOGGER.info('Fusing layers... ')
  197. for m in self.model.modules():
  198. if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
  199. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  200. delattr(m, 'bn') # remove batchnorm
  201. m.forward = m.forward_fuse # update forward
  202. self.info()
  203. return self
  204. def info(self, verbose=False, img_size=640): # print model information
  205. model_info(self, verbose, img_size)
  206. def _apply(self, fn):
  207. # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
  208. self = super()._apply(fn)
  209. m = self.model[-1] # Detect()
  210. if isinstance(m, Detect):
  211. m.stride = fn(m.stride)
  212. m.grid = list(map(fn, m.grid))
  213. if isinstance(m.anchor_grid, list):
  214. m.anchor_grid = list(map(fn, m.anchor_grid))
  215. return self
  216. def parse_model(d, ch): # model_dict, input_channels(3)
  217. LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
  218. anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
  219. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  220. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  221. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  222. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
  223. m = eval(m) if isinstance(m, str) else m # eval strings
  224. for j, a in enumerate(args):
  225. try:
  226. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  227. except NameError:
  228. pass
  229. n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
  230. if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
  231. BottleneckCSP, C3, C3TR, C3SPP, C3Ghost):
  232. c1, c2 = ch[f], args[0]
  233. if c2 != no: # if not output
  234. c2 = make_divisible(c2 * gw, 8)
  235. args = [c1, c2, *args[1:]]
  236. if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
  237. args.insert(2, n) # number of repeats
  238. n = 1
  239. elif m is nn.BatchNorm2d:
  240. args = [ch[f]]
  241. elif m is Concat:
  242. c2 = sum(ch[x] for x in f)
  243. elif m is Detect:
  244. args.append([ch[x] for x in f])
  245. if isinstance(args[1], int): # number of anchors
  246. args[1] = [list(range(args[1] * 2))] * len(f)
  247. elif m is Contract:
  248. c2 = ch[f] * args[0] ** 2
  249. elif m is Expand:
  250. c2 = ch[f] // args[0] ** 2
  251. else:
  252. c2 = ch[f]
  253. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  254. t = str(m)[8:-2].replace('__main__.', '') # module type
  255. np = sum(x.numel() for x in m_.parameters()) # number params
  256. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  257. LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
  258. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  259. layers.append(m_)
  260. if i == 0:
  261. ch = []
  262. ch.append(c2)
  263. return nn.Sequential(*layers), sorted(save)
  264. if __name__ == '__main__':
  265. parser = argparse.ArgumentParser()
  266. parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
  267. parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
  268. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  269. parser.add_argument('--profile', action='store_true', help='profile model speed')
  270. parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
  271. parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
  272. opt = parser.parse_args()
  273. opt.cfg = check_yaml(opt.cfg) # check YAML
  274. print_args(vars(opt))
  275. device = select_device(opt.device)
  276. # Create model
  277. im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
  278. model = Model(opt.cfg).to(device)
  279. # Options
  280. if opt.line_profile: # profile layer by layer
  281. _ = model(im, profile=True)
  282. elif opt.profile: # profile forward-backward
  283. results = profile(input=im, ops=[model], n=3)
  284. elif opt.test: # test all models
  285. for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
  286. try:
  287. _ = Model(cfg)
  288. except Exception as e:
  289. print(f'Error in {cfg}: {e}')