rtmdet_v2_basic.py 7.5 KB

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