rtcdetv2_basic.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. elif norm_type is None:
  30. return nn.Identity()
  31. class Conv(nn.Module):
  32. def __init__(self,
  33. c1, # in channels
  34. c2, # out channels
  35. k=1, # kernel size
  36. p=0, # padding
  37. s=1, # padding
  38. d=1, # dilation
  39. act_type='lrelu', # activation
  40. norm_type='BN', # normalization
  41. depthwise=False):
  42. super(Conv, self).__init__()
  43. convs = []
  44. add_bias = False if norm_type else True
  45. p = p if d == 1 else d
  46. if depthwise:
  47. # Depthwise Conv
  48. assert c1 == c2
  49. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  50. # depthwise conv
  51. if norm_type:
  52. convs.append(get_norm(norm_type, c2))
  53. if act_type:
  54. convs.append(get_activation(act_type))
  55. else:
  56. # Naive Conv
  57. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  58. if norm_type:
  59. convs.append(get_norm(norm_type, c2))
  60. if act_type:
  61. convs.append(get_activation(act_type))
  62. self.convs = nn.Sequential(*convs)
  63. def forward(self, x):
  64. return self.convs(x)
  65. # ---------------------------- Modules ----------------------------
  66. ## Mixed ConvModule
  67. class MixedConvModule(nn.Module):
  68. def __init__(self,
  69. in_dim :int,
  70. out_dim :int,
  71. expand_ratio :float = 0.25,
  72. num_branches :int = 4,
  73. shortcut :bool = True,
  74. act_type :str = 'relu',
  75. norm_type :str = 'BN',
  76. depthwise :bool = False):
  77. super(MixedConvModule, self).__init__()
  78. # ----------- Basic Parameters -----------
  79. self.in_dim = in_dim
  80. self.out_dim = out_dim
  81. self.expand_ratio = expand_ratio
  82. self.num_branches = num_branches
  83. self.shortcut = shortcut
  84. self.inter_dim = round(in_dim * expand_ratio)
  85. # ----------- Network Parameters -----------
  86. self.input_proj = Conv(in_dim, self.inter_dim, k=1, act_type=None, norm_type=norm_type)
  87. self.branches = nn.ModuleList([
  88. Conv(self.inter_dim, self.inter_dim, k=3, p=1, s=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  89. for _ in range(num_branches)])
  90. self.output_proj = Conv(self.inter_dim * self.num_branches, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  91. def forward(self, x):
  92. y = self.input_proj(x)
  93. outs = []
  94. for layer in self.branches:
  95. y = layer(y)
  96. outs.append(y)
  97. outs = torch.cat(outs, dim=1)
  98. return x + self.output_proj(outs) if self.shortcut else self.output_proj(outs)
  99. ## Conv-style FFN
  100. class ConvFFN(nn.Module):
  101. def __init__(self,
  102. in_dim :int,
  103. out_dim :int,
  104. expand_ratio :float = 2.0,
  105. shortcut :bool = True,
  106. act_type :str = 'silu',
  107. norm_type :str = 'BN',
  108. depthwise :bool = False):
  109. super(ConvFFN, self).__init__()
  110. # ----------- Basic Parameters -----------
  111. self.in_dim = in_dim
  112. self.out_dim = out_dim
  113. self.shortcut = shortcut
  114. self.expand_dim = round(in_dim * expand_ratio)
  115. # ----------- Network Parameters -----------
  116. self.conv_ffn = nn.Sequential(
  117. Conv(in_dim, self.expand_dim, k=1, act_type=act_type, norm_type=norm_type),
  118. Conv(self.expand_dim, in_dim, k=1, act_type=None, norm_type=norm_type)
  119. )
  120. def forward(self, x):
  121. return x + self.conv_ffn(x) if self.shortcut else self.conv_ffn(x)
  122. ## ResBlock
  123. class ResXBlock(nn.Module):
  124. def __init__(self,
  125. in_dim :int,
  126. out_dim :int,
  127. expand_ratio :float = 0.25,
  128. ffn_ratio :float = 2.0,
  129. num_branches :int = 4,
  130. shortcut :bool = True,
  131. act_type :str ='silu',
  132. norm_type :str ='BN',
  133. depthwise :bool = False):
  134. super(ResXBlock, self).__init__()
  135. self.layer1 = MixedConvModule(in_dim, out_dim, expand_ratio, num_branches, shortcut, act_type, norm_type, depthwise)
  136. self.layer2 = ConvFFN(out_dim, out_dim, ffn_ratio, shortcut, act_type, norm_type, depthwise)
  137. def forward(self, x):
  138. x = self.layer1(x)
  139. x = self.layer2(x)
  140. return x
  141. ## ResXStage
  142. class ResXStage(nn.Module):
  143. def __init__(self,
  144. in_dim :int,
  145. out_dim :int,
  146. expand_ratio :float = 0.25,
  147. ffn_ratio :float = 2.0,
  148. num_branches :int = 4,
  149. num_blocks :int = 1,
  150. shortcut :bool = True,
  151. act_type :str ='silu',
  152. norm_type :str ='BN',
  153. depthwise :bool = False):
  154. super(ResXStage, self).__init__()
  155. stages = []
  156. for i in range(num_blocks):
  157. if i == 0:
  158. stages.append(ResXBlock(in_dim, out_dim, expand_ratio, ffn_ratio, num_branches, shortcut, act_type, norm_type, depthwise))
  159. else:
  160. stages.append(ResXBlock(out_dim, out_dim, expand_ratio, ffn_ratio, num_branches, shortcut, act_type, norm_type, depthwise))
  161. self.stages = nn.Sequential(*stages)
  162. def forward(self, x):
  163. return self.stages(x)