yolov7_af_basic.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. use_bias = False if norm_type is not None else True
  45. if not depthwise:
  46. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=1, bias=use_bias)
  47. self.norm = get_norm(norm_type, out_dim)
  48. else:
  49. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, d=dilation, g=in_dim, bias=use_bias)
  50. self.norm1 = get_norm(norm_type, in_dim)
  51. self.conv2 = get_conv2d(in_dim, out_dim, k=1, p=0, s=1, d=1, g=1)
  52. self.norm2 = get_norm(norm_type, out_dim)
  53. self.act = get_activation(act_type)
  54. def forward(self, x):
  55. if not self.depthwise:
  56. return self.act(self.norm(self.conv(x)))
  57. else:
  58. # Depthwise conv
  59. x = self.act(self.norm1(self.conv1(x)))
  60. # Pointwise conv
  61. x = self.act(self.norm2(self.conv2(x)))
  62. return x
  63. # ---------------------------- Basic Modules ----------------------------
  64. class MDown(nn.Module):
  65. def __init__(self,
  66. in_dim :int,
  67. out_dim :int,
  68. act_type :str = 'silu',
  69. norm_type :str = 'BN',
  70. depthwise :bool = False,
  71. ) -> None:
  72. super().__init__()
  73. inter_dim = out_dim // 2
  74. self.downsample_1 = nn.Sequential(
  75. nn.MaxPool2d((2, 2), stride=2),
  76. BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  77. )
  78. self.downsample_2 = nn.Sequential(
  79. BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type),
  80. BasicConv(inter_dim, inter_dim,
  81. kernel_size=3, padding=1, stride=2,
  82. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  83. )
  84. def forward(self, x):
  85. x1 = self.downsample_1(x)
  86. x2 = self.downsample_2(x)
  87. return torch.cat([x1, x2], dim=1)
  88. class ELANLayer(nn.Module):
  89. def __init__(self,
  90. in_dim,
  91. out_dim,
  92. expansion :float = 0.5,
  93. num_blocks :int = 1,
  94. act_type :str = 'silu',
  95. norm_type :str = 'BN',
  96. depthwise :bool = False,
  97. ) -> None:
  98. super(ELANLayer, self).__init__()
  99. self.inter_dim = round(in_dim * expansion)
  100. self.conv_layer_1 = BasicConv(in_dim, self.inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  101. self.conv_layer_2 = BasicConv(in_dim, self.inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  102. self.conv_layer_3 = BasicConv(self.inter_dim * 4, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  103. self.elan_layer_1 = nn.Sequential(*[BasicConv(self.inter_dim, self.inter_dim,
  104. kernel_size=3, padding=1,
  105. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  106. for _ in range(num_blocks)])
  107. self.elan_layer_2 = nn.Sequential(*[BasicConv(self.inter_dim, self.inter_dim,
  108. kernel_size=3, padding=1,
  109. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  110. for _ in range(num_blocks)])
  111. def forward(self, x):
  112. # Input proj
  113. x1 = self.conv_layer_1(x)
  114. x2 = self.conv_layer_2(x)
  115. x3 = self.elan_layer_1(x2)
  116. x4 = self.elan_layer_2(x3)
  117. out = self.conv_layer_3(torch.cat([x1, x2, x3, x4], dim=1))
  118. return out
  119. ## PaFPN's ELAN-Block proposed by YOLOv7
  120. class ELANLayerFPN(nn.Module):
  121. def __init__(self,
  122. in_dim,
  123. out_dim,
  124. expansions :List = [0.5, 0.5],
  125. branch_width :int = 4,
  126. branch_depth :int = 1,
  127. act_type :str = 'silu',
  128. norm_type :str = 'BN',
  129. depthwise=False):
  130. super(ELANLayerFPN, self).__init__()
  131. # Basic parameters
  132. inter_dim = round(in_dim * expansions[0])
  133. inter_dim2 = round(inter_dim * expansions[1])
  134. # Network structure
  135. self.cv1 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  136. self.cv2 = BasicConv(in_dim, inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  137. self.cv3 = nn.ModuleList()
  138. for idx in range(round(branch_width)):
  139. if idx == 0:
  140. cvs = [BasicConv(inter_dim, inter_dim2,
  141. kernel_size=3, padding=1,
  142. act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  143. else:
  144. cvs = [BasicConv(inter_dim2, inter_dim2,
  145. kernel_size=3, padding=1,
  146. act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  147. # deeper
  148. if round(branch_depth) > 1:
  149. for _ in range(1, round(branch_depth)):
  150. cvs.append(BasicConv(inter_dim2, inter_dim2, kernel_size=3, padding=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  151. self.cv3.append(nn.Sequential(*cvs))
  152. else:
  153. self.cv3.append(cvs[0])
  154. self.output_proj = BasicConv(inter_dim*2+inter_dim2*len(self.cv3), out_dim,
  155. kernel_size=1, act_type=act_type, norm_type=norm_type)
  156. def forward(self, x):
  157. x1 = self.cv1(x)
  158. x2 = self.cv2(x)
  159. inter_outs = [x1, x2]
  160. for m in self.cv3:
  161. y1 = inter_outs[-1]
  162. y2 = m(y1)
  163. inter_outs.append(y2)
  164. out = self.output_proj(torch.cat(inter_outs, dim=1))
  165. return out