yolo.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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.pruned_common import *
  18. from models.experimental import *
  19. from utils.autoanchor import check_anchor_order
  20. from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
  21. from utils.plots import feature_visualization
  22. from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, 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, device=d), torch.arange(nx, device=d)], indexing='ij')
  64. else:
  65. yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=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 info(self, verbose=False, img_size=640): # print model information
  201. model_info(self, verbose, img_size)
  202. def _apply(self, fn):
  203. # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
  204. self = super()._apply(fn)
  205. m = self.model[-1] # Detect()
  206. if isinstance(m, Detect):
  207. m.stride = fn(m.stride)
  208. m.grid = list(map(fn, m.grid))
  209. if isinstance(m.anchor_grid, list):
  210. m.anchor_grid = list(map(fn, m.anchor_grid))
  211. return self
  212. class ModelPruned(nn.Module):
  213. def __init__(self, maskbndict, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
  214. super().__init__()
  215. self.maskbndict = maskbndict
  216. if isinstance(cfg, dict):
  217. self.yaml = cfg # model dict
  218. else: # is *.yaml
  219. import yaml # for torch hub
  220. self.yaml_file = Path(cfg).name
  221. with open(cfg, encoding='ascii', errors='ignore') as f:
  222. self.yaml = yaml.safe_load(f) # model dict
  223. # Define model
  224. ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
  225. if nc and nc != self.yaml['nc']:
  226. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  227. self.yaml['nc'] = nc # override yaml value
  228. if anchors:
  229. LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
  230. self.yaml['anchors'] = round(anchors) # override yaml value
  231. self.model, self.save, self.from_to_map = parse_pruned_model(self.maskbndict, deepcopy(self.yaml), ch=[ch]) # model, savelist
  232. self.names = [str(i) for i in range(self.yaml['nc'])] # default names
  233. self.inplace = self.yaml.get('inplace', True)
  234. # Build strides, anchors
  235. m = self.model[-1] # Detect()
  236. if isinstance(m, Detect):
  237. s = 256 # 2x min stride
  238. m.inplace = self.inplace
  239. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  240. m.anchors /= m.stride.view(-1, 1, 1)
  241. check_anchor_order(m)
  242. self.stride = m.stride
  243. self._initialize_biases() # only run once
  244. # Init weights, biases
  245. initialize_weights(self)
  246. def forward(self, x, augment=False, profile=False, visualize=False):
  247. if augment:
  248. return self._forward_augment(x) # augmented inference, None
  249. return self._forward_once(x, profile, visualize) # single-scale inference, train
  250. def _forward_augment(self, x):
  251. img_size = x.shape[-2:] # height, width
  252. s = [1, 0.83, 0.67] # scales
  253. f = [None, 3, None] # flips (2-ud, 3-lr)
  254. y = [] # outputs
  255. for si, fi in zip(s, f):
  256. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  257. yi = self._forward_once(xi)[0] # forward
  258. # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
  259. yi = self._descale_pred(yi, fi, si, img_size)
  260. y.append(yi)
  261. y = self._clip_augmented(y) # clip augmented tails
  262. return torch.cat(y, 1), None # augmented inference, train
  263. def _forward_once(self, x, profile=False, visualize=False):
  264. y, dt = [], [] # outputs
  265. for m in self.model:
  266. if m.f != -1: # if not from previous layer
  267. 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
  268. if profile:
  269. self._profile_one_layer(m, x, dt)
  270. x = m(x) # run
  271. y.append(x if m.i in self.save else None) # save output
  272. if visualize:
  273. feature_visualization(x, m.type, m.i, save_dir=visualize)
  274. return x
  275. def _descale_pred(self, p, flips, scale, img_size):
  276. # de-scale predictions following augmented inference (inverse operation)
  277. if self.inplace:
  278. p[..., :4] /= scale # de-scale
  279. if flips == 2:
  280. p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
  281. elif flips == 3:
  282. p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
  283. else:
  284. x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
  285. if flips == 2:
  286. y = img_size[0] - y # de-flip ud
  287. elif flips == 3:
  288. x = img_size[1] - x # de-flip lr
  289. p = torch.cat((x, y, wh, p[..., 4:]), -1)
  290. return p
  291. def _clip_augmented(self, y):
  292. # Clip YOLOv5 augmented inference tails
  293. nl = self.model[-1].nl # number of detection layers (P3-P5)
  294. g = sum(4 ** x for x in range(nl)) # grid points
  295. e = 1 # exclude layer count
  296. i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
  297. y[0] = y[0][:, :-i] # large
  298. i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
  299. y[-1] = y[-1][:, i:] # small
  300. return y
  301. def _profile_one_layer(self, m, x, dt):
  302. c = isinstance(m, Detect) # is final layer, copy input as inplace fix
  303. o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
  304. t = time_sync()
  305. for _ in range(10):
  306. m(x.copy() if c else x)
  307. dt.append((time_sync() - t) * 100)
  308. if m == self.model[0]:
  309. LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
  310. LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
  311. if c:
  312. LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
  313. def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
  314. # https://arxiv.org/abs/1708.02002 section 3.3
  315. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  316. m = self.model[-1] # Detect() module
  317. for mi, s in zip(m.m, m.stride): # from
  318. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  319. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  320. b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
  321. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  322. def _print_biases(self):
  323. m = self.model[-1] # Detect() module
  324. for mi in m.m: # from
  325. b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
  326. LOGGER.info(
  327. ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
  328. # def _print_weights(self):
  329. # for m in self.model.modules():
  330. # if type(m) is Bottleneck:
  331. # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
  332. def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
  333. LOGGER.info('Fusing layers... ')
  334. for m in self.model.modules():
  335. if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
  336. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  337. delattr(m, 'bn') # remove batchnorm
  338. m.forward = m.forward_fuse # update forward
  339. self.info()
  340. return self
  341. def info(self, verbose=False, img_size=640): # print model information
  342. model_info(self, verbose, img_size)
  343. def _apply(self, fn):
  344. # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
  345. self = super()._apply(fn)
  346. m = self.model[-1] # Detect()
  347. if isinstance(m, Detect):
  348. m.stride = fn(m.stride)
  349. m.grid = list(map(fn, m.grid))
  350. if isinstance(m.anchor_grid, list):
  351. m.anchor_grid = list(map(fn, m.anchor_grid))
  352. return self
  353. def parse_model(d, ch): # model_dict, input_channels(3)
  354. LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
  355. anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
  356. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  357. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  358. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  359. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
  360. m = eval(m) if isinstance(m, str) else m # eval strings
  361. for j, a in enumerate(args):
  362. try:
  363. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  364. except NameError:
  365. pass
  366. n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
  367. if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
  368. BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
  369. c1, c2 = ch[f], args[0]
  370. if c2 != no: # if not output
  371. c2 = make_divisible(c2 * gw, 8)
  372. args = [c1, c2, *args[1:]]
  373. if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
  374. args.insert(2, n) # number of repeats
  375. n = 1
  376. elif m is nn.BatchNorm2d:
  377. args = [ch[f]]
  378. elif m is Concat:
  379. c2 = sum(ch[x] for x in f)
  380. elif m is Detect:
  381. args.append([ch[x] for x in f])
  382. if isinstance(args[1], int): # number of anchors
  383. args[1] = [list(range(args[1] * 2))] * len(f)
  384. elif m is Contract:
  385. c2 = ch[f] * args[0] ** 2
  386. elif m is Expand:
  387. c2 = ch[f] // args[0] ** 2
  388. else:
  389. c2 = ch[f]
  390. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  391. t = str(m)[8:-2].replace('__main__.', '') # module type
  392. np = sum(x.numel() for x in m_.parameters()) # number params
  393. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  394. LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
  395. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  396. layers.append(m_)
  397. if i == 0:
  398. ch = []
  399. ch.append(c2)
  400. return nn.Sequential(*layers), sorted(save)
  401. def parse_pruned_model(maskbndict, d, ch): # model_dict, input_channels(3)
  402. LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
  403. anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
  404. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  405. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  406. ch = [3]
  407. fromlayer = [] # last module bn layer name
  408. from_to_map = {}
  409. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  410. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
  411. m = eval(m) if isinstance(m, str) else m # eval strings
  412. for j, a in enumerate(args):
  413. try:
  414. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  415. except NameError:
  416. pass
  417. n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
  418. named_m_base = "model.{}".format(i)
  419. if m in [Conv]:
  420. named_m_bn = named_m_base + ".bn"
  421. bnc = int(maskbndict[named_m_bn].sum())
  422. c1, c2 = ch[f], bnc
  423. args = [c1, c2, *args[1:]]
  424. layertmp = named_m_bn
  425. if i>0:
  426. from_to_map[layertmp] = fromlayer[f]
  427. fromlayer.append(named_m_bn)
  428. elif m in [C3Pruned]:
  429. named_m_cv1_bn = named_m_base + ".cv1.bn"
  430. named_m_cv2_bn = named_m_base + ".cv2.bn"
  431. named_m_cv3_bn = named_m_base + ".cv3.bn"
  432. from_to_map[named_m_cv1_bn] = fromlayer[f]
  433. from_to_map[named_m_cv2_bn] = fromlayer[f]
  434. fromlayer.append(named_m_cv3_bn)
  435. cv1in = ch[f]
  436. cv1out = int(maskbndict[named_m_cv1_bn].sum())
  437. cv2out = int(maskbndict[named_m_cv2_bn].sum())
  438. cv3out = int(maskbndict[named_m_cv3_bn].sum())
  439. args = [cv1in, cv1out, cv2out, cv3out, n, args[-1]]
  440. bottle_args = []
  441. chin = [cv1out]
  442. c3fromlayer = [named_m_cv1_bn]
  443. for p in range(n):
  444. named_m_bottle_cv1_bn = named_m_base + ".m.{}.cv1.bn".format(p)
  445. named_m_bottle_cv2_bn = named_m_base + ".m.{}.cv2.bn".format(p)
  446. bottle_cv1in = chin[-1]
  447. bottle_cv1out = int(maskbndict[named_m_bottle_cv1_bn].sum())
  448. bottle_cv2out = int(maskbndict[named_m_bottle_cv2_bn].sum())
  449. chin.append(bottle_cv2out)
  450. bottle_args.append([bottle_cv1in, bottle_cv1out, bottle_cv2out])
  451. from_to_map[named_m_bottle_cv1_bn] = c3fromlayer[p]
  452. from_to_map[named_m_bottle_cv2_bn] = named_m_bottle_cv1_bn
  453. c3fromlayer.append(named_m_bottle_cv2_bn)
  454. args.insert(4, bottle_args)
  455. c2 = cv3out
  456. n = 1
  457. from_to_map[named_m_cv3_bn] = [c3fromlayer[-1], named_m_cv2_bn]
  458. elif m in [SPPFPruned]:
  459. named_m_cv1_bn = named_m_base + ".cv1.bn"
  460. named_m_cv2_bn = named_m_base + ".cv2.bn"
  461. cv1in = ch[f]
  462. from_to_map[named_m_cv1_bn] = fromlayer[f]
  463. from_to_map[named_m_cv2_bn] = [named_m_cv1_bn]*4
  464. fromlayer.append(named_m_cv2_bn)
  465. cv1out = int(maskbndict[named_m_cv1_bn].sum())
  466. cv2out = int(maskbndict[named_m_cv2_bn].sum())
  467. args = [cv1in, cv1out, cv2out, *args[1:]]
  468. c2 = cv2out
  469. elif m is nn.BatchNorm2d:
  470. args = [ch[f]]
  471. elif m is Concat:
  472. c2 = sum(ch[x] for x in f)
  473. inputtmp = [fromlayer[x] for x in f]
  474. fromlayer.append(inputtmp)
  475. elif m is Detect:
  476. from_to_map[named_m_base + ".m.0"] = fromlayer[f[0]]
  477. from_to_map[named_m_base + ".m.1"] = fromlayer[f[1]]
  478. from_to_map[named_m_base + ".m.2"] = fromlayer[f[2]]
  479. args.append([ch[x] for x in f])
  480. if isinstance(args[1], int): # number of anchors
  481. args[1] = [list(range(args[1] * 2))] * len(f)
  482. elif m is Contract:
  483. c2 = ch[f] * args[0] ** 2
  484. elif m is Expand:
  485. c2 = ch[f] // args[0] ** 2
  486. else:
  487. c2 = ch[f]
  488. fromtmp = fromlayer[-1]
  489. fromlayer.append(fromtmp)
  490. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  491. t = str(m)[8:-2].replace('__main__.', '') # module type
  492. np = sum(x.numel() for x in m_.parameters()) # number params
  493. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  494. LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
  495. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  496. layers.append(m_)
  497. if i == 0:
  498. ch = []
  499. ch.append(c2)
  500. return nn.Sequential(*layers), sorted(save), from_to_map
  501. if __name__ == '__main__':
  502. parser = argparse.ArgumentParser()
  503. parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
  504. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  505. parser.add_argument('--profile', action='store_true', help='profile model speed')
  506. parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
  507. opt = parser.parse_args()
  508. opt.cfg = check_yaml(opt.cfg) # check YAML
  509. print_args(FILE.stem, opt)
  510. device = select_device(opt.device)
  511. # Create model
  512. model = Model(opt.cfg).to(device)
  513. model.train()
  514. # Profile
  515. if opt.profile:
  516. img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
  517. y = model(img, profile=True)
  518. # Test all models
  519. if opt.test:
  520. for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
  521. try:
  522. _ = Model(cfg)
  523. except Exception as e:
  524. print(f'Error in {cfg}: {e}')
  525. # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
  526. # from torch.utils.tensorboard import SummaryWriter
  527. # tb_writer = SummaryWriter('.')
  528. # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
  529. # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph