rtcdet_v2_basic.py 8.1 KB

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