yolo.py 14 KB

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