rtrdet_basic.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import copy
  2. import torch
  3. import torch.nn as nn
  4. from typing import Optional
  5. from torch import Tensor
  6. # ---------------------------- Basic functions ----------------------------
  7. class SiLU(nn.Module):
  8. """export-friendly version of nn.SiLU()"""
  9. @staticmethod
  10. def forward(x):
  11. return x * torch.sigmoid(x)
  12. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  13. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  14. return conv
  15. def get_activation(act_type=None):
  16. if act_type == 'relu':
  17. return nn.ReLU(inplace=True)
  18. elif act_type == 'lrelu':
  19. return nn.LeakyReLU(0.1, inplace=True)
  20. elif act_type == 'mish':
  21. return nn.Mish(inplace=True)
  22. elif act_type == 'silu':
  23. return nn.SiLU(inplace=True)
  24. elif act_type is None:
  25. return nn.Identity()
  26. def get_norm(norm_type, dim):
  27. if norm_type == 'BN':
  28. return nn.BatchNorm2d(dim)
  29. elif norm_type == 'GN':
  30. return nn.GroupNorm(num_groups=32, num_channels=dim)
  31. def get_clones(module, N):
  32. return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
  33. # ---------------------------- 2D CNN ----------------------------
  34. class Conv(nn.Module):
  35. def __init__(self,
  36. c1, # in channels
  37. c2, # out channels
  38. k=1, # kernel size
  39. p=0, # padding
  40. s=1, # padding
  41. d=1, # dilation
  42. act_type='lrelu', # activation
  43. norm_type='BN', # normalization
  44. depthwise=False):
  45. super(Conv, self).__init__()
  46. convs = []
  47. add_bias = False if norm_type else True
  48. p = p if d == 1 else d
  49. if depthwise:
  50. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  51. # depthwise conv
  52. if norm_type:
  53. convs.append(get_norm(norm_type, c1))
  54. if act_type:
  55. convs.append(get_activation(act_type))
  56. # pointwise conv
  57. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, 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. else:
  63. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  64. if norm_type:
  65. convs.append(get_norm(norm_type, c2))
  66. if act_type:
  67. convs.append(get_activation(act_type))
  68. self.convs = nn.Sequential(*convs)
  69. def forward(self, x):
  70. return self.convs(x)
  71. # ------------------------------- MLP -------------------------------
  72. class MLP(nn.Module):
  73. """ Very simple multi-layer perceptron (also called FFN)"""
  74. def __init__(self, in_dim, hidden_dim, out_dim, num_layers):
  75. super().__init__()
  76. self.num_layers = num_layers
  77. h = [hidden_dim] * (num_layers - 1)
  78. self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([in_dim] + h, h + [out_dim]))
  79. def forward(self, x):
  80. for i, layer in enumerate(self.layers):
  81. x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
  82. return x
  83. class FFN(nn.Module):
  84. def __init__(self, d_model=256, mlp_ratio=4.0, dropout=0., act_type='relu'):
  85. super().__init__()
  86. self.fpn_dim = round(d_model * mlp_ratio)
  87. self.linear1 = nn.Linear(d_model, self.fpn_dim)
  88. self.activation = get_activation(act_type)
  89. self.dropout2 = nn.Dropout(dropout)
  90. self.linear2 = nn.Linear(self.fpn_dim, d_model)
  91. self.dropout3 = nn.Dropout(dropout)
  92. self.norm2 = nn.LayerNorm(d_model)
  93. def forward(self, src):
  94. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  95. src = src + self.dropout3(src2)
  96. src = self.norm2(src)
  97. return src
  98. # ---------------------------- Attention ----------------------------
  99. class MultiHeadAttention(nn.Module):
  100. def __init__(self, d_model, num_heads, dropout=0.) -> None:
  101. super().__init__()
  102. # --------------- Basic parameters ---------------
  103. self.d_model = d_model
  104. self.num_heads = num_heads
  105. self.dropout = dropout
  106. self.scale = (d_model // num_heads) ** -0.5
  107. # --------------- Network parameters ---------------
  108. self.q_proj = nn.Linear(d_model, d_model, bias = False) # W_q, W_k, W_v
  109. self.k_proj = nn.Linear(d_model, d_model, bias = False) # W_q, W_k, W_v
  110. self.v_proj = nn.Linear(d_model, d_model, bias = False) # W_q, W_k, W_v
  111. self.out_proj = nn.Linear(d_model, d_model)
  112. self.dropout = nn.Dropout(dropout)
  113. def forward(self, query, key, value):
  114. """
  115. Inputs:
  116. query : (Tensor) -> [B, Nq, C]
  117. key : (Tensor) -> [B, Nk, C]
  118. value : (Tensor) -> [B, Nk, C]
  119. """
  120. bs = query.shape[0]
  121. Nq = query.shape[1]
  122. Nk = key.shape[1]
  123. # ----------------- Input proj -----------------
  124. query = self.q_proj(query)
  125. key = self.k_proj(key)
  126. value = self.v_proj(value)
  127. # ----------------- Multi-head Attn -----------------
  128. ## [B, N, C] -> [B, N, H, C_h] -> [B, H, N, C_h]
  129. query = query.view(bs, Nq, self.num_heads, self.d_model // self.num_heads)
  130. query = query.permute(0, 2, 1, 3).contiguous()
  131. key = key.view(bs, Nk, self.num_heads, self.d_model // self.num_heads)
  132. key = key.permute(0, 2, 1, 3).contiguous()
  133. value = value.view(bs, Nk, self.num_heads, self.d_model // self.num_heads)
  134. value = value.permute(0, 2, 1, 3).contiguous()
  135. # Attention
  136. ## [B, H, Nq, C_h] X [B, H, C_h, Nk] = [B, H, Nq, Nk]
  137. sim_matrix = torch.matmul(query, key.transpose(-1, -2)) * self.scale
  138. sim_matrix = torch.softmax(sim_matrix, dim=-1)
  139. # ----------------- Output -----------------
  140. out = torch.matmul(sim_matrix, value) # [B, H, Nq, C_h]
  141. out = out.permute(0, 2, 1, 3).contiguous().view(bs, Nq, -1)
  142. out = self.out_proj(out)
  143. return out
  144. # ---------------------------- Modified YOLOv7's Modules ----------------------------
  145. class ELANBlock(nn.Module):
  146. def __init__(self, in_dim, out_dim, expand_ratio=0.5, depth=1.0, act_type='silu', norm_type='BN', depthwise=False):
  147. super(ELANBlock, self).__init__()
  148. if isinstance(expand_ratio, float):
  149. inter_dim = int(in_dim * expand_ratio)
  150. inter_dim2 = inter_dim
  151. elif isinstance(expand_ratio, list):
  152. assert len(expand_ratio) == 2
  153. e1, e2 = expand_ratio
  154. inter_dim = int(in_dim * e1)
  155. inter_dim2 = int(inter_dim * e2)
  156. # branch-1
  157. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  158. # branch-2
  159. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  160. # branch-3
  161. for idx in range(round(3*depth)):
  162. if idx == 0:
  163. cv3 = [Conv(inter_dim, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  164. else:
  165. cv3.append(Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  166. self.cv3 = nn.Sequential(*cv3)
  167. # branch-4
  168. self.cv4 = nn.Sequential(*[
  169. Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  170. for _ in range(round(3*depth))
  171. ])
  172. # output
  173. self.out = Conv(inter_dim*2 + inter_dim2*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  174. def forward(self, x):
  175. """
  176. Input:
  177. x: [B, C_in, H, W]
  178. Output:
  179. out: [B, C_out, H, W]
  180. """
  181. x1 = self.cv1(x)
  182. x2 = self.cv2(x)
  183. x3 = self.cv3(x2)
  184. x4 = self.cv4(x3)
  185. # [B, C, H, W] -> [B, 2C, H, W]
  186. out = self.out(torch.cat([x1, x2, x3, x4], dim=1))
  187. return out
  188. class ELANBlockFPN(nn.Module):
  189. 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):
  190. super().__init__()
  191. # ----------- Basic Parameters -----------
  192. self.in_dim = in_dim
  193. self.out_dim = out_dim
  194. self.inter_dim1 = round(out_dim * expand_ratio)
  195. self.inter_dim2 = round(self.inter_dim1 * expand_ratio)
  196. self.expand_ratio = expand_ratio
  197. self.branch_depth = branch_depth
  198. self.shortcut = shortcut
  199. # ----------- Network Parameters -----------
  200. ## branch-1
  201. self.cv1 = Conv(in_dim, self.inter_dim1, k=1, act_type=act_type, norm_type=norm_type)
  202. ## branch-2
  203. self.cv2 = Conv(in_dim, self.inter_dim1, k=1, act_type=act_type, norm_type=norm_type)
  204. ## branch-3
  205. self.cv3 = []
  206. for i in range(branch_depth):
  207. if i == 0:
  208. self.cv3.append(Conv(self.inter_dim1, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  209. else:
  210. self.cv3.append(Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  211. self.cv3 = nn.Sequential(*self.cv3)
  212. ## branch-4
  213. self.cv4 = nn.Sequential(*[
  214. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  215. for _ in range(branch_depth)
  216. ])
  217. ## branch-5
  218. self.cv5 = nn.Sequential(*[
  219. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  220. for _ in range(branch_depth)
  221. ])
  222. ## branch-6
  223. self.cv6 = nn.Sequential(*[
  224. Conv(self.inter_dim2, self.inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  225. for _ in range(branch_depth)
  226. ])
  227. ## output proj
  228. self.out = Conv(self.inter_dim1*2 + self.inter_dim2*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  229. def forward(self, x):
  230. x1 = self.cv1(x)
  231. x2 = self.cv2(x)
  232. x3 = self.cv3(x2)
  233. x4 = self.cv4(x3)
  234. x5 = self.cv5(x4)
  235. x6 = self.cv6(x5)
  236. # [B, C, H, W] -> [B, 2C, H, W]
  237. out = self.out(torch.cat([x1, x2, x3, x4, x5, x6], dim=1))
  238. return out
  239. class DSBlock(nn.Module):
  240. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  241. super().__init__()
  242. inter_dim = out_dim // 2
  243. self.mp = nn.MaxPool2d((2, 2), 2)
  244. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  245. self.cv2 = nn.Sequential(
  246. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  247. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  248. )
  249. def forward(self, x):
  250. x1 = self.cv1(self.mp(x))
  251. x2 = self.cv2(x)
  252. out = torch.cat([x1, x2], dim=1)
  253. return out
  254. # ---------------------------- Transformer Modules ----------------------------
  255. class TREncoderLayer(nn.Module):
  256. def __init__(self,
  257. d_model,
  258. num_heads,
  259. mlp_ratio=4.0,
  260. dropout=0.1,
  261. act_type="relu",
  262. ):
  263. super().__init__()
  264. # Multi-head Self-Attn
  265. self.self_attn = MultiHeadAttention(d_model, num_heads, dropout)
  266. self.dropout = nn.Dropout(dropout)
  267. self.norm = nn.LayerNorm(d_model)
  268. # Feedforwaed Network
  269. self.ffn = FFN(d_model, mlp_ratio, dropout, act_type)
  270. def with_pos_embed(self, tensor, pos: Optional[Tensor]):
  271. return tensor if pos is None else tensor + pos
  272. def forward(self, src, pos):
  273. """
  274. Input:
  275. src: [torch.Tensor] -> [B, N, C]
  276. pos: [torch.Tensor] -> [B, N, C]
  277. Output:
  278. src: [torch.Tensor] -> [B, N, C]
  279. """
  280. q = k = self.with_pos_embed(src, pos)
  281. # self-attn
  282. src2 = self.self_attn(q, k, value=src)
  283. # reshape: [B, N, C] -> [B, C, H, W]
  284. src = src + self.dropout(src2)
  285. src = self.norm(src)
  286. # ffpn
  287. src = self.ffn(src)
  288. return src
  289. class TRDecoderLayer(nn.Module):
  290. def __init__(self,
  291. d_model,
  292. num_heads,
  293. mlp_ratio=4.0,
  294. dropout=0.1,
  295. act_type="relu"):
  296. super().__init__()
  297. self.d_model = d_model
  298. # self attention
  299. self.self_attn = MultiHeadAttention(d_model, num_heads, dropout)
  300. self.dropout1 = nn.Dropout(dropout)
  301. self.norm1 = nn.LayerNorm(d_model)
  302. # cross attention
  303. self.cross_attn = MultiHeadAttention(d_model, num_heads, dropout)
  304. self.dropout2 = nn.Dropout(dropout)
  305. self.norm2 = nn.LayerNorm(d_model)
  306. # FFN
  307. self.ffn = FFN(d_model, mlp_ratio, dropout, act_type)
  308. def with_pos_embed(self, tensor, pos: Optional[Tensor]):
  309. return tensor if pos is None else tensor + pos
  310. def forward(self, tgt, query_pos, memory, memory_pos):
  311. # self attention
  312. q1 = k1 = self.with_pos_embed(tgt, query_pos)
  313. v1 = tgt
  314. tgt2 = self.self_attn(q1, k1, v1)
  315. tgt = tgt + self.dropout1(tgt2)
  316. tgt = self.norm1(tgt)
  317. # cross attention
  318. q2 = self.with_pos_embed(tgt, query_pos)
  319. k2 = self.with_pos_embed(memory, memory_pos)
  320. v2 = memory
  321. tgt2 = self.cross_attn(q2, k2, v2)
  322. tgt = tgt + self.dropout2(tgt2)
  323. tgt = self.norm2(tgt)
  324. # ffn
  325. tgt = self.ffn(tgt)
  326. return tgt