rtcdet_v2_basic.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. # ---------------------------- Base Modules ----------------------------
  130. ## ELAN Block
  131. class ELANBlock(nn.Module):
  132. def __init__(self, in_dim, out_dim, squeeze_ratio=0.25, act_type='silu', norm_type='BN', depthwise=False):
  133. super().__init__()
  134. # ----------- Basic Parameters -----------
  135. self.in_dim = in_dim
  136. self.out_dim = out_dim
  137. self.inter_dim = round(in_dim * squeeze_ratio)
  138. # ----------- Network Parameters -----------
  139. self.cv1 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  140. self.cv2 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  141. self.cv3 = InverseBottleneck(self.inter_dim, self.inter_dim, expand_ratio=2, shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  142. self.cv4 = InverseBottleneck(self.inter_dim, self.inter_dim, expand_ratio=2, shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  143. # output
  144. self.out_conv = Conv(self.inter_dim*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  145. def forward(self, x):
  146. x1 = self.cv1(x)
  147. x2 = self.cv2(x)
  148. x3 = self.cv3(x2)
  149. x4 = self.cv4(x3)
  150. out = self.out_conv(torch.cat([x1, x2, x3, x4], dim=1))
  151. return out
  152. ## ELAN Stage
  153. class ELANStage(nn.Module):
  154. def __init__(self, in_dim, out_dim, num_blocks=1, squeeze_ratio=0.25, 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.num_blocks = num_blocks
  160. self.inter_dim = in_dim // 2
  161. # -------------- Network parameters --------------
  162. self.stage_blocks = nn.Sequential()
  163. for i in range(self.num_blocks):
  164. if i == 0:
  165. self.stage_blocks.append(ELANBlock(in_dim, out_dim, squeeze_ratio, act_type, norm_type, depthwise))
  166. else:
  167. self.stage_blocks.append(ELANBlock(out_dim, out_dim, squeeze_ratio, act_type, norm_type, depthwise))
  168. def forward(self, x):
  169. return self.stage_blocks(x)
  170. ## DownSample Block
  171. class DSBlock(nn.Module):
  172. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  173. super().__init__()
  174. self.in_dim = in_dim
  175. self.out_dim = out_dim
  176. self.inter_dim = out_dim // 2
  177. # branch-1
  178. self.maxpool = nn.Sequential(
  179. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  180. nn.MaxPool2d((2, 2), 2)
  181. )
  182. # branch-2
  183. self.ds_conv = nn.Sequential(
  184. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  185. Conv(self.inter_dim, self.inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  186. )
  187. def forward(self, x):
  188. # branch-1
  189. x1 = self.maxpool(x)
  190. # branch-2
  191. x2 = self.ds_conv(x)
  192. # out-proj
  193. out = torch.cat([x1, x2], dim=1)
  194. return out
  195. # ---------------------------- FPN Modules ----------------------------
  196. ## build fpn's core block
  197. def build_fpn_block(cfg, in_dim, out_dim):
  198. if cfg['fpn_core_block'] == 'elan_block':
  199. layer = ELANStage(in_dim = in_dim,
  200. out_dim = out_dim,
  201. num_blocks = round(3 * cfg['depth']),
  202. squeeze_ratio = cfg['fpn_squeeze_ratio'],
  203. act_type = cfg['fpn_act'],
  204. norm_type = cfg['fpn_norm'],
  205. depthwise = cfg['fpn_depthwise']
  206. )
  207. return layer
  208. ## build fpn's reduce layer
  209. def build_reduce_layer(cfg, in_dim, out_dim):
  210. if cfg['fpn_reduce_layer'] == 'conv':
  211. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  212. return layer
  213. ## build fpn's downsample layer
  214. def build_downsample_layer(cfg, in_dim, out_dim):
  215. if cfg['fpn_downsample_layer'] == 'conv':
  216. layer = Conv(in_dim, out_dim, k=3, s=2, p=1,
  217. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  218. elif cfg['fpn_downsample_layer'] == 'maxpool':
  219. assert in_dim == out_dim
  220. layer = nn.MaxPool2d((2, 2), stride=2)
  221. elif cfg['fpn_downsample_layer'] == 'dsblock':
  222. layer = DSBlock(in_dim, out_dim, cfg['fpn_act'], cfg['fpn_norm'], cfg['fpn_depthwise'])
  223. return layer