Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

305 lignes
13KB

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