yolov8_basic.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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, d, g, bias=False):
  10. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, 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 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. if depthwise:
  49. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  50. # depthwise conv
  51. if norm_type:
  52. convs.append(get_norm(norm_type, c1))
  53. if act_type:
  54. convs.append(get_activation(act_type))
  55. # pointwise conv
  56. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  57. if norm_type:
  58. convs.append(get_norm(norm_type, c2))
  59. if act_type:
  60. convs.append(get_activation(act_type))
  61. else:
  62. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  63. if norm_type:
  64. convs.append(get_norm(norm_type, c2))
  65. if act_type:
  66. convs.append(get_activation(act_type))
  67. self.convs = nn.Sequential(*convs)
  68. def forward(self, x):
  69. return self.convs(x)
  70. # --------------------- Yolov8 modules ---------------------
  71. ## Yolov8 BottleNeck
  72. class Yolov8Bottleneck(nn.Module):
  73. def __init__(self,
  74. in_dim,
  75. out_dim,
  76. expand_ratio = 0.5,
  77. kernel_sizes = [3, 3],
  78. shortcut = True,
  79. act_type = 'silu',
  80. norm_type = 'BN',
  81. depthwise = False,):
  82. super(Yolov8Bottleneck, self).__init__()
  83. inter_dim = int(out_dim * expand_ratio) # hidden channels
  84. self.cv1 = Conv(in_dim, inter_dim, k=kernel_sizes[0], p=kernel_sizes[0]//2, norm_type=norm_type, act_type=act_type, depthwise=depthwise)
  85. self.cv2 = Conv(inter_dim, out_dim, k=kernel_sizes[1], p=kernel_sizes[1]//2, norm_type=norm_type, act_type=act_type, depthwise=depthwise)
  86. self.shortcut = shortcut and in_dim == out_dim
  87. def forward(self, x):
  88. h = self.cv2(self.cv1(x))
  89. return x + h if self.shortcut else h
  90. # Yolov8 StageBlock
  91. class Yolov8StageBlock(nn.Module):
  92. def __init__(self,
  93. in_dim,
  94. out_dim,
  95. num_blocks = 1,
  96. shortcut = False,
  97. act_type = 'silu',
  98. norm_type = 'BN',
  99. depthwise = False,):
  100. super(Yolov8StageBlock, self).__init__()
  101. self.inter_dim = out_dim // 2
  102. self.input_proj = Conv(in_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  103. self.m = nn.Sequential(*(
  104. Yolov8Bottleneck(self.inter_dim, self.inter_dim, 1.0, [3, 3], shortcut, act_type, norm_type, depthwise)
  105. for _ in range(num_blocks)))
  106. self.output_proj = Conv((2 + num_blocks) * self.inter_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  107. def forward(self, x):
  108. # Input proj
  109. x1, x2 = torch.chunk(self.input_proj(x), 2, dim=1)
  110. out = list([x1, x2])
  111. # Bottlenecl
  112. out.extend(m(out[-1]) for m in self.m)
  113. # Output proj
  114. out = self.output_proj(torch.cat(out, dim=1))
  115. return out