rtcdet_basic.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import torch
  2. import torch.nn as nn
  3. from typing import List
  4. # --------------------- Basic modules ---------------------
  5. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  6. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  7. return conv
  8. def get_activation(act_type=None):
  9. if act_type == 'relu':
  10. return nn.ReLU(inplace=True)
  11. elif act_type == 'lrelu':
  12. return nn.LeakyReLU(0.1, inplace=True)
  13. elif act_type == 'mish':
  14. return nn.Mish(inplace=True)
  15. elif act_type == 'silu':
  16. return nn.SiLU(inplace=True)
  17. elif act_type is None:
  18. return nn.Identity()
  19. else:
  20. raise NotImplementedError
  21. def get_norm(norm_type, dim):
  22. if norm_type == 'BN':
  23. return nn.BatchNorm2d(dim)
  24. elif norm_type == 'GN':
  25. return nn.GroupNorm(num_groups=32, num_channels=dim)
  26. elif norm_type is None:
  27. return nn.Identity()
  28. else:
  29. raise NotImplementedError
  30. class BasicConv(nn.Module):
  31. def __init__(self,
  32. in_dim, # in channels
  33. out_dim, # out channels
  34. kernel_size=1, # kernel size
  35. padding=0, # padding
  36. stride=1, # padding
  37. dilation=1, # dilation
  38. act_type :str = 'lrelu', # activation
  39. norm_type :str = 'BN', # normalization
  40. depthwise :bool = False
  41. ):
  42. super(BasicConv, self).__init__()
  43. self.depthwise = depthwise
  44. if not depthwise:
  45. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1)
  46. self.norm = get_norm(norm_type, out_dim)
  47. else:
  48. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim)
  49. self.norm1 = get_norm(norm_type, in_dim)
  50. self.conv2 = get_conv2d(in_dim, out_dim, k=1, p=0, s=1, d=1, g=1)
  51. self.norm2 = get_norm(norm_type, out_dim)
  52. self.act = get_activation(act_type)
  53. def forward(self, x):
  54. if not self.depthwise:
  55. return self.act(self.norm(self.conv(x)))
  56. else:
  57. # Depthwise conv
  58. x = self.norm1(self.conv1(x))
  59. # Pointwise conv
  60. x = self.norm2(self.conv2(x))
  61. return x
  62. # --------------------- Yolov8 modules ---------------------
  63. class MDown(nn.Module):
  64. def __init__(self,
  65. in_dim :int,
  66. out_dim :int,
  67. act_type :str = 'silu',
  68. norm_type :str = 'BN',
  69. depthwise :bool = False,
  70. ) -> None:
  71. super().__init__()
  72. inter_dim = out_dim // 2
  73. self.downsample_1 = nn.Sequential(
  74. nn.MaxPool2d((2, 2), stride=2),
  75. BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  76. )
  77. self.downsample_2 = nn.Sequential(
  78. BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type),
  79. BasicConv(inter_dim, inter_dim,
  80. kernel_size=3, padding=1, stride=2,
  81. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  82. )
  83. if in_dim == out_dim:
  84. self.output_proj = nn.Identity()
  85. else:
  86. self.output_proj = BasicConv(inter_dim * 2, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  87. def forward(self, x):
  88. x1 = self.downsample_1(x)
  89. x2 = self.downsample_2(x)
  90. out = self.output_proj(torch.cat([x1, x2], dim=1))
  91. return out
  92. class Bottleneck(nn.Module):
  93. def __init__(self,
  94. in_dim :int,
  95. out_dim :int,
  96. kernel_size :List = [1, 3],
  97. expansion :float = 0.5,
  98. shortcut :bool = False,
  99. act_type :str = 'silu',
  100. norm_type :str = 'BN',
  101. depthwise :bool = False,
  102. ) -> None:
  103. super(Bottleneck, self).__init__()
  104. inter_dim = int(out_dim * expansion)
  105. # ----------------- Network setting -----------------
  106. self.conv_layer1 = BasicConv(in_dim, inter_dim,
  107. kernel_size=kernel_size[0], padding=kernel_size[0]//2, stride=1,
  108. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  109. self.conv_layer2 = BasicConv(inter_dim, out_dim,
  110. kernel_size=kernel_size[1], padding=kernel_size[1]//2, stride=1,
  111. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  112. self.shortcut = shortcut and in_dim == out_dim
  113. def forward(self, x):
  114. h = self.conv_layer2(self.conv_layer1(x))
  115. return x + h if self.shortcut else h
  116. class ELANLayer(nn.Module):
  117. def __init__(self,
  118. in_dim,
  119. out_dim,
  120. expansion :float = 0.5,
  121. num_blocks :int = 1,
  122. shortcut :bool = False,
  123. act_type :str = 'silu',
  124. norm_type :str = 'BN',
  125. depthwise :bool = False,
  126. ) -> None:
  127. super(ELANLayer, self).__init__()
  128. inter_dim = round(out_dim * expansion)
  129. self.input_proj = BasicConv(in_dim, inter_dim * 2, kernel_size=1, act_type=act_type, norm_type=norm_type)
  130. self.output_proj = BasicConv((2 + num_blocks) * inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  131. self.module = nn.ModuleList([Bottleneck(inter_dim,
  132. inter_dim,
  133. kernel_size = [3, 3],
  134. expansion = 1.0,
  135. shortcut = shortcut,
  136. act_type = act_type,
  137. norm_type = norm_type,
  138. depthwise = depthwise)
  139. for _ in range(num_blocks)])
  140. def forward(self, x):
  141. # Input proj
  142. x1, x2 = torch.chunk(self.input_proj(x), 2, dim=1)
  143. out = list([x1, x2])
  144. # Bottlenecl
  145. out.extend(m(out[-1]) for m in self.module)
  146. # Output proj
  147. out = self.output_proj(torch.cat(out, dim=1))
  148. return out
  149. class ELANLayerFPN(nn.Module):
  150. def __init__(self,
  151. in_dim,
  152. out_dim,
  153. num_blocks :int = 1,
  154. expansion :float = 0.5,
  155. act_type :str = 'silu',
  156. norm_type :str = 'BN',
  157. depthwise :bool = False,
  158. ) -> None:
  159. super(ELANLayerFPN, self).__init__()
  160. inter_dim_1 = round(out_dim * expansion)
  161. inter_dim_2 = round(inter_dim_1* expansion)
  162. # Branch-1
  163. self.branch_1 = BasicConv(in_dim, inter_dim_1, kernel_size=1, act_type=act_type, norm_type=norm_type)
  164. # Branch-2
  165. self.branch_2 = BasicConv(in_dim, inter_dim_1, kernel_size=1, act_type=act_type, norm_type=norm_type)
  166. # Branch-3
  167. branch_3 = []
  168. for i in range(num_blocks):
  169. if i == 0:
  170. branch_3.append(BasicConv(inter_dim_1, inter_dim_2, kernel_size=3, padding=1,
  171. act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  172. else:
  173. branch_3.append(BasicConv(inter_dim_2, inter_dim_2, kernel_size=3, padding=1,
  174. act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  175. self.branch_3 = nn.Sequential(*branch_3)
  176. # Branch-4
  177. self.branch_4 = nn.Sequential(*[BasicConv(inter_dim_2, inter_dim_2, kernel_size=3, padding=1,
  178. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  179. for _ in range(num_blocks)])
  180. # Branch-5
  181. self.branch_5 = nn.Sequential(*[BasicConv(inter_dim_2, inter_dim_2, kernel_size=3, padding=1,
  182. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  183. for _ in range(num_blocks)])
  184. # Branch-6
  185. self.branch_6 = nn.Sequential(*[BasicConv(inter_dim_2, inter_dim_2, kernel_size=3, padding=1,
  186. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  187. for _ in range(num_blocks)])
  188. self.output_proj = BasicConv(2*inter_dim_1 + 4*inter_dim_2, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  189. def forward(self, x):
  190. # Elan
  191. x1 = self.branch_1(x)
  192. x2 = self.branch_2(x)
  193. x3 = self.branch_3(x2)
  194. x4 = self.branch_4(x3)
  195. x5 = self.branch_5(x4)
  196. x6 = self.branch_6(x5)
  197. # Output proj
  198. out = list([x1, x2, x3, x4, x5, x6])
  199. out = self.output_proj(torch.cat(out, dim=1))
  200. return out