lowdet_basic.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # ---------------------------- 2D CNN ----------------------------
  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 layer
  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. # ---------------------------- Core Modules ----------------------------
  68. ## MultiHeadMixedConv
  69. class MultiHeadMixedConv(nn.Module):
  70. def __init__(self, in_dim, out_dim, num_heads=4, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  71. super().__init__()
  72. # -------------- Basic parameters --------------
  73. self.in_dim = in_dim
  74. self.out_dim = out_dim
  75. self.num_heads = num_heads
  76. self.head_dim = in_dim // num_heads
  77. self.shortcut = shortcut
  78. # -------------- Network parameters --------------
  79. ## Scale Modulation
  80. self.mixed_convs = nn.ModuleList([
  81. Conv(self.head_dim, self.head_dim, k=2*i+1, p=i, act_type=None, norm_type=None, depthwise=depthwise)
  82. for i in range(1, num_heads+1)])
  83. ## Aggregation proj
  84. self.out_proj = Conv(self.head_dim*num_heads, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  85. def forward(self, x):
  86. xs = torch.chunk(x, self.num_heads, dim=1)
  87. ys = [mixed_conv(x_h) for x_h, mixed_conv in zip(xs, self.mixed_convs)]
  88. ys = self.out_proj(torch.cat(ys, dim=1))
  89. return x + ys if self.shortcut else ys
  90. ## Scale Modulation Block
  91. class SMBlock(nn.Module):
  92. def __init__(self, in_dim, out_dim, nblocks=1, num_heads=4, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  93. super().__init__()
  94. # -------------- Basic parameters --------------
  95. self.in_dim = in_dim
  96. self.out_dim = out_dim
  97. self.nblocks = nblocks
  98. self.num_heads = num_heads
  99. self.shortcut = shortcut
  100. self.inter_dim = in_dim // 2
  101. # -------------- Network parameters --------------
  102. self.cv1 = Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  103. self.cv2 = Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  104. ## Scale Modulation
  105. self.smblocks = nn.Sequential(*[
  106. MultiHeadMixedConv(self.inter_dim, self.inter_dim, self.num_heads, self.shortcut, act_type, norm_type, depthwise)
  107. for _ in range(nblocks)])
  108. ## Output proj
  109. self.out_proj = Conv(self.inter_dim*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  110. def forward(self, x):
  111. """
  112. Input:
  113. x: (Tensor) -> [B, C_in, H, W]
  114. Output:
  115. out: (Tensor) -> [B, C_out, H, W]
  116. """
  117. x1, x2 = torch.chunk(x, 2, dim=1)
  118. # branch-1
  119. x1 = self.cv1(x1)
  120. # branch-2
  121. x2 = self.smblocks(x2)
  122. # output
  123. out = torch.cat([x1, x2], dim=1)
  124. out = self.out_proj(out)
  125. return out
  126. ## DownSample Block
  127. class DSBlock(nn.Module):
  128. def __init__(self, in_dim, act_type='silu', norm_type='BN', depthwise=False):
  129. super().__init__()
  130. # branch-1
  131. self.maxpool = nn.MaxPool2d((2, 2), 2)
  132. # branch-2
  133. inter_dim = in_dim // 2
  134. self.sm1 = Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  135. self.sm2 = Conv(inter_dim, inter_dim, k=5, p=2, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  136. self.sm3 = Conv(inter_dim, inter_dim, k=7, p=3, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  137. def channel_shuffle(self, x, groups):
  138. # type: (torch.Tensor, int) -> torch.Tensor
  139. batchsize, num_channels, height, width = x.data.size()
  140. per_group_dim = num_channels // groups
  141. # reshape
  142. x = x.view(batchsize, groups, per_group_dim, height, width)
  143. x = torch.transpose(x, 1, 2).contiguous()
  144. # flatten
  145. x = x.view(batchsize, -1, height, width)
  146. return x
  147. def forward(self, x):
  148. """
  149. Input:
  150. x: (Tensor) -> [B, C, H, W]
  151. Output:
  152. out: (Tensor) -> [B, 2C, H/2, W/2]
  153. """
  154. x1, x2 = torch.chunk(x, 2, dim=1)
  155. # branch-1
  156. x1 = self.maxpool(x1)
  157. # branch-2
  158. x2 = torch.cat([self.sm1(x2), self.sm2(x2), self.sm3(x2)], dim=1)
  159. # channel shuffle
  160. out = torch.cat([x1, x2], dim=1)
  161. out = self.channel_shuffle(out, groups=4)
  162. return out
  163. # ---------------------------- FPN Modules ----------------------------
  164. ## build fpn's core block
  165. def build_fpn_block(cfg, in_dim, out_dim):
  166. if cfg['fpn_core_block'] == 'smblock':
  167. layer = SMBlock(in_dim=in_dim,
  168. out_dim=out_dim,
  169. nblocks=cfg['fpn_nblocks'],
  170. num_heads=cfg['fpn_num_heads'],
  171. shortcut=cfg['fpn_shortcut'],
  172. act_type=cfg['fpn_act'],
  173. norm_type=cfg['fpn_norm'],
  174. depthwise=cfg['fpn_depthwise']
  175. )
  176. return layer
  177. ## build fpn's reduce layer
  178. def build_reduce_layer(cfg, in_dim, out_dim):
  179. if cfg['fpn_reduce_layer'] == 'conv':
  180. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  181. return layer
  182. ## build fpn's downsample layer
  183. def build_downsample_layer(cfg, in_dim, out_dim):
  184. if cfg['fpn_downsample_layer'] == 'conv':
  185. layer = Conv(in_dim, out_dim, k=3, s=2, p=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  186. elif cfg['fpn_downsample_layer'] == 'maxpool':
  187. assert in_dim == out_dim
  188. layer = nn.MaxPool2d((2, 2), stride=2)
  189. return layer