yolov6_basic.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # --------------------- Basic modules ---------------------
  5. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  6. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  7. return conv
  8. def get_activation(act_type=None):
  9. if act_type == 'relu':
  10. return nn.ReLU(inplace=True)
  11. elif act_type == 'lrelu':
  12. return nn.LeakyReLU(0.1, inplace=True)
  13. elif act_type == 'mish':
  14. return nn.Mish(inplace=True)
  15. elif act_type == 'silu':
  16. return nn.SiLU(inplace=True)
  17. elif act_type is None:
  18. return nn.Identity()
  19. else:
  20. raise NotImplementedError
  21. def get_norm(norm_type, dim):
  22. if norm_type == 'BN':
  23. return nn.BatchNorm2d(dim)
  24. elif norm_type == 'GN':
  25. return nn.GroupNorm(num_groups=32, num_channels=dim)
  26. elif norm_type is None:
  27. return nn.Identity()
  28. else:
  29. raise NotImplementedError
  30. class BasicConv(nn.Module):
  31. def __init__(self,
  32. in_dim, # in channels
  33. out_dim, # out channels
  34. kernel_size=1, # kernel size
  35. padding=0, # padding
  36. stride=1, # padding
  37. dilation=1, # dilation
  38. act_type :str = 'lrelu', # activation
  39. norm_type :str = 'BN', # normalization
  40. depthwise :bool = False
  41. ):
  42. super(BasicConv, self).__init__()
  43. self.depthwise = depthwise
  44. if not depthwise:
  45. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1, bias=True)
  46. self.norm = get_norm(norm_type, out_dim)
  47. else:
  48. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim, bias=True)
  49. self.norm1 = get_norm(norm_type, in_dim)
  50. self.conv2 = get_conv2d(in_dim, out_dim, k=1, p=0, s=1, d=1, g=1, bias=True)
  51. self.norm2 = get_norm(norm_type, out_dim)
  52. self.act = get_activation(act_type)
  53. def forward(self, x):
  54. if not self.depthwise:
  55. return self.act(self.norm(self.conv(x)))
  56. else:
  57. # Depthwise conv
  58. x = self.norm1(self.conv1(x))
  59. # Pointwise conv
  60. x = self.act(self.norm2(self.conv2(x)))
  61. return x
  62. class RepVGGBlock(nn.Module):
  63. def __init__(self,
  64. in_channels,
  65. out_channels,
  66. kernel_size=3,
  67. stride=1,
  68. padding=1,
  69. dilation=1,
  70. groups=1,
  71. deploy=False,
  72. ):
  73. super(RepVGGBlock, self).__init__()
  74. assert kernel_size == 3
  75. assert padding == 1
  76. # --------- Basic parameters ---------
  77. self.deploy = deploy
  78. self.groups = groups
  79. self.in_channels = in_channels
  80. self.out_channels = out_channels
  81. padding_11 = padding - kernel_size // 2
  82. # --------- Model parameters ---------
  83. if deploy:
  84. self.rbr_reparam = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
  85. padding=padding, dilation=dilation, groups=groups, bias=True)
  86. else:
  87. self.rbr_identity = nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
  88. self.rbr_dense = BasicConv(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, act_type=None)
  89. self.rbr_1x1 = BasicConv(in_channels, out_channels, kernel_size=1, padding=padding_11, stride=stride, act_type=None)
  90. self.nonlinearity = nn.ReLU()
  91. def forward(self, inputs):
  92. '''Forward process'''
  93. if hasattr(self, 'rbr_reparam'):
  94. return self.nonlinearity(self.rbr_reparam(inputs))
  95. if self.rbr_identity is None:
  96. id_out = 0
  97. else:
  98. id_out = self.rbr_identity(inputs)
  99. return self.nonlinearity(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
  100. def get_equivalent_kernel_bias(self):
  101. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
  102. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
  103. kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
  104. return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
  105. def _avg_to_3x3_tensor(self, avgp):
  106. channels = self.in_channels
  107. groups = self.groups
  108. kernel_size = avgp.kernel_size
  109. input_dim = channels // groups
  110. k = torch.zeros((channels, input_dim, kernel_size, kernel_size))
  111. k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2
  112. return k
  113. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  114. if kernel1x1 is None:
  115. return 0
  116. else:
  117. return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  118. def _fuse_bn_tensor(self, branch):
  119. if branch is None:
  120. return 0, 0
  121. if isinstance(branch, BasicConv):
  122. kernel = branch.conv.weight
  123. bias = branch.conv.bias
  124. return kernel, bias
  125. elif isinstance(branch, nn.BatchNorm2d):
  126. if not hasattr(self, 'id_tensor'):
  127. input_dim = self.in_channels // self.groups
  128. kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
  129. for i in range(self.in_channels):
  130. kernel_value[i, i % input_dim, 1, 1] = 1
  131. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  132. kernel = self.id_tensor
  133. running_mean = branch.running_mean
  134. running_var = branch.running_var
  135. gamma = branch.weight
  136. beta = branch.bias
  137. eps = branch.eps
  138. std = (running_var + eps).sqrt()
  139. t = (gamma / std).reshape(-1, 1, 1, 1)
  140. return kernel * t, beta - running_mean * gamma / std
  141. def switch_to_deploy(self):
  142. if hasattr(self, 'rbr_reparam'):
  143. return
  144. kernel, bias = self.get_equivalent_kernel_bias()
  145. self.rbr_reparam = nn.Conv2d(in_channels=self.rbr_dense.conv.in_channels, out_channels=self.rbr_dense.conv.out_channels,
  146. kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
  147. padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation, groups=self.rbr_dense.conv.groups, bias=True)
  148. self.rbr_reparam.weight.data = kernel
  149. self.rbr_reparam.bias.data = bias
  150. for para in self.parameters():
  151. para.detach_()
  152. self.__delattr__('rbr_dense')
  153. self.__delattr__('rbr_1x1')
  154. if hasattr(self, 'rbr_identity'):
  155. self.__delattr__('rbr_identity')
  156. if hasattr(self, 'id_tensor'):
  157. self.__delattr__('id_tensor')
  158. self.deploy = True
  159. # ---------------------------- Basic Modules ----------------------------
  160. class RepBlock(nn.Module):
  161. def __init__(self, in_channels, out_channels, num_blocks=1, block=RepVGGBlock):
  162. super().__init__()
  163. self.conv1 = block(in_channels, out_channels)
  164. self.block = nn.Sequential(*(block(out_channels, out_channels)
  165. for _ in range(num_blocks - 1))) if num_blocks > 1 else nn.Identity()
  166. if block == BottleRep:
  167. self.conv1 = BottleRep(in_channels, out_channels, weight=True)
  168. num_blocks = num_blocks // 2
  169. self.block = nn.Sequential(*(BottleRep(out_channels, out_channels, weight=True)
  170. for _ in range(num_blocks - 1))) if num_blocks > 1 else None
  171. def forward(self, x):
  172. x = self.conv1(x)
  173. if self.block is not None:
  174. x = self.block(x)
  175. return x
  176. class BottleRep(nn.Module):
  177. def __init__(self, in_channels, out_channels, weight=False):
  178. super().__init__()
  179. self.conv1 = RepVGGBlock(in_channels, out_channels, kernel_size=3, padding=1, stride=1)
  180. self.conv2 = RepVGGBlock(out_channels, out_channels, kernel_size=3, padding=1, stride=1)
  181. if in_channels != out_channels:
  182. self.shortcut = False
  183. else:
  184. self.shortcut = True
  185. if weight:
  186. self.alpha = nn.Parameter(torch.ones(1))
  187. else:
  188. self.alpha = 1.0
  189. def forward(self, x):
  190. outputs = self.conv1(x)
  191. outputs = self.conv2(outputs)
  192. return outputs + self.alpha * x if self.shortcut else outputs
  193. class RepCSPBlock(nn.Module):
  194. def __init__(self, in_channels, out_channels, num_blocks=1, expansion=0.5):
  195. super().__init__()
  196. inter_dim = round(out_channels * expansion) # hidden channels
  197. self.cv1 = BasicConv(in_channels, inter_dim, kernel_size=1, act_type='relu')
  198. self.cv2 = BasicConv(in_channels, inter_dim, kernel_size=1, act_type='relu')
  199. self.cv3 = BasicConv(2 * inter_dim, out_channels, kernel_size=1, act_type='relu')
  200. self.module = RepBlock(inter_dim, inter_dim, num_blocks, block=BottleRep)
  201. def forward(self, x):
  202. x1 = self.cv1(x)
  203. x2 = self.module(self.cv2(x))
  204. out = self.cv3(torch.cat((x1, x2), dim=1))
  205. return out