rtcdet_v2_basic.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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:
  49. convs.append(get_norm(norm_type, c1))
  50. if act_type:
  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:
  55. convs.append(get_norm(norm_type, c2))
  56. if act_type:
  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:
  61. convs.append(get_norm(norm_type, c2))
  62. if act_type:
  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. # ---------------------------- Base Modules ----------------------------
  107. ## Faster Module
  108. class FasterModule(nn.Module):
  109. def __init__(self, in_dim, out_dim, split_ratio=0.25, kernel_size=3, shortcut=True, act_type='silu', norm_type='BN'):
  110. super().__init__()
  111. # ----------- Basic Parameters -----------
  112. self.in_dim = in_dim
  113. self.out_dim = out_dim
  114. self.split_ratio = split_ratio
  115. self.expand_dim = in_dim * 2
  116. self.shortcut = True if shortcut and in_dim == out_dim else False
  117. self.act_type = act_type
  118. self.norm_type = norm_type
  119. # ----------- Network Parameters -----------
  120. self.partial_conv = PartialConv(in_dim, in_dim, split_ratio, kernel_size, stride=1, act_type=None, norm_type=None)
  121. self.expand_layer = Conv(in_dim, self.expand_dim, k=1, act_type=act_type, norm_type=norm_type)
  122. self.project_layer = Conv(self.expand_dim, out_dim, k=1, act_type=None, norm_type=None)
  123. def forward(self, x):
  124. h = self.project_layer(self.expand_layer(self.partial_conv(x)))
  125. return x + h if self.shortcut else h
  126. ## CSP-style FasterBlock
  127. class CSPFasterStage(nn.Module):
  128. def __init__(self, in_dim, out_dim, num_blocks=1, kernel_size=3, shortcut=True, act_type='silu', norm_type='BN'):
  129. super().__init__()
  130. # -------------- Basic parameters --------------
  131. self.in_dim = in_dim
  132. self.out_dim = out_dim
  133. self.num_blocks = num_blocks
  134. self.inter_dim = in_dim // 2
  135. # -------------- Network parameters --------------
  136. self.cv1 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  137. self.cv2 = Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  138. self.blocks = nn.Sequential(*[
  139. FasterModule(self.inter_dim, self.inter_dim, 0.5, kernel_size, shortcut, act_type, norm_type)
  140. for _ in range(self.num_blocks)])
  141. self.out_proj = Conv(self.inter_dim*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  142. def forward(self, x):
  143. x1 = self.cv1(x)
  144. x2 = self.blocks(self.cv2(x))
  145. return self.out_proj(torch.cat([x1, x2], dim=1))
  146. ## DownSample Block
  147. class DSBlock(nn.Module):
  148. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  149. super().__init__()
  150. self.in_dim = in_dim
  151. self.out_dim = out_dim
  152. self.inter_dim = out_dim // 2
  153. # branch-1
  154. self.maxpool = nn.Sequential(
  155. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  156. nn.MaxPool2d((2, 2), 2)
  157. )
  158. # branch-2
  159. self.ds_conv = nn.Sequential(
  160. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  161. Conv(self.inter_dim, self.inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  162. )
  163. def forward(self, x):
  164. # branch-1
  165. x1 = self.maxpool(x)
  166. # branch-2
  167. x2 = self.ds_conv(x)
  168. # out-proj
  169. out = torch.cat([x1, x2], dim=1)
  170. return out
  171. # ---------------------------- FPN Modules ----------------------------
  172. ## build fpn's core block
  173. def build_fpn_block(cfg, in_dim, out_dim):
  174. if cfg['fpn_core_block'] == 'faster_block':
  175. layer = CSPFasterStage(in_dim = in_dim,
  176. out_dim = out_dim,
  177. num_blocks = round(3 * cfg['depth']),
  178. kernel_size = 3,
  179. shortcut = False,
  180. act_type = cfg['fpn_act'],
  181. norm_type = cfg['fpn_norm'],
  182. )
  183. return layer
  184. ## build fpn's reduce layer
  185. def build_reduce_layer(cfg, in_dim, out_dim):
  186. if cfg['fpn_reduce_layer'] == 'conv':
  187. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  188. return layer
  189. ## build fpn's downsample layer
  190. def build_downsample_layer(cfg, in_dim, out_dim):
  191. if cfg['fpn_downsample_layer'] == 'conv':
  192. layer = Conv(in_dim, out_dim, k=3, s=2, p=1,
  193. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  194. elif cfg['fpn_downsample_layer'] == 'maxpool':
  195. assert in_dim == out_dim
  196. layer = nn.MaxPool2d((2, 2), stride=2)
  197. elif cfg['fpn_downsample_layer'] == 'dsblock':
  198. layer = DSBlock(in_dim, out_dim, cfg['fpn_act'], cfg['fpn_norm'], cfg['fpn_depthwise'])
  199. return layer