3
0

yolo.py 15 KB

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