rtmdet_v2_basic.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. class Conv(nn.Module):
  30. def __init__(self,
  31. c1, # in channels
  32. c2, # out channels
  33. k=1, # kernel size
  34. p=0, # padding
  35. s=1, # padding
  36. d=1, # dilation
  37. act_type='lrelu', # activation
  38. norm_type='BN', # normalization
  39. depthwise=False):
  40. super(Conv, self).__init__()
  41. convs = []
  42. add_bias = False if norm_type else True
  43. p = p if d == 1 else d
  44. if depthwise:
  45. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  46. # depthwise conv
  47. if norm_type:
  48. convs.append(get_norm(norm_type, c1))
  49. if act_type:
  50. convs.append(get_activation(act_type))
  51. # pointwise conv
  52. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  53. if norm_type:
  54. convs.append(get_norm(norm_type, c2))
  55. if act_type:
  56. convs.append(get_activation(act_type))
  57. else:
  58. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  59. if norm_type:
  60. convs.append(get_norm(norm_type, c2))
  61. if act_type:
  62. convs.append(get_activation(act_type))
  63. self.convs = nn.Sequential(*convs)
  64. def forward(self, x):
  65. return self.convs(x)
  66. # ---------------------------- Base Modules ----------------------------
  67. ## Multi-head Mixed Conv (MHMC)
  68. class MultiHeadMixedConv(nn.Module):
  69. def __init__(self, in_dim, out_dim, num_heads=4, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  70. super().__init__()
  71. # -------------- Basic parameters --------------
  72. self.in_dim = in_dim
  73. self.out_dim = out_dim
  74. self.num_heads = num_heads
  75. self.shortcut = shortcut
  76. self.head_dim = in_dim // num_heads
  77. # -------------- Network parameters --------------
  78. ## Scale Modulation
  79. self.mixed_convs = nn.ModuleList()
  80. for i in range(num_heads):
  81. self.mixed_convs.append(
  82. Conv(self.head_dim, self.head_dim, k=2*i+1, p=i, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  83. )
  84. ## Out-proj
  85. self.out_proj = Conv(in_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  86. def forward(self, x):
  87. xs = torch.chunk(x, self.num_heads, dim=1)
  88. ys = [mixed_conv(x_h) for x_h, mixed_conv in zip(xs, self.mixed_convs)]
  89. out = self.out_proj(torch.cat(ys, dim=1))
  90. return out + x if self.shortcut else out
  91. # ---------------------------- Base Blocks ----------------------------
  92. ## Mixed Convolution Block
  93. class MCBlock(nn.Module):
  94. def __init__(self, in_dim, out_dim, nblocks=1, num_heads=4, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  95. super().__init__()
  96. # -------------- Basic parameters --------------
  97. self.in_dim = in_dim
  98. self.out_dim = out_dim
  99. self.nblocks = nblocks
  100. self.num_heads = num_heads
  101. self.shortcut = shortcut
  102. self.inter_dim = in_dim // 2
  103. # -------------- Network parameters --------------
  104. ## branch-1
  105. self.cv1 = Conv(self.in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  106. self.cv2 = Conv(self.in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  107. ## branch-2
  108. self.smblocks = nn.Sequential(*[
  109. MultiHeadMixedConv(self.inter_dim, self.inter_dim, self.num_heads, self.shortcut, act_type, norm_type, depthwise)
  110. for _ in range(nblocks)])
  111. ## out proj
  112. self.out_proj = Conv(self.inter_dim*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  113. def forward(self, x):
  114. # branch-1
  115. x1 = self.cv1(x)
  116. # branch-2
  117. x2 = self.smblocks(self.cv2(x))
  118. # output
  119. out = torch.cat([x1, x2], dim=1)
  120. out = self.out_proj(out)
  121. return out
  122. ## DownSample Block
  123. class DSBlock(nn.Module):
  124. def __init__(self, in_dim, out_dim, num_heads=4, act_type='silu', norm_type='BN', depthwise=False):
  125. super().__init__()
  126. self.in_dim = in_dim
  127. self.out_dim = out_dim
  128. self.inter_dim = out_dim // 2
  129. self.num_heads = num_heads
  130. # branch-1
  131. self.maxpool = nn.Sequential(
  132. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  133. nn.MaxPool2d((2, 2), 2)
  134. )
  135. # branch-2
  136. self.ds_conv = nn.Sequential(
  137. Conv(in_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  138. Conv(self.inter_dim, self.inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  139. )
  140. def forward(self, x):
  141. # branch-1
  142. x1 = self.maxpool(x)
  143. # branch-2
  144. x2 = self.ds_conv(x)
  145. # out-proj
  146. out = torch.cat([x1, x2], dim=1)
  147. return out
  148. # ---------------------------- FPN Modules ----------------------------
  149. ## build fpn's core block
  150. def build_fpn_block(cfg, in_dim, out_dim):
  151. if cfg['fpn_core_block'] == 'mcblock':
  152. layer = MCBlock(in_dim=in_dim,
  153. out_dim=out_dim,
  154. nblocks=round(cfg['depth'] * 3),
  155. num_heads=cfg['fpn_num_heads'],
  156. shortcut=False,
  157. act_type=cfg['fpn_act'],
  158. norm_type=cfg['fpn_norm'],
  159. depthwise=cfg['fpn_depthwise']
  160. )
  161. return layer
  162. ## build fpn's reduce layer
  163. def build_reduce_layer(cfg, in_dim, out_dim):
  164. if cfg['fpn_reduce_layer'] == 'conv':
  165. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  166. return layer
  167. ## build fpn's downsample layer
  168. def build_downsample_layer(cfg, in_dim, out_dim):
  169. if cfg['fpn_downsample_layer'] == 'conv':
  170. layer = Conv(in_dim, out_dim, k=3, s=2, p=1,
  171. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  172. elif cfg['fpn_downsample_layer'] == 'maxpool':
  173. assert in_dim == out_dim
  174. layer = nn.MaxPool2d((2, 2), stride=2)
  175. elif cfg['fpn_downsample_layer'] == 'dsblock':
  176. layer = DSBlock(in_dim, out_dim, num_heads=cfg['fpn_num_heads'],
  177. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  178. return layer