rtcdet_basic.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import torch
  2. import torch.nn as nn
  3. # --------------------- Basic modules ---------------------
  4. class SiLU(nn.Module):
  5. """export-friendly version of nn.SiLU()"""
  6. @staticmethod
  7. def forward(x):
  8. return x * torch.sigmoid(x)
  9. def get_conv2d(c1, c2, k, p, s, g, bias=False):
  10. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, groups=g, bias=bias)
  11. return conv
  12. def get_activation(act_type=None):
  13. if act_type == 'relu':
  14. return nn.ReLU(inplace=True)
  15. elif act_type == 'lrelu':
  16. return nn.LeakyReLU(0.1, inplace=True)
  17. elif act_type == 'mish':
  18. return nn.Mish(inplace=True)
  19. elif act_type == 'silu':
  20. return nn.SiLU(inplace=True)
  21. elif act_type is None:
  22. return nn.Identity()
  23. else:
  24. raise NotImplementedError
  25. def get_norm(norm_type, dim):
  26. if norm_type == 'BN':
  27. return nn.BatchNorm2d(dim)
  28. elif norm_type == 'GN':
  29. return nn.GroupNorm(num_groups=32, num_channels=dim)
  30. elif norm_type is None:
  31. return nn.Identity()
  32. else:
  33. raise NotImplementedError
  34. class BasicConv(nn.Module):
  35. def __init__(self,
  36. in_dim, # in channels
  37. out_dim, # out channels
  38. kernel_size :int = 1, # kernel size
  39. padding :int = 0, # padding
  40. stride :int = 1, # padding
  41. act_type :str = 'silu', # activation
  42. norm_type :str = 'BN', # normalization
  43. depthwise :bool = False,
  44. ):
  45. super(BasicConv, self).__init__()
  46. self.depthwise = depthwise
  47. add_bias = False if norm_type else True
  48. if not depthwise:
  49. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  50. self.norm = get_norm(norm_type, out_dim)
  51. self.act = get_activation(act_type)
  52. else:
  53. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, g=in_dim, bias=add_bias)
  54. self.norm1 = get_norm(norm_type, in_dim)
  55. self.conv2 = get_conv2d(in_dim, out_dim, k=1, d=0, s=1, g=1, bias=add_bias)
  56. self.norm2 = get_norm(norm_type, out_dim)
  57. self.act = get_activation(act_type)
  58. def forward(self, x):
  59. if not self.depthwise:
  60. return self.act(self.norm(self.conv(x)))
  61. else:
  62. return self.act(self.norm2(self.conv2(self.norm1(self.conv1(x)))))
  63. # --------------------- Yolov8 modules ---------------------
  64. ## Yolov8 BottleNeck
  65. class Bottleneck(nn.Module):
  66. def __init__(self,
  67. in_dim,
  68. out_dim,
  69. expand_ratio = 0.5,
  70. kernel_sizes = [3, 3],
  71. shortcut = True,
  72. act_type = 'silu',
  73. norm_type = 'BN',
  74. depthwise = False,):
  75. super(Bottleneck, self).__init__()
  76. inter_dim = int(out_dim * expand_ratio) # hidden channels
  77. padding_sizes = [k // 2 for k in kernel_sizes]
  78. self.cv1 = BasicConv(in_dim, inter_dim, kernel_size=kernel_sizes[0], padding=padding_sizes[0], act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  79. self.cv2 = BasicConv(inter_dim, out_dim, kernel_size=kernel_sizes[1], padding=padding_sizes[1], act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  80. self.shortcut = shortcut and in_dim == out_dim
  81. def forward(self, x):
  82. h = self.cv2(self.cv1(x))
  83. return x + h if self.shortcut else h
  84. # Yolov8 StageBlock
  85. class RTCBlock(nn.Module):
  86. def __init__(self,
  87. in_dim,
  88. out_dim,
  89. num_blocks = 1,
  90. shortcut = False,
  91. act_type = 'silu',
  92. norm_type = 'BN',
  93. depthwise = False,):
  94. super(RTCBlock, self).__init__()
  95. self.inter_dim = out_dim // 2
  96. self.input_proj = BasicConv(in_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  97. self.m = nn.ModuleList([
  98. Bottleneck(self.inter_dim, self.inter_dim, 1.0, [1, 3], shortcut, act_type, norm_type, depthwise)
  99. for _ in range(num_blocks)])
  100. self.output_proj = BasicConv((2 + num_blocks) * self.inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  101. def forward(self, x):
  102. # Input proj
  103. x1, x2 = torch.chunk(self.input_proj(x), 2, dim=1)
  104. out = list([x1, x2])
  105. # Bottleneck
  106. out.extend(m(out[-1]) for m in self.m)
  107. # Output proj
  108. out = self.output_proj(torch.cat(out, dim=1))
  109. return out