yolov7_basic.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import torch
  2. import torch.nn as nn
  3. class SiLU(nn.Module):
  4. """export-friendly version of nn.SiLU()"""
  5. @staticmethod
  6. def forward(x):
  7. return x * torch.sigmoid(x)
  8. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  9. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  10. return conv
  11. def get_activation(act_type=None):
  12. if act_type == 'relu':
  13. return nn.ReLU(inplace=True)
  14. elif act_type == 'lrelu':
  15. return nn.LeakyReLU(0.1, inplace=True)
  16. elif act_type == 'mish':
  17. return nn.Mish(inplace=True)
  18. elif act_type == 'silu':
  19. return nn.SiLU(inplace=True)
  20. def get_norm(norm_type, dim):
  21. if norm_type == 'BN':
  22. return nn.BatchNorm2d(dim)
  23. elif norm_type == 'GN':
  24. return nn.GroupNorm(num_groups=32, num_channels=dim)
  25. # Basic conv layer
  26. class Conv(nn.Module):
  27. def __init__(self,
  28. c1, # in channels
  29. c2, # out channels
  30. k=1, # kernel size
  31. p=0, # padding
  32. s=1, # padding
  33. d=1, # dilation
  34. act_type='lrelu', # activation
  35. norm_type='BN', # normalization
  36. depthwise=False):
  37. super(Conv, self).__init__()
  38. convs = []
  39. add_bias = False if norm_type else True
  40. if depthwise:
  41. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  42. # depthwise conv
  43. if norm_type:
  44. convs.append(get_norm(norm_type, c1))
  45. if act_type:
  46. convs.append(get_activation(act_type))
  47. # pointwise conv
  48. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  49. if norm_type:
  50. convs.append(get_norm(norm_type, c2))
  51. if act_type:
  52. convs.append(get_activation(act_type))
  53. else:
  54. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  55. if norm_type:
  56. convs.append(get_norm(norm_type, c2))
  57. if act_type:
  58. convs.append(get_activation(act_type))
  59. self.convs = nn.Sequential(*convs)
  60. def forward(self, x):
  61. return self.convs(x)
  62. # ELAN Block
  63. class ELANBlock(nn.Module):
  64. """
  65. ELAN BLock of YOLOv7's backbone
  66. """
  67. def __init__(self, in_dim, out_dim, expand_ratio=0.5, act_type='silu', norm_type='BN', depthwise=False):
  68. super(ELANBlock, self).__init__()
  69. inter_dim = int(in_dim * expand_ratio)
  70. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  71. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  72. self.cv3 = nn.Sequential(*[
  73. Conv(inter_dim, inter_dim, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  74. for _ in range(2)
  75. ])
  76. self.cv4 = nn.Sequential(*[
  77. Conv(inter_dim, inter_dim, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  78. for _ in range(2)
  79. ])
  80. self.out = Conv(inter_dim*4, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  81. def forward(self, x):
  82. """
  83. Input:
  84. x: [B, C, H, W]
  85. Output:
  86. out: [B, 2C, H, W]
  87. """
  88. x1 = self.cv1(x)
  89. x2 = self.cv2(x)
  90. x3 = self.cv3(x2)
  91. x4 = self.cv4(x3)
  92. # [B, C, H, W] -> [B, 2C, H, W]
  93. out = self.out(torch.cat([x1, x2, x3, x4], dim=1))
  94. return out
  95. # DownSample Block
  96. class DownSample(nn.Module):
  97. def __init__(self, in_dim, act_type='silu', norm_type='BN'):
  98. super().__init__()
  99. inter_dim = in_dim // 2
  100. self.mp = nn.MaxPool2d((2, 2), 2)
  101. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  102. self.cv2 = nn.Sequential(
  103. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  104. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type)
  105. )
  106. def forward(self, x):
  107. """
  108. Input:
  109. x: [B, C, H, W]
  110. Output:
  111. out: [B, C, H//2, W//2]
  112. """
  113. # [B, C, H, W] -> [B, C//2, H//2, W//2]
  114. x1 = self.cv1(self.mp(x))
  115. x2 = self.cv2(x)
  116. # [B, C, H//2, W//2]
  117. out = torch.cat([x1, x2], dim=1)
  118. return out
  119. # ELAN Block for PaFPN
  120. class ELANBlockFPN(nn.Module):
  121. """
  122. ELAN BLock of YOLOv7's head
  123. """
  124. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  125. super(ELANBlockFPN, self).__init__()
  126. # Basic parameters
  127. e1, e2 = 0.5, 0.5
  128. width = 4
  129. depth = 1
  130. inter_dim = int(in_dim * e1)
  131. inter_dim2 = int(inter_dim * e2)
  132. # Network structure
  133. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  134. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  135. self.cv3 = nn.ModuleList()
  136. for idx in range(width):
  137. if idx == 0:
  138. cvs = [Conv(inter_dim, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  139. else:
  140. cvs = [Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  141. # deeper
  142. if depth > 1:
  143. for _ in range(1, depth):
  144. cvs.append(Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  145. self.cv3.append(nn.Sequential(*cvs))
  146. else:
  147. self.cv3.append(cvs[0])
  148. self.out = Conv(inter_dim*2+inter_dim2*len(self.cv3), out_dim, k=1, act_type=act_type, norm_type=norm_type)
  149. def forward(self, x):
  150. """
  151. Input:
  152. x: [B, C_in, H, W]
  153. Output:
  154. out: [B, C_out, H, W]
  155. """
  156. x1 = self.cv1(x)
  157. x2 = self.cv2(x)
  158. inter_outs = [x1, x2]
  159. for m in self.cv3:
  160. y1 = inter_outs[-1]
  161. y2 = m(y1)
  162. inter_outs.append(y2)
  163. # [B, C_in, H, W] -> [B, C_out, H, W]
  164. out = self.out(torch.cat(inter_outs, dim=1))
  165. return out
  166. # DownSample Block for PaFPN
  167. class DownSampleFPN(nn.Module):
  168. def __init__(self, in_dim, act_type='silu', norm_type='BN', depthwise=False):
  169. super().__init__()
  170. inter_dim = in_dim
  171. self.mp = nn.MaxPool2d((2, 2), 2)
  172. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  173. self.cv2 = nn.Sequential(
  174. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  175. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  176. )
  177. def forward(self, x):
  178. """
  179. Input:
  180. x: [B, C, H, W]
  181. Output:
  182. out: [B, 2C, H//2, W//2]
  183. """
  184. # [B, C, H, W] -> [B, C//2, H//2, W//2]
  185. x1 = self.cv1(self.mp(x))
  186. x2 = self.cv2(x)
  187. # [B, C, H//2, W//2]
  188. out = torch.cat([x1, x2], dim=1)
  189. return out