yolov7_basic.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # ---------------------------- 2D CNN ----------------------------
  5. class SiLU(nn.Module):
  6. """export-friendly version of nn.SiLU()"""
  7. @staticmethod
  8. def forward(x):
  9. return x * torch.sigmoid(x)
  10. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  11. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  12. return conv
  13. def get_activation(act_type=None):
  14. if act_type == 'relu':
  15. return nn.ReLU(inplace=True)
  16. elif act_type == 'lrelu':
  17. return nn.LeakyReLU(0.1, inplace=True)
  18. elif act_type == 'mish':
  19. return nn.Mish(inplace=True)
  20. elif act_type == 'silu':
  21. return nn.SiLU(inplace=True)
  22. def get_norm(norm_type, dim):
  23. if norm_type == 'BN':
  24. return nn.BatchNorm2d(dim)
  25. elif norm_type == 'GN':
  26. return nn.GroupNorm(num_groups=32, num_channels=dim)
  27. ## Basic conv layer
  28. class Conv(nn.Module):
  29. def __init__(self,
  30. c1, # in channels
  31. c2, # out channels
  32. k=1, # kernel size
  33. p=0, # padding
  34. s=1, # padding
  35. d=1, # dilation
  36. act_type='lrelu', # activation
  37. norm_type='BN', # normalization
  38. depthwise=False):
  39. super(Conv, self).__init__()
  40. convs = []
  41. add_bias = False if norm_type else True
  42. if depthwise:
  43. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  44. # depthwise conv
  45. if norm_type:
  46. convs.append(get_norm(norm_type, c1))
  47. if act_type:
  48. convs.append(get_activation(act_type))
  49. # pointwise conv
  50. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  51. if norm_type:
  52. convs.append(get_norm(norm_type, c2))
  53. if act_type:
  54. convs.append(get_activation(act_type))
  55. else:
  56. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  57. if norm_type:
  58. convs.append(get_norm(norm_type, c2))
  59. if act_type:
  60. convs.append(get_activation(act_type))
  61. self.convs = nn.Sequential(*convs)
  62. def forward(self, x):
  63. return self.convs(x)
  64. # ---------------------------- YOLOv7 Modules ----------------------------
  65. ## ELAN-Block proposed by YOLOv7
  66. class ELANBlock(nn.Module):
  67. def __init__(self, in_dim, out_dim, squeeze_ratio=0.5, branch_depth :int=2, act_type='silu', norm_type='BN', depthwise=False):
  68. super(ELANBlock, self).__init__()
  69. inter_dim = int(in_dim * squeeze_ratio)
  70. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  71. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  72. self.cv3 = nn.Sequential(*[
  73. Conv(inter_dim, inter_dim, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  74. for _ in range(round(branch_depth))
  75. ])
  76. self.cv4 = nn.Sequential(*[
  77. Conv(inter_dim, inter_dim, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  78. for _ in range(round(branch_depth))
  79. ])
  80. self.out = Conv(inter_dim*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  81. def forward(self, x):
  82. x1 = self.cv1(x)
  83. x2 = self.cv2(x)
  84. x3 = self.cv3(x2)
  85. x4 = self.cv4(x3)
  86. out = self.out(torch.cat([x1, x2, x3, x4], dim=1))
  87. return out
  88. ## PaFPN's ELAN-Block proposed by YOLOv7
  89. class ELANBlockFPN(nn.Module):
  90. def __init__(self, in_dim, out_dim, squeeze_ratio=0.5, branch_width :int=4, branch_depth :int=1, act_type='silu', norm_type='BN', depthwise=False):
  91. super(ELANBlockFPN, self).__init__()
  92. # Basic parameters
  93. inter_dim = int(in_dim * squeeze_ratio)
  94. inter_dim2 = int(inter_dim * squeeze_ratio)
  95. # Network structure
  96. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  97. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  98. self.cv3 = nn.ModuleList()
  99. for idx in range(round(branch_width)):
  100. if idx == 0:
  101. cvs = [Conv(inter_dim, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  102. else:
  103. cvs = [Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  104. # deeper
  105. if round(branch_depth) > 1:
  106. for _ in range(1, round(branch_depth)):
  107. cvs.append(Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  108. self.cv3.append(nn.Sequential(*cvs))
  109. else:
  110. self.cv3.append(cvs[0])
  111. self.out = Conv(inter_dim*2+inter_dim2*len(self.cv3), out_dim, k=1, act_type=act_type, norm_type=norm_type)
  112. def forward(self, x):
  113. x1 = self.cv1(x)
  114. x2 = self.cv2(x)
  115. inter_outs = [x1, x2]
  116. for m in self.cv3:
  117. y1 = inter_outs[-1]
  118. y2 = m(y1)
  119. inter_outs.append(y2)
  120. out = self.out(torch.cat(inter_outs, dim=1))
  121. return out
  122. ## DownSample Block proposed by YOLOv7
  123. class DownSample(nn.Module):
  124. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  125. super().__init__()
  126. inter_dim = out_dim // 2
  127. self.mp = nn.MaxPool2d((2, 2), 2)
  128. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  129. self.cv2 = nn.Sequential(
  130. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  131. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  132. )
  133. def forward(self, x):
  134. x1 = self.cv1(self.mp(x))
  135. x2 = self.cv2(x)
  136. out = torch.cat([x1, x2], dim=1)
  137. return out
  138. # ---------------------------- RepConv Modules ----------------------------
  139. class RepConv(nn.Module):
  140. """
  141. The code referenced to https://github.com/WongKinYiu/yolov7/models/common.py
  142. """
  143. # Represented convolution
  144. # https://arxiv.org/abs/2101.03697
  145. def __init__(self, c1, c2, k=3, s=1, p=1, g=1, act_type='silu', deploy=False):
  146. super(RepConv, self).__init__()
  147. # -------------- Basic parameters --------------
  148. self.deploy = deploy
  149. self.groups = g
  150. self.in_channels = c1
  151. self.out_channels = c2
  152. # -------------- Network parameters --------------
  153. if deploy:
  154. self.rbr_reparam = nn.Conv2d(c1, c2, k, s, p, groups=g, bias=True)
  155. else:
  156. self.rbr_identity = (nn.BatchNorm2d(num_features=c1) if c2 == c1 and s == 1 else None)
  157. self.rbr_dense = nn.Sequential(
  158. nn.Conv2d(c1, c2, k, s, p, groups=g, bias=False),
  159. nn.BatchNorm2d(num_features=c2),
  160. )
  161. self.rbr_1x1 = nn.Sequential(
  162. nn.Conv2d(c1, c2, kernel_size=1, stride=s, bias=False),
  163. nn.BatchNorm2d(num_features=c2),
  164. )
  165. self.act = get_activation(act_type)
  166. def forward(self, inputs):
  167. if hasattr(self, "rbr_reparam"):
  168. return self.act(self.rbr_reparam(inputs))
  169. if self.rbr_identity is None:
  170. id_out = 0
  171. else:
  172. id_out = self.rbr_identity(inputs)
  173. return self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
  174. def get_equivalent_kernel_bias(self):
  175. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
  176. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
  177. kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
  178. return (
  179. kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid,
  180. bias3x3 + bias1x1 + biasid,
  181. )
  182. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  183. if kernel1x1 is None:
  184. return 0
  185. else:
  186. return nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  187. def _fuse_bn_tensor(self, branch):
  188. if branch is None:
  189. return 0, 0
  190. if isinstance(branch, nn.Sequential):
  191. kernel = branch[0].weight
  192. running_mean = branch[1].running_mean
  193. running_var = branch[1].running_var
  194. gamma = branch[1].weight
  195. beta = branch[1].bias
  196. eps = branch[1].eps
  197. else:
  198. assert isinstance(branch, nn.BatchNorm2d)
  199. if not hasattr(self, "id_tensor"):
  200. input_dim = self.in_channels // self.groups
  201. kernel_value = np.zeros(
  202. (self.in_channels, input_dim, 3, 3), dtype=np.float32
  203. )
  204. for i in range(self.in_channels):
  205. kernel_value[i, i % input_dim, 1, 1] = 1
  206. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  207. kernel = self.id_tensor
  208. running_mean = branch.running_mean
  209. running_var = branch.running_var
  210. gamma = branch.weight
  211. beta = branch.bias
  212. eps = branch.eps
  213. std = (running_var + eps).sqrt()
  214. t = (gamma / std).reshape(-1, 1, 1, 1)
  215. return kernel * t, beta - running_mean * gamma / std
  216. def repvgg_convert(self):
  217. kernel, bias = self.get_equivalent_kernel_bias()
  218. return (
  219. kernel.detach().cpu().numpy(),
  220. bias.detach().cpu().numpy(),
  221. )
  222. def fuse_conv_bn(self, conv, bn):
  223. std = (bn.running_var + bn.eps).sqrt()
  224. bias = bn.bias - bn.running_mean * bn.weight / std
  225. t = (bn.weight / std).reshape(-1, 1, 1, 1)
  226. weights = conv.weight * t
  227. bn = nn.Identity()
  228. conv = nn.Conv2d(in_channels = conv.in_channels,
  229. out_channels = conv.out_channels,
  230. kernel_size = conv.kernel_size,
  231. stride=conv.stride,
  232. padding = conv.padding,
  233. dilation = conv.dilation,
  234. groups = conv.groups,
  235. bias = True,
  236. padding_mode = conv.padding_mode)
  237. conv.weight = torch.nn.Parameter(weights)
  238. conv.bias = torch.nn.Parameter(bias)
  239. return conv
  240. def fuse_repvgg_block(self):
  241. if self.deploy:
  242. return
  243. self.rbr_dense = self.fuse_conv_bn(self.rbr_dense[0], self.rbr_dense[1])
  244. self.rbr_1x1 = self.fuse_conv_bn(self.rbr_1x1[0], self.rbr_1x1[1])
  245. rbr_1x1_bias = self.rbr_1x1.bias
  246. weight_1x1_expanded = torch.nn.functional.pad(self.rbr_1x1.weight, [1, 1, 1, 1])
  247. # Fuse self.rbr_identity
  248. if (isinstance(self.rbr_identity, nn.BatchNorm2d) or isinstance(self.rbr_identity, nn.modules.batchnorm.SyncBatchNorm)):
  249. identity_conv_1x1 = nn.Conv2d(
  250. in_channels=self.in_channels,
  251. out_channels=self.out_channels,
  252. kernel_size=1,
  253. stride=1,
  254. padding=0,
  255. groups=self.groups,
  256. bias=False)
  257. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.to(self.rbr_1x1.weight.data.device)
  258. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.squeeze().squeeze()
  259. identity_conv_1x1.weight.data.fill_(0.0)
  260. identity_conv_1x1.weight.data.fill_diagonal_(1.0)
  261. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.unsqueeze(2).unsqueeze(3)
  262. identity_conv_1x1 = self.fuse_conv_bn(identity_conv_1x1, self.rbr_identity)
  263. bias_identity_expanded = identity_conv_1x1.bias
  264. weight_identity_expanded = torch.nn.functional.pad(identity_conv_1x1.weight, [1, 1, 1, 1])
  265. else:
  266. bias_identity_expanded = torch.nn.Parameter( torch.zeros_like(rbr_1x1_bias) )
  267. weight_identity_expanded = torch.nn.Parameter( torch.zeros_like(weight_1x1_expanded) )
  268. self.rbr_dense.weight = torch.nn.Parameter(self.rbr_dense.weight + weight_1x1_expanded + weight_identity_expanded)
  269. self.rbr_dense.bias = torch.nn.Parameter(self.rbr_dense.bias + rbr_1x1_bias + bias_identity_expanded)
  270. self.rbr_reparam = self.rbr_dense
  271. self.deploy = True
  272. if self.rbr_identity is not None:
  273. del self.rbr_identity
  274. self.rbr_identity = None
  275. if self.rbr_1x1 is not None:
  276. del self.rbr_1x1
  277. self.rbr_1x1 = None
  278. if self.rbr_dense is not None:
  279. del self.rbr_dense
  280. self.rbr_dense = None