yolov8_basic.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 YoloBottleneck(nn.Module):
  64. def __init__(self,
  65. in_dim :int,
  66. out_dim :int,
  67. kernel_size :List = [1, 3],
  68. expansion :float = 0.5,
  69. shortcut :bool = False,
  70. act_type :str = 'silu',
  71. norm_type :str = 'BN',
  72. depthwise :bool = False,
  73. ) -> None:
  74. super(YoloBottleneck, self).__init__()
  75. inter_dim = int(out_dim * expansion)
  76. # ----------------- Network setting -----------------
  77. self.conv_layer1 = BasicConv(in_dim, inter_dim,
  78. kernel_size=kernel_size[0], padding=kernel_size[0]//2, stride=1,
  79. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  80. self.conv_layer2 = BasicConv(inter_dim, out_dim,
  81. kernel_size=kernel_size[1], padding=kernel_size[1]//2, stride=1,
  82. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  83. self.shortcut = shortcut and in_dim == out_dim
  84. def forward(self, x):
  85. h = self.conv_layer2(self.conv_layer1(x))
  86. return x + h if self.shortcut else h
  87. class CSPLayer(nn.Module):
  88. # CSP Bottleneck with 3 convolutions
  89. def __init__(self,
  90. in_dim :int,
  91. out_dim :int,
  92. num_blocks :int = 1,
  93. kernel_size :List = [3, 3],
  94. expansion :float = 0.5,
  95. shortcut :bool = True,
  96. act_type :str = 'silu',
  97. norm_type :str = 'BN',
  98. depthwise :bool = False,
  99. ) -> None:
  100. super().__init__()
  101. inter_dim = round(out_dim * expansion)
  102. self.input_proj_1 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  103. self.input_proj_2 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  104. self.output_proj = BasicConv(2 * inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  105. self.module = nn.Sequential(*[YoloBottleneck(inter_dim,
  106. inter_dim,
  107. kernel_size,
  108. expansion = 1.0,
  109. shortcut = shortcut,
  110. act_type = act_type,
  111. norm_type = norm_type,
  112. depthwise = depthwise,
  113. ) for _ in range(num_blocks)])
  114. def forward(self, x):
  115. x1 = self.input_proj_1(x)
  116. x2 = self.input_proj_2(x)
  117. x2 = self.module(x2)
  118. out = self.output_proj(torch.cat([x1, x2], dim=1))
  119. return out
  120. class ELANLayer(nn.Module):
  121. def __init__(self,
  122. in_dim,
  123. out_dim,
  124. expansion :float = 0.5,
  125. num_blocks :int = 1,
  126. shortcut :bool = False,
  127. act_type :str = 'silu',
  128. norm_type :str = 'BN',
  129. depthwise :bool = False,
  130. ) -> None:
  131. super(ELANLayer, self).__init__()
  132. inter_dim = round(out_dim * expansion)
  133. self.input_proj = BasicConv(in_dim, inter_dim * 2, kernel_size=1, act_type=act_type, norm_type=norm_type)
  134. self.output_proj = BasicConv((2 + num_blocks) * inter_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  135. self.module = nn.ModuleList([YoloBottleneck(inter_dim,
  136. inter_dim,
  137. kernel_size = [3, 3],
  138. expansion = 1.0,
  139. shortcut = shortcut,
  140. act_type = act_type,
  141. norm_type = norm_type,
  142. depthwise = depthwise)
  143. for _ in range(num_blocks)])
  144. def forward(self, x):
  145. # Input proj
  146. x1, x2 = torch.chunk(self.input_proj(x), 2, dim=1)
  147. out = list([x1, x2])
  148. # Bottlenecl
  149. out.extend(m(out[-1]) for m in self.module)
  150. # Output proj
  151. out = self.output_proj(torch.cat(out, dim=1))
  152. return out