modules.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. from typing import List
  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. group=1, # group
  40. act_type :str = 'lrelu', # activation
  41. norm_type :str = 'BN', # normalization
  42. depthwise :bool = False
  43. ):
  44. super(BasicConv, self).__init__()
  45. self.depthwise = depthwise
  46. if not depthwise:
  47. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=group)
  48. self.norm = get_norm(norm_type, out_dim)
  49. else:
  50. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim)
  51. self.norm1 = get_norm(norm_type, in_dim)
  52. self.conv2 = get_conv2d(in_dim, out_dim, k=1, p=0, s=1, d=1, g=1)
  53. self.norm2 = get_norm(norm_type, out_dim)
  54. self.act = get_activation(act_type)
  55. def forward(self, x):
  56. if not self.depthwise:
  57. return self.act(self.norm(self.conv(x)))
  58. else:
  59. # Depthwise conv
  60. x = self.norm1(self.conv1(x))
  61. # Pointwise conv
  62. x = self.act(self.norm2(self.conv2(x)))
  63. return x
  64. # --------------------- GELAN modules (from yolov9) ---------------------
  65. class ADown(nn.Module):
  66. def __init__(self, in_dim, out_dim, act_type="silu", norm_type="BN", depthwise=False):
  67. super().__init__()
  68. inter_dim = out_dim // 2
  69. self.conv_layer_1 = BasicConv(in_dim // 2, inter_dim,
  70. kernel_size=3, padding=1, stride=2,
  71. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  72. self.conv_layer_2 = BasicConv(in_dim // 2, inter_dim, kernel_size=1,
  73. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  74. def forward(self, x):
  75. x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
  76. x1,x2 = x.chunk(2, 1)
  77. x1 = self.conv_layer_1(x1)
  78. x2 = torch.nn.functional.max_pool2d(x2, 3, 2, 1)
  79. x2 = self.conv_layer_2(x2)
  80. return torch.cat((x1, x2), 1)
  81. class RepConvN(nn.Module):
  82. """RepConv is a basic rep-style block, including training and deploy status
  83. This code is based on https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py
  84. """
  85. def __init__(self, in_dim, out_dim, k=3, s=1, p=1, g=1, act_type='silu', norm_type='BN', depthwise=False):
  86. super().__init__()
  87. assert k == 3 and p == 1
  88. self.g = g
  89. self.in_dim = in_dim
  90. self.out_dim = out_dim
  91. self.act = get_activation(act_type)
  92. self.bn = None
  93. self.conv1 = BasicConv(in_dim, out_dim,
  94. kernel_size=k, padding=p, stride=s, group=g,
  95. act_type=None, norm_type=norm_type, depthwise=depthwise)
  96. self.conv2 = BasicConv(in_dim, out_dim,
  97. kernel_size=1, padding=(p - k // 2), stride=s, group=g,
  98. act_type=None, norm_type=norm_type, depthwise=depthwise)
  99. def forward(self, x):
  100. """Forward process"""
  101. if hasattr(self, 'conv'):
  102. return self.forward_fuse(x)
  103. else:
  104. id_out = 0 if self.bn is None else self.bn(x)
  105. return self.act(self.conv1(x) + self.conv2(x) + id_out)
  106. def forward_fuse(self, x):
  107. """Forward process"""
  108. return self.act(self.conv(x))
  109. def get_equivalent_kernel_bias(self):
  110. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
  111. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
  112. kernelid, biasid = self._fuse_bn_tensor(self.bn)
  113. return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
  114. def _avg_to_3x3_tensor(self, avgp):
  115. channels = self.in_dim
  116. groups = self.g
  117. kernel_size = avgp.kernel_size
  118. input_dim = channels // groups
  119. k = torch.zeros((channels, input_dim, kernel_size, kernel_size))
  120. k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2
  121. return k
  122. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  123. if kernel1x1 is None:
  124. return 0
  125. else:
  126. return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  127. def _fuse_bn_tensor(self, branch):
  128. if branch is None:
  129. return 0, 0
  130. if isinstance(branch, BasicConv):
  131. kernel = branch.conv.weight
  132. running_mean = branch.norm.running_mean
  133. running_var = branch.norm.running_var
  134. gamma = branch.norm.weight
  135. beta = branch.norm.bias
  136. eps = branch.norm.eps
  137. elif isinstance(branch, nn.BatchNorm2d):
  138. if not hasattr(self, 'id_tensor'):
  139. input_dim = self.in_dim // self.g
  140. kernel_value = np.zeros((self.in_dim, input_dim, 3, 3), dtype=np.float32)
  141. for i in range(self.in_dim):
  142. kernel_value[i, i % input_dim, 1, 1] = 1
  143. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  144. kernel = self.id_tensor
  145. running_mean = branch.running_mean
  146. running_var = branch.running_var
  147. gamma = branch.weight
  148. beta = branch.bias
  149. eps = branch.eps
  150. std = (running_var + eps).sqrt()
  151. t = (gamma / std).reshape(-1, 1, 1, 1)
  152. return kernel * t, beta - running_mean * gamma / std
  153. def fuse_convs(self):
  154. if hasattr(self, 'conv'):
  155. return
  156. kernel, bias = self.get_equivalent_kernel_bias()
  157. self.conv = nn.Conv2d(in_channels = self.conv1.conv.in_channels,
  158. out_channels = self.conv1.conv.out_channels,
  159. kernel_size = self.conv1.conv.kernel_size,
  160. stride = self.conv1.conv.stride,
  161. padding = self.conv1.conv.padding,
  162. dilation = self.conv1.conv.dilation,
  163. groups = self.conv1.conv.groups,
  164. bias = True).requires_grad_(False)
  165. self.conv.weight.data = kernel
  166. self.conv.bias.data = bias
  167. for para in self.parameters():
  168. para.detach_()
  169. self.__delattr__('conv1')
  170. self.__delattr__('conv2')
  171. if hasattr(self, 'nm'):
  172. self.__delattr__('nm')
  173. if hasattr(self, 'bn'):
  174. self.__delattr__('bn')
  175. if hasattr(self, 'id_tensor'):
  176. self.__delattr__('id_tensor')
  177. class RepNBottleneck(nn.Module):
  178. def __init__(self,
  179. in_dim,
  180. out_dim,
  181. shortcut=True,
  182. kernel_size=(3, 3),
  183. expansion=0.5,
  184. act_type='silu',
  185. norm_type='BN',
  186. depthwise=False
  187. ):
  188. super().__init__()
  189. inter_dim = round(out_dim * expansion)
  190. self.conv_layer_1 = RepConvN(in_dim, inter_dim, kernel_size[0], p=kernel_size[0]//2, s=1, act_type=act_type, norm_type=norm_type)
  191. self.conv_layer_2 = BasicConv(inter_dim, out_dim, kernel_size[1], padding=kernel_size[1]//2, stride=1, act_type=act_type, norm_type=norm_type)
  192. self.add = shortcut and in_dim == out_dim
  193. def forward(self, x):
  194. h = self.conv_layer_2(self.conv_layer_1(x))
  195. return x + h if self.add else h
  196. class RepNCSP(nn.Module):
  197. def __init__(self,
  198. in_dim,
  199. out_dim,
  200. num_blocks=1,
  201. shortcut=True,
  202. expansion=0.5,
  203. act_type='silu',
  204. norm_type='BN',
  205. depthwise=False
  206. ):
  207. super().__init__()
  208. inter_dim = int(out_dim * expansion)
  209. self.conv_layer_1 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  210. self.conv_layer_2 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  211. self.conv_layer_3 = BasicConv(2 * inter_dim, out_dim, kernel_size=1)
  212. self.module = nn.Sequential(*(RepNBottleneck(inter_dim,
  213. inter_dim,
  214. kernel_size = [3, 3],
  215. shortcut = shortcut,
  216. expansion = 1.0,
  217. act_type = act_type,
  218. norm_type = norm_type,
  219. depthwise = depthwise)
  220. for _ in range(num_blocks)))
  221. def forward(self, x):
  222. x1 = self.conv_layer_1(x)
  223. x2 = self.module(self.conv_layer_2(x))
  224. return self.conv_layer_3(torch.cat([x1, x2], dim=1))
  225. class RepGElanLayer(nn.Module):
  226. """YOLOv9's GELAN module"""
  227. def __init__(self,
  228. in_dim :int,
  229. inter_dims :List,
  230. out_dim :int,
  231. num_blocks :int = 1,
  232. shortcut :bool = False,
  233. act_type :str = 'silu',
  234. norm_type :str = 'BN',
  235. depthwise :bool = False,
  236. ) -> None:
  237. super(RepGElanLayer, self).__init__()
  238. # ----------- Basic parameters -----------
  239. self.in_dim = in_dim
  240. self.inter_dims = inter_dims
  241. self.out_dim = out_dim
  242. # ----------- Network parameters -----------
  243. self.conv_layer_1 = BasicConv(in_dim, inter_dims[0], kernel_size=1, act_type=act_type, norm_type=norm_type)
  244. self.elan_module_1 = nn.Sequential(
  245. RepNCSP(inter_dims[0]//2,
  246. inter_dims[1],
  247. num_blocks = num_blocks,
  248. shortcut = shortcut,
  249. expansion = 0.5,
  250. act_type = act_type,
  251. norm_type = norm_type,
  252. depthwise = depthwise),
  253. BasicConv(inter_dims[1], inter_dims[1],
  254. kernel_size=3, padding=1,
  255. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  256. )
  257. self.elan_module_2 = nn.Sequential(
  258. RepNCSP(inter_dims[1],
  259. inter_dims[1],
  260. num_blocks = num_blocks,
  261. shortcut = shortcut,
  262. expansion = 0.5,
  263. act_type = act_type,
  264. norm_type = norm_type,
  265. depthwise = depthwise),
  266. BasicConv(inter_dims[1], inter_dims[1],
  267. kernel_size=3, padding=1,
  268. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  269. )
  270. self.conv_layer_2 = BasicConv(inter_dims[0] + 2*self.inter_dims[1], out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  271. def forward(self, x):
  272. # Input proj
  273. x1, x2 = torch.chunk(self.conv_layer_1(x), 2, dim=1)
  274. out = list([x1, x2])
  275. # ELAN module
  276. out.append(self.elan_module_1(out[-1]))
  277. out.append(self.elan_module_2(out[-1]))
  278. # Output proj
  279. out = self.conv_layer_2(torch.cat(out, dim=1))
  280. return out