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.

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