yolov6_basic.py 9.3 KB

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