rtcdet_v2_basic.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # ---------------------------- Base Conv Module ----------------------------
  5. class SiLU(nn.Module):
  6. """export-friendly version of nn.SiLU()"""
  7. @staticmethod
  8. def forward(x):
  9. return x * torch.sigmoid(x)
  10. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  11. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  12. return conv
  13. def get_activation(act_type=None):
  14. if act_type == 'relu':
  15. return nn.ReLU(inplace=True)
  16. elif act_type == 'lrelu':
  17. return nn.LeakyReLU(0.1, inplace=True)
  18. elif act_type == 'mish':
  19. return nn.Mish(inplace=True)
  20. elif act_type == 'silu':
  21. return nn.SiLU(inplace=True)
  22. elif act_type is None:
  23. return nn.Identity()
  24. def get_norm(norm_type, dim):
  25. if norm_type == 'BN':
  26. return nn.BatchNorm2d(dim)
  27. elif norm_type == 'GN':
  28. return nn.GroupNorm(num_groups=32, num_channels=dim)
  29. ## Basic Conv Module
  30. class Conv(nn.Module):
  31. def __init__(self,
  32. c1, # in channels
  33. c2, # out channels
  34. k=1, # kernel size
  35. p=0, # padding
  36. s=1, # padding
  37. d=1, # dilation
  38. act_type='lrelu', # activation
  39. norm_type='BN', # normalization
  40. depthwise=False):
  41. super(Conv, self).__init__()
  42. convs = []
  43. add_bias = False if norm_type else True
  44. p = p if d == 1 else d
  45. if depthwise:
  46. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  47. # depthwise conv
  48. if norm_type is not None:
  49. convs.append(get_norm(norm_type, c1))
  50. if act_type is not None:
  51. convs.append(get_activation(act_type))
  52. # pointwise conv
  53. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  54. if norm_type is not None:
  55. convs.append(get_norm(norm_type, c2))
  56. if act_type is not None:
  57. convs.append(get_activation(act_type))
  58. else:
  59. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  60. if norm_type is not None:
  61. convs.append(get_norm(norm_type, c2))
  62. if act_type is not None:
  63. convs.append(get_activation(act_type))
  64. self.convs = nn.Sequential(*convs)
  65. def forward(self, x):
  66. return self.convs(x)
  67. ## Partial Conv Module
  68. class PartialConv(nn.Module):
  69. def __init__(self, in_dim, out_dim, split_ratio=0.25, kernel_size=1, stride=1, act_type=None, norm_type=None):
  70. super().__init__()
  71. # ----------- Basic Parameters -----------
  72. assert in_dim == out_dim
  73. self.in_dim = in_dim
  74. self.out_dim = out_dim
  75. self.split_ratio = split_ratio
  76. self.split_dim = round(in_dim * split_ratio)
  77. self.untouched_dim = in_dim - self.split_dim
  78. self.kernel_size = kernel_size
  79. self.padding = kernel_size // 2
  80. self.stride = stride
  81. self.act_type = act_type
  82. self.norm_type = norm_type
  83. # ----------- Network Parameters -----------
  84. self.partial_conv = Conv(self.split_dim, self.split_dim, self.kernel_size, self.padding, self.stride, act_type=act_type, norm_type=norm_type)
  85. def forward(self, x):
  86. x1, x2 = torch.split(x, [self.split_dim, self.untouched_dim], dim=1)
  87. x1 = self.partial_conv(x1)
  88. x = torch.cat((x1, x2), 1)
  89. return x
  90. ## Channel Shuffle
  91. class ChannelShuffle(nn.Module):
  92. def __init__(self, groups=1) -> None:
  93. super().__init__()
  94. self.groups = groups
  95. def forward(self, x):
  96. # type: (torch.Tensor, int) -> torch.Tensor
  97. batchsize, num_channels, height, width = x.data.size()
  98. channels_per_group = num_channels // self.groups
  99. # reshape
  100. x = x.view(batchsize, self.groups,
  101. channels_per_group, height, width)
  102. x = torch.transpose(x, 1, 2).contiguous()
  103. # flatten
  104. x = x.view(batchsize, -1, height, width)
  105. return x
  106. ## Inverse BottleNeck
  107. class InverseBottleneck(nn.Module):
  108. def __init__(self,
  109. in_dim,
  110. out_dim,
  111. expand_ratio=2.0,
  112. shortcut=False,
  113. act_type='silu',
  114. norm_type='BN',
  115. depthwise=False):
  116. super(InverseBottleneck, self).__init__()
  117. # ----------- Basic Parameters -----------
  118. self.in_dim = in_dim
  119. self.out_dim = out_dim
  120. self.expand_dim = int(in_dim * expand_ratio)
  121. # ----------- Network Parameters -----------
  122. self.cv1 = Conv(in_dim, in_dim, k=3, p=1, act_type=None, norm_type=norm_type, depthwise=depthwise)
  123. self.cv2 = Conv(in_dim, self.expand_dim, k=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  124. self.cv3 = Conv(self.expand_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  125. self.shortcut = shortcut and in_dim == out_dim
  126. def forward(self, x):
  127. h = self.cv3(self.cv2(self.cv1(x)))
  128. return x + h if self.shortcut else h
  129. ## YOLO-style BottleNeck
  130. class YoloBottleneck(nn.Module):
  131. def __init__(self,
  132. in_dim,
  133. out_dim,
  134. expand_ratio=0.5,
  135. shortcut=False,
  136. act_type='silu',
  137. norm_type='BN',
  138. depthwise=False):
  139. super(YoloBottleneck, self).__init__()
  140. # ------------------ Basic parameters ------------------
  141. self.in_dim = in_dim
  142. self.out_dim = out_dim
  143. self.inter_dim = int(out_dim * expand_ratio)
  144. self.shortcut = shortcut and in_dim == out_dim
  145. # ------------------ Network parameters ------------------
  146. self.cv1 = Conv(in_dim, self.inter_dim, k=1, norm_type=norm_type, act_type=act_type)
  147. self.cv2 = Conv(self.inter_dim, out_dim, k=3, p=1, norm_type=norm_type, act_type=act_type, depthwise=depthwise)
  148. def forward(self, x):
  149. h = self.cv2(self.cv1(x))
  150. return x + h if self.shortcut else h
  151. # ---------------------------- Base Modules ----------------------------
  152. ## ELAN Stage of Backbone
  153. class ELAN_Stage(nn.Module):
  154. def __init__(self, in_dim, out_dim, squeeze_ratio :float=0.5, branch_depth :int=1, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  155. super().__init__()
  156. # ----------- Basic Parameters -----------
  157. self.in_dim = in_dim
  158. self.out_dim = out_dim
  159. self.inter_dim = round(in_dim * squeeze_ratio)
  160. self.squeeze_ratio = squeeze_ratio
  161. self.branch_depth = branch_depth
  162. # ----------- Network Parameters -----------
  163. self.cv1 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  164. self.cv2 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  165. self.cv3 = nn.Sequential(*[
  166. YoloBottleneck(self.inter_dim, self.inter_dim, 1.0, shortcut, act_type, norm_type, depthwise)
  167. for _ in range(branch_depth)
  168. ])
  169. self.cv4 = nn.Sequential(*[
  170. YoloBottleneck(self.inter_dim, self.inter_dim, 1.0, shortcut, act_type, norm_type, depthwise)
  171. for _ in range(branch_depth)
  172. ])
  173. ## output
  174. self.out_conv = Conv(self.inter_dim*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  175. def forward(self, x):
  176. x1 = self.cv1(x)
  177. x2 = self.cv2(x)
  178. x3 = self.cv3(x2)
  179. x4 = self.cv4(x3)
  180. out = self.out_conv(torch.cat([x1, x2, x3, x4], dim=1))
  181. return out
  182. ## DownSample Block
  183. class DSBlock(nn.Module):
  184. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  185. super().__init__()
  186. self.in_dim = in_dim
  187. self.out_dim = out_dim
  188. self.inter_dim = out_dim // 2
  189. # branch-1
  190. self.maxpool = nn.Sequential(
  191. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  192. nn.MaxPool2d((2, 2), 2)
  193. )
  194. # branch-2
  195. self.ds_conv = nn.Sequential(
  196. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  197. Conv(self.inter_dim, self.inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  198. )
  199. def forward(self, x):
  200. # branch-1
  201. x1 = self.maxpool(x)
  202. # branch-2
  203. x2 = self.ds_conv(x)
  204. # out-proj
  205. out = torch.cat([x1, x2], dim=1)
  206. return out
  207. # ---------------------------- FPN Modules ----------------------------
  208. ## build fpn's core block
  209. def build_fpn_block(cfg, in_dim, out_dim):
  210. if cfg['fpn_core_block'] == 'elan_block':
  211. layer = ELAN_Stage(in_dim = in_dim,
  212. out_dim = out_dim,
  213. squeeze_ratio = cfg['fpn_squeeze_ratio'],
  214. branch_depth = round(3 * cfg['depth']),
  215. shortcut = False,
  216. act_type = cfg['fpn_act'],
  217. norm_type = cfg['fpn_norm'],
  218. depthwise = cfg['fpn_depthwise']
  219. )
  220. return layer
  221. ## build fpn's reduce layer
  222. def build_reduce_layer(cfg, in_dim, out_dim):
  223. if cfg['fpn_reduce_layer'] == 'conv':
  224. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  225. return layer
  226. ## build fpn's downsample layer
  227. def build_downsample_layer(cfg, in_dim, out_dim):
  228. if cfg['fpn_downsample_layer'] == 'conv':
  229. layer = Conv(in_dim, out_dim, k=3, s=2, p=1,
  230. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  231. elif cfg['fpn_downsample_layer'] == 'maxpool':
  232. assert in_dim == out_dim
  233. layer = nn.MaxPool2d((2, 2), stride=2)
  234. return layer