rtcdet_basic.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. # ---------------------------- Modified YOLOv7's Modules ----------------------------
  68. ## ELANBlock for Backbone
  69. class ELANBlock(nn.Module):
  70. def __init__(self, in_dim, out_dim, expand_ratio=0.5, depth=1.0, act_type='silu', norm_type='BN', depthwise=False):
  71. super(ELANBlock, self).__init__()
  72. if isinstance(expand_ratio, float):
  73. inter_dim = int(in_dim * expand_ratio)
  74. inter_dim2 = inter_dim
  75. elif isinstance(expand_ratio, list):
  76. assert len(expand_ratio) == 2
  77. e1, e2 = expand_ratio
  78. inter_dim = int(in_dim * e1)
  79. inter_dim2 = int(inter_dim * e2)
  80. # branch-1
  81. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  82. # branch-2
  83. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  84. # branch-3
  85. for idx in range(round(3*depth)):
  86. if idx == 0:
  87. cv3 = [Conv(inter_dim, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  88. else:
  89. cv3.append(Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  90. self.cv3 = nn.Sequential(*cv3)
  91. # branch-4
  92. self.cv4 = nn.Sequential(*[
  93. Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  94. for _ in range(round(3*depth))
  95. ])
  96. # output
  97. self.out = Conv(inter_dim*2 + inter_dim2*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  98. def forward(self, x):
  99. """
  100. Input:
  101. x: [B, C_in, H, W]
  102. Output:
  103. out: [B, C_out, H, W]
  104. """
  105. x1 = self.cv1(x)
  106. x2 = self.cv2(x)
  107. x3 = self.cv3(x2)
  108. x4 = self.cv4(x3)
  109. # [B, C, H, W] -> [B, 2C, H, W]
  110. out = self.out(torch.cat([x1, x2, x3, x4], dim=1))
  111. return out
  112. ## ELAN Block for FPN
  113. class ELANBlockFPN(nn.Module):
  114. def __init__(self, in_dim, out_dim, expand_ratio :float=0.5, branch_depth :int=1, shortcut=False, act_type='silu', norm_type='BN', depthwise=False):
  115. super().__init__()
  116. # ----------- Basic Parameters -----------
  117. self.in_dim = in_dim
  118. self.out_dim = out_dim
  119. self.inter_dim1 = round(out_dim * expand_ratio)
  120. self.inter_dim2 = round(self.inter_dim1 * expand_ratio)
  121. self.expand_ratio = expand_ratio
  122. self.branch_depth = branch_depth
  123. self.shortcut = shortcut
  124. # ----------- Network Parameters -----------
  125. ## branch-1
  126. self.cv1 = Conv(in_dim, self.inter_dim1, k=1, act_type=act_type, norm_type=norm_type)
  127. ## branch-2
  128. self.cv2 = Conv(in_dim, self.inter_dim1, k=1, act_type=act_type, norm_type=norm_type)
  129. ## branch-3
  130. self.cv3 = []
  131. for i in range(branch_depth):
  132. if i == 0:
  133. self.cv3.append(Conv(self.inter_dim1, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  134. else:
  135. self.cv3.append(Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  136. self.cv3 = nn.Sequential(*self.cv3)
  137. ## branch-4
  138. self.cv4 = nn.Sequential(*[
  139. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  140. for _ in range(branch_depth)
  141. ])
  142. ## branch-5
  143. self.cv5 = nn.Sequential(*[
  144. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  145. for _ in range(branch_depth)
  146. ])
  147. ## branch-6
  148. self.cv6 = nn.Sequential(*[
  149. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  150. for _ in range(branch_depth)
  151. ])
  152. ## output proj
  153. self.out = Conv(self.inter_dim1*2 + self.inter_dim2*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  154. def forward(self, x):
  155. x1 = self.cv1(x)
  156. x2 = self.cv2(x)
  157. x3 = self.cv3(x2)
  158. x4 = self.cv4(x3)
  159. x5 = self.cv5(x4)
  160. x6 = self.cv6(x5)
  161. # [B, C, H, W] -> [B, 2C, H, W]
  162. out = self.out(torch.cat([x1, x2, x3, x4, x5, x6], dim=1))
  163. return out
  164. ## DownSample
  165. class DSBlock(nn.Module):
  166. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  167. super().__init__()
  168. inter_dim = out_dim // 2
  169. self.mp = nn.MaxPool2d((2, 2), 2)
  170. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  171. self.cv2 = nn.Sequential(
  172. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  173. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  174. )
  175. def forward(self, x):
  176. x1 = self.cv1(self.mp(x))
  177. x2 = self.cv2(x)
  178. out = torch.cat([x1, x2], dim=1)
  179. return out
  180. # ---------------------------- FPN Modules ----------------------------
  181. ## build fpn's core block
  182. def build_fpn_block(cfg, in_dim, out_dim):
  183. if cfg['fpn_core_block'] == 'elanblock':
  184. layer = ELANBlockFPN(in_dim = in_dim,
  185. out_dim = out_dim,
  186. expand_ratio = cfg['fpn_expand_ratio'],
  187. branch_depth = round(3 * cfg['depth']),
  188. shortcut = False,
  189. act_type = cfg['fpn_act'],
  190. norm_type = cfg['fpn_norm'],
  191. depthwise = cfg['fpn_depthwise']
  192. )
  193. return layer
  194. ## build fpn's reduce layer
  195. def build_reduce_layer(cfg, in_dim, out_dim):
  196. if cfg['fpn_reduce_layer'] == 'conv':
  197. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  198. return layer
  199. ## build fpn's downsample layer
  200. def build_downsample_layer(cfg, in_dim, out_dim):
  201. if cfg['fpn_downsample_layer'] == 'conv':
  202. layer = Conv(in_dim, out_dim, k=3, s=2, p=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  203. elif cfg['fpn_downsample_layer'] == 'dsblock':
  204. layer = DSBlock(in_dim, out_dim, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  205. return layer