gelan_basic.py 13 KB

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