基于Yolov7的路面病害检测代码
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

844 行
39KB

  1. import argparse
  2. import logging
  3. import sys
  4. from copy import deepcopy
  5. sys.path.append('./') # to run '$ python *.py' files in subdirectories
  6. logger = logging.getLogger(__name__)
  7. import torch
  8. from models.common import *
  9. from models.experimental import *
  10. from utils.autoanchor import check_anchor_order
  11. from utils.general import make_divisible, check_file, set_logging
  12. from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
  13. select_device, copy_attr
  14. from utils.loss import SigmoidBin
  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. export = False # onnx export
  22. end2end = False
  23. include_nms = False
  24. concat = False
  25. def __init__(self, nc=80, anchors=(), ch=()): # detection layer
  26. super(Detect, self).__init__()
  27. self.nc = nc # number of classes
  28. self.no = nc + 5 # number of outputs per anchor
  29. self.nl = len(anchors) # number of detection layers
  30. self.na = len(anchors[0]) // 2 # number of anchors
  31. self.grid = [torch.zeros(1)] * self.nl # init grid
  32. a = torch.tensor(anchors).float().view(self.nl, -1, 2)
  33. self.register_buffer('anchors', a) # shape(nl,na,2)
  34. self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
  35. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  36. def forward(self, x):
  37. # x = x.copy() # for profiling
  38. z = [] # inference output
  39. self.training |= self.export
  40. for i in range(self.nl):
  41. x[i] = self.m[i](x[i]) # conv
  42. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  43. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  44. if not self.training: # inference
  45. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  46. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  47. y = x[i].sigmoid()
  48. if not torch.onnx.is_in_onnx_export():
  49. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  50. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  51. else:
  52. xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
  53. xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
  54. wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
  55. y = torch.cat((xy, wh, conf), 4)
  56. z.append(y.view(bs, -1, self.no))
  57. if self.training:
  58. out = x
  59. elif self.end2end:
  60. out = torch.cat(z, 1)
  61. elif self.include_nms:
  62. z = self.convert(z)
  63. out = (z, )
  64. elif self.concat:
  65. out = torch.cat(z, 1)
  66. else:
  67. out = (torch.cat(z, 1), x)
  68. return out
  69. @staticmethod
  70. def _make_grid(nx=20, ny=20):
  71. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  72. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  73. def convert(self, z):
  74. z = torch.cat(z, 1)
  75. box = z[:, :, :4]
  76. conf = z[:, :, 4:5]
  77. score = z[:, :, 5:]
  78. score *= conf
  79. convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
  80. dtype=torch.float32,
  81. device=z.device)
  82. box @= convert_matrix
  83. return (box, score)
  84. class IDetect(nn.Module):
  85. stride = None # strides computed during build
  86. export = False # onnx export
  87. end2end = False
  88. include_nms = False
  89. concat = False
  90. def __init__(self, nc=80, anchors=(), ch=()): # detection layer
  91. super(IDetect, self).__init__()
  92. self.nc = nc # number of classes
  93. self.no = nc + 5 # number of outputs per anchor
  94. self.nl = len(anchors) # number of detection layers
  95. self.na = len(anchors[0]) // 2 # number of anchors
  96. self.grid = [torch.zeros(1)] * self.nl # init grid
  97. a = torch.tensor(anchors).float().view(self.nl, -1, 2)
  98. self.register_buffer('anchors', a) # shape(nl,na,2)
  99. self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
  100. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  101. self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
  102. self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
  103. def forward(self, x):
  104. # x = x.copy() # for profiling
  105. z = [] # inference output
  106. self.training |= self.export
  107. for i in range(self.nl):
  108. x[i] = self.m[i](self.ia[i](x[i])) # conv
  109. x[i] = self.im[i](x[i])
  110. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  111. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  112. if not self.training: # inference
  113. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  114. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  115. y = x[i].sigmoid()
  116. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  117. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  118. z.append(y.view(bs, -1, self.no))
  119. return x if self.training else (torch.cat(z, 1), x)
  120. def fuseforward(self, x):
  121. # x = x.copy() # for profiling
  122. z = [] # inference output
  123. self.training |= self.export
  124. for i in range(self.nl):
  125. x[i] = self.m[i](x[i]) # conv
  126. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  127. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  128. if not self.training: # inference
  129. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  130. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  131. y = x[i].sigmoid()
  132. if not torch.onnx.is_in_onnx_export():
  133. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  134. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  135. else:
  136. xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
  137. xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
  138. wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
  139. y = torch.cat((xy, wh, conf), 4)
  140. z.append(y.view(bs, -1, self.no))
  141. if self.training:
  142. out = x
  143. elif self.end2end:
  144. out = torch.cat(z, 1)
  145. elif self.include_nms:
  146. z = self.convert(z)
  147. out = (z, )
  148. elif self.concat:
  149. out = torch.cat(z, 1)
  150. else:
  151. out = (torch.cat(z, 1), x)
  152. return out
  153. def fuse(self):
  154. print("IDetect.fuse")
  155. # fuse ImplicitA and Convolution
  156. for i in range(len(self.m)):
  157. c1,c2,_,_ = self.m[i].weight.shape
  158. c1_,c2_, _,_ = self.ia[i].implicit.shape
  159. self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1)
  160. # fuse ImplicitM and Convolution
  161. for i in range(len(self.m)):
  162. c1,c2, _,_ = self.im[i].implicit.shape
  163. self.m[i].bias *= self.im[i].implicit.reshape(c2)
  164. self.m[i].weight *= self.im[i].implicit.transpose(0,1)
  165. @staticmethod
  166. def _make_grid(nx=20, ny=20):
  167. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  168. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  169. def convert(self, z):
  170. z = torch.cat(z, 1)
  171. box = z[:, :, :4]
  172. conf = z[:, :, 4:5]
  173. score = z[:, :, 5:]
  174. score *= conf
  175. convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
  176. dtype=torch.float32,
  177. device=z.device)
  178. box @= convert_matrix
  179. return (box, score)
  180. class IKeypoint(nn.Module):
  181. stride = None # strides computed during build
  182. export = False # onnx export
  183. def __init__(self, nc=80, anchors=(), nkpt=17, ch=(), inplace=True, dw_conv_kpt=False): # detection layer
  184. super(IKeypoint, self).__init__()
  185. self.nc = nc # number of classes
  186. self.nkpt = nkpt
  187. self.dw_conv_kpt = dw_conv_kpt
  188. self.no_det=(nc + 5) # number of outputs per anchor for box and class
  189. self.no_kpt = 3*self.nkpt ## number of outputs per anchor for keypoints
  190. self.no = self.no_det+self.no_kpt
  191. self.nl = len(anchors) # number of detection layers
  192. self.na = len(anchors[0]) // 2 # number of anchors
  193. self.grid = [torch.zeros(1)] * self.nl # init grid
  194. self.flip_test = False
  195. a = torch.tensor(anchors).float().view(self.nl, -1, 2)
  196. self.register_buffer('anchors', a) # shape(nl,na,2)
  197. self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
  198. self.m = nn.ModuleList(nn.Conv2d(x, self.no_det * self.na, 1) for x in ch) # output conv
  199. self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
  200. self.im = nn.ModuleList(ImplicitM(self.no_det * self.na) for _ in ch)
  201. if self.nkpt is not None:
  202. if self.dw_conv_kpt: #keypoint head is slightly more complex
  203. self.m_kpt = nn.ModuleList(
  204. nn.Sequential(DWConv(x, x, k=3), Conv(x,x),
  205. DWConv(x, x, k=3), Conv(x, x),
  206. DWConv(x, x, k=3), Conv(x,x),
  207. DWConv(x, x, k=3), Conv(x, x),
  208. DWConv(x, x, k=3), Conv(x, x),
  209. DWConv(x, x, k=3), nn.Conv2d(x, self.no_kpt * self.na, 1)) for x in ch)
  210. else: #keypoint head is a single convolution
  211. self.m_kpt = nn.ModuleList(nn.Conv2d(x, self.no_kpt * self.na, 1) for x in ch)
  212. self.inplace = inplace # use in-place ops (e.g. slice assignment)
  213. def forward(self, x):
  214. # x = x.copy() # for profiling
  215. z = [] # inference output
  216. self.training |= self.export
  217. for i in range(self.nl):
  218. if self.nkpt is None or self.nkpt==0:
  219. x[i] = self.im[i](self.m[i](self.ia[i](x[i]))) # conv
  220. else :
  221. x[i] = torch.cat((self.im[i](self.m[i](self.ia[i](x[i]))), self.m_kpt[i](x[i])), axis=1)
  222. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  223. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  224. x_det = x[i][..., :6]
  225. x_kpt = x[i][..., 6:]
  226. if not self.training: # inference
  227. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  228. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  229. kpt_grid_x = self.grid[i][..., 0:1]
  230. kpt_grid_y = self.grid[i][..., 1:2]
  231. if self.nkpt == 0:
  232. y = x[i].sigmoid()
  233. else:
  234. y = x_det.sigmoid()
  235. if self.inplace:
  236. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  237. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
  238. if self.nkpt != 0:
  239. x_kpt[..., 0::3] = (x_kpt[..., ::3] * 2. - 0.5 + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
  240. x_kpt[..., 1::3] = (x_kpt[..., 1::3] * 2. - 0.5 + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
  241. #x_kpt[..., 0::3] = (x_kpt[..., ::3] + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
  242. #x_kpt[..., 1::3] = (x_kpt[..., 1::3] + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
  243. #print('=============')
  244. #print(self.anchor_grid[i].shape)
  245. #print(self.anchor_grid[i][...,0].unsqueeze(4).shape)
  246. #print(x_kpt[..., 0::3].shape)
  247. #x_kpt[..., 0::3] = ((x_kpt[..., 0::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
  248. #x_kpt[..., 1::3] = ((x_kpt[..., 1::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
  249. #x_kpt[..., 0::3] = (((x_kpt[..., 0::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
  250. #x_kpt[..., 1::3] = (((x_kpt[..., 1::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
  251. x_kpt[..., 2::3] = x_kpt[..., 2::3].sigmoid()
  252. y = torch.cat((xy, wh, y[..., 4:], x_kpt), dim = -1)
  253. else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
  254. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  255. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  256. if self.nkpt != 0:
  257. y[..., 6:] = (y[..., 6:] * 2. - 0.5 + self.grid[i].repeat((1,1,1,1,self.nkpt))) * self.stride[i] # xy
  258. y = torch.cat((xy, wh, y[..., 4:]), -1)
  259. z.append(y.view(bs, -1, self.no))
  260. return x if self.training else (torch.cat(z, 1), x)
  261. @staticmethod
  262. def _make_grid(nx=20, ny=20):
  263. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  264. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  265. class IAuxDetect(nn.Module):
  266. stride = None # strides computed during build
  267. export = False # onnx export
  268. end2end = False
  269. include_nms = False
  270. concat = False
  271. def __init__(self, nc=80, anchors=(), ch=()): # detection layer
  272. super(IAuxDetect, self).__init__()
  273. self.nc = nc # number of classes
  274. self.no = nc + 5 # number of outputs per anchor
  275. self.nl = len(anchors) # number of detection layers
  276. self.na = len(anchors[0]) // 2 # number of anchors
  277. self.grid = [torch.zeros(1)] * self.nl # init grid
  278. a = torch.tensor(anchors).float().view(self.nl, -1, 2)
  279. self.register_buffer('anchors', a) # shape(nl,na,2)
  280. self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
  281. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[:self.nl]) # output conv
  282. self.m2 = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[self.nl:]) # output conv
  283. self.ia = nn.ModuleList(ImplicitA(x) for x in ch[:self.nl])
  284. self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch[:self.nl])
  285. def forward(self, x):
  286. # x = x.copy() # for profiling
  287. z = [] # inference output
  288. self.training |= self.export
  289. for i in range(self.nl):
  290. x[i] = self.m[i](self.ia[i](x[i])) # conv
  291. x[i] = self.im[i](x[i])
  292. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  293. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  294. x[i+self.nl] = self.m2[i](x[i+self.nl])
  295. x[i+self.nl] = x[i+self.nl].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  296. if not self.training: # inference
  297. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  298. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  299. y = x[i].sigmoid()
  300. if not torch.onnx.is_in_onnx_export():
  301. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  302. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  303. else:
  304. xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
  305. xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
  306. wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
  307. y = torch.cat((xy, wh, conf), 4)
  308. z.append(y.view(bs, -1, self.no))
  309. return x if self.training else (torch.cat(z, 1), x[:self.nl])
  310. def fuseforward(self, x):
  311. # x = x.copy() # for profiling
  312. z = [] # inference output
  313. self.training |= self.export
  314. for i in range(self.nl):
  315. x[i] = self.m[i](x[i]) # conv
  316. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  317. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  318. if not self.training: # inference
  319. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  320. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  321. y = x[i].sigmoid()
  322. if not torch.onnx.is_in_onnx_export():
  323. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  324. y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  325. else:
  326. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  327. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].data # wh
  328. y = torch.cat((xy, wh, y[..., 4:]), -1)
  329. z.append(y.view(bs, -1, self.no))
  330. if self.training:
  331. out = x
  332. elif self.end2end:
  333. out = torch.cat(z, 1)
  334. elif self.include_nms:
  335. z = self.convert(z)
  336. out = (z, )
  337. elif self.concat:
  338. out = torch.cat(z, 1)
  339. else:
  340. out = (torch.cat(z, 1), x)
  341. return out
  342. def fuse(self):
  343. print("IAuxDetect.fuse")
  344. # fuse ImplicitA and Convolution
  345. for i in range(len(self.m)):
  346. c1,c2,_,_ = self.m[i].weight.shape
  347. c1_,c2_, _,_ = self.ia[i].implicit.shape
  348. self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1)
  349. # fuse ImplicitM and Convolution
  350. for i in range(len(self.m)):
  351. c1,c2, _,_ = self.im[i].implicit.shape
  352. self.m[i].bias *= self.im[i].implicit.reshape(c2)
  353. self.m[i].weight *= self.im[i].implicit.transpose(0,1)
  354. @staticmethod
  355. def _make_grid(nx=20, ny=20):
  356. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  357. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  358. def convert(self, z):
  359. z = torch.cat(z, 1)
  360. box = z[:, :, :4]
  361. conf = z[:, :, 4:5]
  362. score = z[:, :, 5:]
  363. score *= conf
  364. convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
  365. dtype=torch.float32,
  366. device=z.device)
  367. box @= convert_matrix
  368. return (box, score)
  369. class IBin(nn.Module):
  370. stride = None # strides computed during build
  371. export = False # onnx export
  372. def __init__(self, nc=80, anchors=(), ch=(), bin_count=21): # detection layer
  373. super(IBin, self).__init__()
  374. self.nc = nc # number of classes
  375. self.bin_count = bin_count
  376. self.w_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
  377. self.h_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
  378. # classes, x,y,obj
  379. self.no = nc + 3 + \
  380. self.w_bin_sigmoid.get_length() + self.h_bin_sigmoid.get_length() # w-bce, h-bce
  381. # + self.x_bin_sigmoid.get_length() + self.y_bin_sigmoid.get_length()
  382. self.nl = len(anchors) # number of detection layers
  383. self.na = len(anchors[0]) // 2 # number of anchors
  384. self.grid = [torch.zeros(1)] * self.nl # init grid
  385. a = torch.tensor(anchors).float().view(self.nl, -1, 2)
  386. self.register_buffer('anchors', a) # shape(nl,na,2)
  387. self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
  388. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  389. self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
  390. self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
  391. def forward(self, x):
  392. #self.x_bin_sigmoid.use_fw_regression = True
  393. #self.y_bin_sigmoid.use_fw_regression = True
  394. self.w_bin_sigmoid.use_fw_regression = True
  395. self.h_bin_sigmoid.use_fw_regression = True
  396. # x = x.copy() # for profiling
  397. z = [] # inference output
  398. self.training |= self.export
  399. for i in range(self.nl):
  400. x[i] = self.m[i](self.ia[i](x[i])) # conv
  401. x[i] = self.im[i](x[i])
  402. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  403. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  404. if not self.training: # inference
  405. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  406. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  407. y = x[i].sigmoid()
  408. y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  409. #y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  410. #px = (self.x_bin_sigmoid.forward(y[..., 0:12]) + self.grid[i][..., 0]) * self.stride[i]
  411. #py = (self.y_bin_sigmoid.forward(y[..., 12:24]) + self.grid[i][..., 1]) * self.stride[i]
  412. pw = self.w_bin_sigmoid.forward(y[..., 2:24]) * self.anchor_grid[i][..., 0]
  413. ph = self.h_bin_sigmoid.forward(y[..., 24:46]) * self.anchor_grid[i][..., 1]
  414. #y[..., 0] = px
  415. #y[..., 1] = py
  416. y[..., 2] = pw
  417. y[..., 3] = ph
  418. y = torch.cat((y[..., 0:4], y[..., 46:]), dim=-1)
  419. z.append(y.view(bs, -1, y.shape[-1]))
  420. return x if self.training else (torch.cat(z, 1), x)
  421. @staticmethod
  422. def _make_grid(nx=20, ny=20):
  423. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  424. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  425. class Model(nn.Module):
  426. def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
  427. super(Model, self).__init__()
  428. self.traced = False
  429. if isinstance(cfg, dict):
  430. self.yaml = cfg # model dict
  431. else: # is *.yaml
  432. import yaml # for torch hub
  433. self.yaml_file = Path(cfg).name
  434. with open(cfg) as f:
  435. self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
  436. # Define model
  437. ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
  438. if nc and nc != self.yaml['nc']:
  439. logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  440. self.yaml['nc'] = nc # override yaml value
  441. if anchors:
  442. logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
  443. self.yaml['anchors'] = round(anchors) # override yaml value
  444. self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
  445. self.names = [str(i) for i in range(self.yaml['nc'])] # default names
  446. # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
  447. # Build strides, anchors
  448. m = self.model[-1] # Detect()
  449. if isinstance(m, Detect):
  450. s = 256 # 2x min stride
  451. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  452. check_anchor_order(m)
  453. m.anchors /= m.stride.view(-1, 1, 1)
  454. self.stride = m.stride
  455. self._initialize_biases() # only run once
  456. # print('Strides: %s' % m.stride.tolist())
  457. if isinstance(m, IDetect):
  458. s = 256 # 2x min stride
  459. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  460. check_anchor_order(m)
  461. m.anchors /= m.stride.view(-1, 1, 1)
  462. self.stride = m.stride
  463. self._initialize_biases() # only run once
  464. # print('Strides: %s' % m.stride.tolist())
  465. if isinstance(m, IAuxDetect):
  466. s = 256 # 2x min stride
  467. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward
  468. #print(m.stride)
  469. check_anchor_order(m)
  470. m.anchors /= m.stride.view(-1, 1, 1)
  471. self.stride = m.stride
  472. self._initialize_aux_biases() # only run once
  473. # print('Strides: %s' % m.stride.tolist())
  474. if isinstance(m, IBin):
  475. s = 256 # 2x min stride
  476. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  477. check_anchor_order(m)
  478. m.anchors /= m.stride.view(-1, 1, 1)
  479. self.stride = m.stride
  480. self._initialize_biases_bin() # only run once
  481. # print('Strides: %s' % m.stride.tolist())
  482. if isinstance(m, IKeypoint):
  483. s = 256 # 2x min stride
  484. m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
  485. check_anchor_order(m)
  486. m.anchors /= m.stride.view(-1, 1, 1)
  487. self.stride = m.stride
  488. self._initialize_biases_kpt() # only run once
  489. # print('Strides: %s' % m.stride.tolist())
  490. # Init weights, biases
  491. initialize_weights(self)
  492. self.info()
  493. logger.info('')
  494. def forward(self, x, augment=False, profile=False):
  495. if augment:
  496. img_size = x.shape[-2:] # height, width
  497. s = [1, 0.83, 0.67] # scales
  498. f = [None, 3, None] # flips (2-ud, 3-lr)
  499. y = [] # outputs
  500. for si, fi in zip(s, f):
  501. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  502. yi = self.forward_once(xi)[0] # forward
  503. # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
  504. yi[..., :4] /= si # de-scale
  505. if fi == 2:
  506. yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
  507. elif fi == 3:
  508. yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
  509. y.append(yi)
  510. return torch.cat(y, 1), None # augmented inference, train
  511. else:
  512. return self.forward_once(x, profile) # single-scale inference, train
  513. def forward_once(self, x, profile=False):
  514. y, dt = [], [] # outputs
  515. for m in self.model:
  516. if m.f != -1: # if not from previous layer
  517. 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
  518. if not hasattr(self, 'traced'):
  519. self.traced=False
  520. if self.traced:
  521. if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint):
  522. break
  523. if profile:
  524. c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))
  525. o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
  526. for _ in range(10):
  527. m(x.copy() if c else x)
  528. t = time_synchronized()
  529. for _ in range(10):
  530. m(x.copy() if c else x)
  531. dt.append((time_synchronized() - t) * 100)
  532. print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
  533. x = m(x) # run
  534. y.append(x if m.i in self.save else None) # save output
  535. if profile:
  536. print('%.1fms total' % sum(dt))
  537. return x
  538. def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
  539. # https://arxiv.org/abs/1708.02002 section 3.3
  540. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  541. m = self.model[-1] # Detect() module
  542. for mi, s in zip(m.m, m.stride): # from
  543. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  544. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  545. b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  546. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  547. def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
  548. # https://arxiv.org/abs/1708.02002 section 3.3
  549. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  550. m = self.model[-1] # Detect() module
  551. for mi, mi2, s in zip(m.m, m.m2, m.stride): # from
  552. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  553. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  554. b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  555. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  556. b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  557. b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  558. b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  559. mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)
  560. def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency
  561. # https://arxiv.org/abs/1708.02002 section 3.3
  562. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  563. m = self.model[-1] # Bin() module
  564. bc = m.bin_count
  565. for mi, s in zip(m.m, m.stride): # from
  566. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  567. old = b[:, (0,1,2,bc+3)].data
  568. obj_idx = 2*bc+4
  569. b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))
  570. b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  571. b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  572. b[:, (0,1,2,bc+3)].data = old
  573. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  574. def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency
  575. # https://arxiv.org/abs/1708.02002 section 3.3
  576. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  577. m = self.model[-1] # Detect() module
  578. for mi, s in zip(m.m, m.stride): # from
  579. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  580. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  581. b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  582. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  583. def _print_biases(self):
  584. m = self.model[-1] # Detect() module
  585. for mi in m.m: # from
  586. b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
  587. print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
  588. # def _print_weights(self):
  589. # for m in self.model.modules():
  590. # if type(m) is Bottleneck:
  591. # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
  592. def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
  593. print('Fusing layers... ')
  594. for m in self.model.modules():
  595. if isinstance(m, RepConv):
  596. #print(f" fuse_repvgg_block")
  597. m.fuse_repvgg_block()
  598. elif isinstance(m, RepConv_OREPA):
  599. #print(f" switch_to_deploy")
  600. m.switch_to_deploy()
  601. elif type(m) is Conv and hasattr(m, 'bn'):
  602. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  603. delattr(m, 'bn') # remove batchnorm
  604. m.forward = m.fuseforward # update forward
  605. elif isinstance(m, (IDetect, IAuxDetect)):
  606. m.fuse()
  607. m.forward = m.fuseforward
  608. self.info()
  609. return self
  610. def nms(self, mode=True): # add or remove NMS module
  611. present = type(self.model[-1]) is NMS # last layer is NMS
  612. if mode and not present:
  613. print('Adding NMS... ')
  614. m = NMS() # module
  615. m.f = -1 # from
  616. m.i = self.model[-1].i + 1 # index
  617. self.model.add_module(name='%s' % m.i, module=m) # add
  618. self.eval()
  619. elif not mode and present:
  620. print('Removing NMS... ')
  621. self.model = self.model[:-1] # remove
  622. return self
  623. def autoshape(self): # add autoShape module
  624. print('Adding autoShape... ')
  625. m = autoShape(self) # wrap model
  626. copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
  627. return m
  628. def info(self, verbose=False, img_size=640): # print model information
  629. model_info(self, verbose, img_size)
  630. def parse_model(d, ch): # model_dict, input_channels(3)
  631. logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
  632. anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
  633. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  634. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  635. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  636. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
  637. m = eval(m) if isinstance(m, str) else m # eval strings
  638. for j, a in enumerate(args):
  639. try:
  640. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  641. except:
  642. pass
  643. n = max(round(n * gd), 1) if n > 1 else n # depth gain
  644. if m in [nn.Conv2d, Conv, RobustConv, RobustConv2, DWConv, GhostConv, RepConv, RepConv_OREPA, DownC,
  645. SPP, SPPF, SPPCSPC, GhostSPPCSPC, MixConv2d, Focus, Stem, GhostStem, CrossConv,
  646. Bottleneck, BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
  647. RepBottleneck, RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
  648. Res, ResCSPA, ResCSPB, ResCSPC,
  649. RepRes, RepResCSPA, RepResCSPB, RepResCSPC,
  650. ResX, ResXCSPA, ResXCSPB, ResXCSPC,
  651. RepResX, RepResXCSPA, RepResXCSPB, RepResXCSPC,
  652. Ghost, GhostCSPA, GhostCSPB, GhostCSPC,
  653. SwinTransformerBlock, STCSPA, STCSPB, STCSPC,
  654. SwinTransformer2Block, ST2CSPA, ST2CSPB, ST2CSPC]:
  655. c1, c2 = ch[f], args[0]
  656. if c2 != no: # if not output
  657. c2 = make_divisible(c2 * gw, 8)
  658. args = [c1, c2, *args[1:]]
  659. if m in [DownC, SPPCSPC, GhostSPPCSPC,
  660. BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
  661. RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
  662. ResCSPA, ResCSPB, ResCSPC,
  663. RepResCSPA, RepResCSPB, RepResCSPC,
  664. ResXCSPA, ResXCSPB, ResXCSPC,
  665. RepResXCSPA, RepResXCSPB, RepResXCSPC,
  666. GhostCSPA, GhostCSPB, GhostCSPC,
  667. STCSPA, STCSPB, STCSPC,
  668. ST2CSPA, ST2CSPB, ST2CSPC]:
  669. args.insert(2, n) # number of repeats
  670. n = 1
  671. elif m is nn.BatchNorm2d:
  672. args = [ch[f]]
  673. elif m is Concat:
  674. c2 = sum([ch[x] for x in f])
  675. elif m is Chuncat:
  676. c2 = sum([ch[x] for x in f])
  677. elif m is Shortcut:
  678. c2 = ch[f[0]]
  679. elif m is Foldcut:
  680. c2 = ch[f] // 2
  681. elif m in [Detect, IDetect, IAuxDetect, IBin, IKeypoint]:
  682. args.append([ch[x] for x in f])
  683. if isinstance(args[1], int): # number of anchors
  684. args[1] = [list(range(args[1] * 2))] * len(f)
  685. elif m is ReOrg:
  686. c2 = ch[f] * 4
  687. elif m is Contract:
  688. c2 = ch[f] * args[0] ** 2
  689. elif m is Expand:
  690. c2 = ch[f] // args[0] ** 2
  691. else:
  692. c2 = ch[f]
  693. m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
  694. t = str(m)[8:-2].replace('__main__.', '') # module type
  695. np = sum([x.numel() for x in m_.parameters()]) # number params
  696. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  697. logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
  698. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  699. layers.append(m_)
  700. if i == 0:
  701. ch = []
  702. ch.append(c2)
  703. return nn.Sequential(*layers), sorted(save)
  704. if __name__ == '__main__':
  705. parser = argparse.ArgumentParser()
  706. parser.add_argument('--cfg', type=str, default='yolor-csp-c.yaml', help='model.yaml')
  707. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  708. parser.add_argument('--profile', action='store_true', help='profile model speed')
  709. opt = parser.parse_args()
  710. opt.cfg = check_file(opt.cfg) # check file
  711. set_logging()
  712. device = select_device(opt.device)
  713. # Create model
  714. model = Model(opt.cfg).to(device)
  715. model.train()
  716. if opt.profile:
  717. img = torch.rand(1, 3, 640, 640).to(device)
  718. y = model(img, profile=True)
  719. # Profile
  720. # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
  721. # y = model(img, profile=True)
  722. # Tensorboard
  723. # from torch.utils.tensorboard import SummaryWriter
  724. # tb_writer = SummaryWriter()
  725. # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
  726. # tb_writer.add_graph(model.model, img) # add model to tensorboard
  727. # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard