modules.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from typing import List
  5. # ----------------- CNN modules -----------------
  6. class ConvModule(nn.Module):
  7. def __init__(self,
  8. in_dim, # in channels
  9. out_dim, # out channels
  10. kernel_size=1, # kernel size
  11. stride=1, # padding
  12. groups=1, # groups
  13. use_act: bool = True,
  14. ):
  15. super(ConvModule, self).__init__()
  16. self.conv = nn.Conv2d(in_dim, out_dim, kernel_size, padding=kernel_size//2, stride=stride, groups=groups, bias=False)
  17. self.norm = nn.BatchNorm2d(out_dim)
  18. self.act = nn.SiLU(inplace=True) if use_act else nn.Identity()
  19. def forward(self, x):
  20. return self.act(self.norm(self.conv(x)))
  21. class Bottleneck(nn.Module):
  22. def __init__(self,
  23. in_dim :int,
  24. out_dim :int,
  25. kernel_size :List = [3, 3],
  26. shortcut :bool = False,
  27. expansion :float = 0.5,
  28. ) -> None:
  29. super(Bottleneck, self).__init__()
  30. # ----------------- Network setting -----------------
  31. inter_dim = int(out_dim * expansion)
  32. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=kernel_size[0], stride=1)
  33. self.cv2 = ConvModule(inter_dim, out_dim, kernel_size=kernel_size[1], stride=1)
  34. self.shortcut = shortcut and in_dim == out_dim
  35. def forward(self, x):
  36. h = self.cv2(self.cv1(x))
  37. return x + h if self.shortcut else h
  38. class C3kBlock(nn.Module):
  39. def __init__(self,
  40. in_dim: int,
  41. out_dim: int,
  42. num_blocks: int = 1,
  43. shortcut: bool = True,
  44. expansion: float = 0.5,
  45. ):
  46. super().__init__()
  47. inter_dim = int(out_dim * expansion) # hidden channels
  48. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1)
  49. self.cv2 = ConvModule(in_dim, inter_dim, kernel_size=1)
  50. self.cv3 = ConvModule(2 * inter_dim, out_dim, kernel_size=1) # optional act=FReLU(c2)
  51. self.m = nn.Sequential(*[
  52. Bottleneck(in_dim = inter_dim,
  53. out_dim = inter_dim,
  54. kernel_size = [3, 3],
  55. shortcut = shortcut,
  56. expansion = 1.0,
  57. ) for _ in range(num_blocks)])
  58. def forward(self, x):
  59. return self.cv3(torch.cat([self.m(self.cv1(x)), self.cv2(x)], dim=1))
  60. class C3k2fBlock(nn.Module):
  61. def __init__(self, in_dim, out_dim, num_blocks=1, use_c3k=True, expansion=0.5, shortcut=True):
  62. super().__init__()
  63. inter_dim = int(out_dim * expansion) # hidden channels
  64. self.cv1 = ConvModule(in_dim, 2 * inter_dim, kernel_size=1)
  65. self.cv2 = ConvModule((2 + num_blocks) * inter_dim, out_dim, kernel_size=1)
  66. if use_c3k:
  67. self.m = nn.ModuleList(
  68. C3kBlock(inter_dim, inter_dim, 2, shortcut)
  69. for _ in range(num_blocks)
  70. )
  71. else:
  72. self.m = nn.ModuleList(
  73. Bottleneck(inter_dim, inter_dim, [3, 3], shortcut, expansion=0.5)
  74. for _ in range(num_blocks)
  75. )
  76. def _forward_impl(self, x):
  77. # Input proj
  78. x1, x2 = torch.chunk(self.cv1(x), 2, dim=1)
  79. out = list([x1, x2])
  80. # Bottlenecl
  81. out.extend(m(out[-1]) for m in self.m)
  82. # Output proj
  83. out = self.cv2(torch.cat(out, dim=1))
  84. return out
  85. def forward(self, x):
  86. return self._forward_impl(x)
  87. # ----------------- Attention modules -----------------
  88. class Attention(nn.Module):
  89. def __init__(self, dim, num_heads=8, attn_ratio=0.5):
  90. super().__init__()
  91. self.num_heads = num_heads
  92. self.head_dim = dim // num_heads
  93. self.key_dim = int(self.head_dim * attn_ratio)
  94. self.scale = self.key_dim**-0.5
  95. nh_kd = self.key_dim * num_heads
  96. h = dim + nh_kd * 2
  97. self.qkv = ConvModule(dim, h, kernel_size=1, use_act=False)
  98. self.proj = ConvModule(dim, dim, kernel_size=1, use_act=False)
  99. self.pe = ConvModule(dim, dim, kernel_size=3, groups=dim, use_act=False)
  100. def forward(self, x):
  101. bs, c, h, w = x.shape
  102. seq_len = h * w
  103. qkv = self.qkv(x)
  104. q, k, v = qkv.view(bs, self.num_heads, self.key_dim * 2 + self.head_dim, seq_len).split(
  105. [self.key_dim, self.key_dim, self.head_dim], dim=2
  106. )
  107. attn = (q.transpose(-2, -1) @ k) * self.scale
  108. attn = attn.softmax(dim=-1)
  109. x = (v @ attn.transpose(-2, -1)).view(bs, c, h, w) + self.pe(v.reshape(bs, c, h, w))
  110. x = self.proj(x)
  111. return x
  112. class PSABlock(nn.Module):
  113. def __init__(self, in_dim, attn_ratio=0.5, num_heads=4, shortcut=True):
  114. super().__init__()
  115. self.attn = Attention(in_dim, attn_ratio=attn_ratio, num_heads=num_heads)
  116. self.ffn = nn.Sequential(ConvModule(in_dim, in_dim * 2, kernel_size=1),
  117. ConvModule(in_dim * 2, in_dim, kernel_size=1, use_act=False))
  118. self.add = shortcut
  119. def forward(self, x):
  120. x = x + self.attn(x) if self.add else self.attn(x)
  121. x = x + self.ffn(x) if self.add else self.ffn(x)
  122. return x