conv.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import math
  2. from typing import List
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from .norm import LayerNorm2D
  7. def get_conv2d(c1, c2, k, p, s, d, g):
  8. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g)
  9. return conv
  10. def get_activation(act_type=None):
  11. if act_type is None:
  12. return nn.Identity()
  13. elif act_type == 'relu':
  14. return nn.ReLU(inplace=True)
  15. elif act_type == 'lrelu':
  16. return nn.LeakyReLU(0.1, inplace=True)
  17. elif act_type == 'mish':
  18. return nn.Mish(inplace=True)
  19. elif act_type == 'silu':
  20. return nn.SiLU(inplace=True)
  21. elif act_type == 'gelu':
  22. return nn.GELU()
  23. else:
  24. raise NotImplementedError(act_type)
  25. def get_norm(norm_type, dim):
  26. if norm_type == 'BN':
  27. return nn.BatchNorm2d(dim)
  28. elif norm_type == 'GN':
  29. return nn.GroupNorm(num_groups=32, num_channels=dim)
  30. elif norm_type is None:
  31. return nn.Identity()
  32. else:
  33. raise NotImplementedError(norm_type)
  34. # ----------------- CNN ops -----------------
  35. class ConvModule(nn.Module):
  36. def __init__(self,
  37. c1,
  38. c2,
  39. k=1,
  40. p=0,
  41. s=1,
  42. d=1,
  43. act_type='relu',
  44. norm_type='BN',
  45. depthwise=False):
  46. super(ConvModule, self).__init__()
  47. convs = []
  48. if depthwise:
  49. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1))
  50. # depthwise conv
  51. if norm_type:
  52. convs.append(get_norm(norm_type, c1))
  53. if act_type:
  54. convs.append(get_activation(act_type))
  55. # pointwise conv
  56. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1))
  57. if norm_type:
  58. convs.append(get_norm(norm_type, c2))
  59. if act_type:
  60. convs.append(get_activation(act_type))
  61. else:
  62. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1))
  63. if norm_type:
  64. convs.append(get_norm(norm_type, c2))
  65. if act_type:
  66. convs.append(get_activation(act_type))
  67. self.convs = nn.Sequential(*convs)
  68. def forward(self, x):
  69. return self.convs(x)
  70. class BasicConv(nn.Module):
  71. def __init__(self,
  72. in_dim, # in channels
  73. out_dim, # out channels
  74. kernel_size=1, # kernel size
  75. padding=0, # padding
  76. stride=1, # padding
  77. dilation=1, # dilation
  78. act_type :str = 'lrelu', # activation
  79. norm_type :str = 'BN', # normalization
  80. depthwise :bool = False
  81. ):
  82. super(BasicConv, self).__init__()
  83. self.depthwise = depthwise
  84. if not depthwise:
  85. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1)
  86. self.norm = get_norm(norm_type, out_dim)
  87. else:
  88. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim)
  89. self.norm1 = get_norm(norm_type, in_dim)
  90. self.conv2 = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1)
  91. self.norm2 = get_norm(norm_type, out_dim)
  92. self.act = get_activation(act_type)
  93. def forward(self, x):
  94. if not self.depthwise:
  95. return self.act(self.norm(self.conv(x)))
  96. else:
  97. # Depthwise conv
  98. x = self.norm1(self.conv1(x))
  99. # Pointwise conv
  100. x = self.norm2(self.conv2(x))
  101. return x
  102. class UpSampleWrapper(nn.Module):
  103. """Upsample last feat map to specific stride."""
  104. def __init__(self, in_dim, upsample_factor):
  105. super(UpSampleWrapper, self).__init__()
  106. # ---------- Basic parameters ----------
  107. self.upsample_factor = upsample_factor
  108. # ---------- Network parameters ----------
  109. if upsample_factor == 1:
  110. self.upsample = nn.Identity()
  111. else:
  112. scale = int(math.log2(upsample_factor))
  113. dim = in_dim
  114. layers = []
  115. for _ in range(scale-1):
  116. layers += [
  117. nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2),
  118. LayerNorm2D(dim),
  119. nn.GELU()
  120. ]
  121. layers += [nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2)]
  122. self.upsample = nn.Sequential(*layers)
  123. self.out_dim = dim
  124. def forward(self, x):
  125. x = self.upsample(x)
  126. return x
  127. # ----------------- RepCNN module -----------------
  128. class RepVggBlock(nn.Module):
  129. def __init__(self, in_dim, out_dim, act_type='relu', norm_type='BN'):
  130. super().__init__()
  131. # ----------------- Basic parameters -----------------
  132. self.in_dim = in_dim
  133. self.out_dim = out_dim
  134. # ----------------- Network parameters -----------------
  135. self.conv1 = BasicConv(in_dim, out_dim, kernel_size=3, padding=1, act_type=None, norm_type=norm_type)
  136. self.conv2 = BasicConv(in_dim, out_dim, kernel_size=1, padding=0, act_type=None, norm_type=norm_type)
  137. self.act = get_activation(act_type)
  138. def forward(self, x):
  139. if hasattr(self, 'conv'):
  140. y = self.conv(x)
  141. else:
  142. y = self.conv1(x) + self.conv2(x)
  143. return self.act(y)
  144. def convert_to_deploy(self):
  145. if not hasattr(self, 'conv'):
  146. self.conv = nn.Conv2d(self.in_dim, self.out_dim, 3, 1, padding=1)
  147. kernel, bias = self.get_equivalent_kernel_bias()
  148. self.conv.weight.data = kernel
  149. self.conv.bias.data = bias
  150. # self.__delattr__('conv1')
  151. # self.__delattr__('conv2')
  152. def get_equivalent_kernel_bias(self):
  153. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
  154. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
  155. return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1), bias3x3 + bias1x1
  156. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  157. if kernel1x1 is None:
  158. return 0
  159. else:
  160. return F.pad(kernel1x1, [1, 1, 1, 1])
  161. def _fuse_bn_tensor(self, branch: BasicConv):
  162. if branch is None:
  163. return 0, 0
  164. kernel = branch.conv.weight
  165. running_mean = branch.norm.running_mean
  166. running_var = branch.norm.running_var
  167. gamma = branch.norm.weight
  168. beta = branch.norm.bias
  169. eps = branch.norm.eps
  170. std = (running_var + eps).sqrt()
  171. t = (gamma / std).reshape(-1, 1, 1, 1)
  172. return kernel * t, beta - running_mean * gamma / std
  173. class RepCSPLayer(nn.Module):
  174. def __init__(self,
  175. in_dim :int = 256,
  176. out_dim :int = 256,
  177. num_blocks :int = 3,
  178. expansion :float = 1.0,
  179. act_type :str = "relu",
  180. norm_type :str = "GN",):
  181. super(RepCSPLayer, self).__init__()
  182. # ----------------- Basic parameters -----------------
  183. inter_dim = int(out_dim * expansion)
  184. # ----------------- Network parameters -----------------
  185. self.conv1 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  186. self.conv2 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  187. self.bottlenecks = nn.Sequential(*[
  188. RepVggBlock(inter_dim, inter_dim, act_type, norm_type) for _ in range(num_blocks)
  189. ])
  190. if inter_dim != out_dim:
  191. self.conv3 = BasicConv(inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  192. else:
  193. self.conv3 = nn.Identity()
  194. def forward(self, x):
  195. x_1 = self.conv1(x)
  196. x_1 = self.bottlenecks(x_1)
  197. x_2 = self.conv2(x)
  198. return self.conv3(x_1 + x_2)
  199. # ----------------- CNN module -----------------
  200. class YoloBottleneck(nn.Module):
  201. def __init__(self,
  202. in_dim :int,
  203. out_dim :int,
  204. kernel_size :List = [1, 3],
  205. expand_ratio :float = 0.5,
  206. shortcut :bool = False,
  207. act_type :str = 'silu',
  208. norm_type :str = 'BN',
  209. depthwise :bool = False,
  210. ) -> None:
  211. super(YoloBottleneck, self).__init__()
  212. inter_dim = int(out_dim * expand_ratio)
  213. # ----------------- Network setting -----------------
  214. self.conv_layer1 = BasicConv(in_dim, inter_dim,
  215. kernel_size=kernel_size[0], padding=kernel_size[0]//2, stride=1,
  216. act_type=act_type, norm_type=norm_type)
  217. self.conv_layer2 = BasicConv(inter_dim, out_dim,
  218. kernel_size=kernel_size[1], padding=kernel_size[1]//2, stride=1,
  219. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  220. self.shortcut = shortcut and in_dim == out_dim
  221. def forward(self, x):
  222. h = self.conv_layer2(self.conv_layer1(x))
  223. return x + h if self.shortcut else h
  224. class ELANLayer(nn.Module):
  225. def __init__(self,
  226. in_dim,
  227. out_dim,
  228. expand_ratio :float = 0.5,
  229. num_blocks :int = 1,
  230. shortcut :bool = False,
  231. act_type :str = 'silu',
  232. norm_type :str = 'BN',
  233. depthwise :bool = False,
  234. ) -> None:
  235. super(ELANLayer, self).__init__()
  236. self.inter_dim = round(out_dim * expand_ratio)
  237. self.input_proj = BasicConv(in_dim, self.inter_dim * 2, kernel_size=1, act_type=act_type, norm_type=norm_type)
  238. self.output_proj = BasicConv((2 + num_blocks) * self.inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  239. self.module = nn.ModuleList([YoloBottleneck(self.inter_dim,
  240. self.inter_dim,
  241. kernel_size = [3, 3],
  242. expand_ratio = 1.0,
  243. shortcut = shortcut,
  244. act_type = act_type,
  245. norm_type = norm_type,
  246. depthwise = depthwise)
  247. for _ in range(num_blocks)])
  248. def forward(self, x):
  249. # Input proj
  250. x1, x2 = torch.chunk(self.input_proj(x), 2, dim=1)
  251. out = list([x1, x2])
  252. # Bottlenecl
  253. out.extend(m(out[-1]) for m in self.module)
  254. # Output proj
  255. out = self.output_proj(torch.cat(out, dim=1))
  256. return out