yolov7_af_pafpn.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from typing import List
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. try:
  6. from .yolov7_af_basic import BasicConv, ELANLayerFPN, MDown
  7. except:
  8. from yolov7_af_basic import BasicConv, ELANLayerFPN, MDown
  9. # Yolov7 af PaFPN
  10. class Yolov7PaFPN(nn.Module):
  11. def __init__(self, cfg, in_dims: List = [512, 1024, 512]):
  12. super(Yolov7PaFPN, self).__init__()
  13. # ----------------------------- Basic parameters -----------------------------
  14. self.in_dims = in_dims
  15. c3, c4, c5 = in_dims
  16. # ----------------------------- Yolov7's Top-down FPN -----------------------------
  17. ## P5 -> P4
  18. self.reduce_layer_1 = BasicConv(c5, round(256*cfg.width),
  19. kernel_size=1, act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  20. self.reduce_layer_2 = BasicConv(c4, round(256*cfg.width),
  21. kernel_size=1, act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  22. self.top_down_layer_1 = ELANLayerFPN(in_dim = round(256*cfg.width) + round(256*cfg.width),
  23. out_dim = round(256*cfg.width),
  24. expansions = cfg.fpn_expansions,
  25. branch_width = cfg.fpn_block_bw,
  26. branch_depth = cfg.fpn_block_dw,
  27. act_type = cfg.fpn_act,
  28. norm_type = cfg.fpn_norm,
  29. depthwise = cfg.fpn_depthwise,
  30. )
  31. ## P4 -> P3
  32. self.reduce_layer_3 = BasicConv(round(256*cfg.width), round(128*cfg.width),
  33. kernel_size=1, act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  34. self.reduce_layer_4 = BasicConv(c3, round(128*cfg.width),
  35. kernel_size=1, act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  36. self.top_down_layer_2 = ELANLayerFPN(in_dim = round(128*cfg.width) + round(128*cfg.width),
  37. out_dim = round(128*cfg.width),
  38. expansions = cfg.fpn_expansions,
  39. branch_width = cfg.fpn_block_bw,
  40. branch_depth = cfg.fpn_block_dw,
  41. act_type = cfg.fpn_act,
  42. norm_type = cfg.fpn_norm,
  43. depthwise = cfg.fpn_depthwise,
  44. )
  45. # ----------------------------- Yolov7's Bottom-up PAN -----------------------------
  46. ## P3 -> P4
  47. self.downsample_layer_1 = MDown(round(128*cfg.width), round(256*cfg.width),
  48. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  49. self.bottom_up_layer_1 = ELANLayerFPN(in_dim = round(256*cfg.width) + round(256*cfg.width),
  50. out_dim = round(256*cfg.width),
  51. expansions = cfg.fpn_expansions,
  52. branch_width = cfg.fpn_block_bw,
  53. branch_depth = cfg.fpn_block_dw,
  54. act_type = cfg.fpn_act,
  55. norm_type = cfg.fpn_norm,
  56. depthwise = cfg.fpn_depthwise,
  57. )
  58. ## P4 -> P5
  59. self.downsample_layer_2 = MDown(round(256*cfg.width), round(512*cfg.width),
  60. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  61. self.bottom_up_layer_2 = ELANLayerFPN(in_dim = round(512*cfg.width) + c5,
  62. out_dim = round(512*cfg.width),
  63. expansions = cfg.fpn_expansions,
  64. branch_width = cfg.fpn_block_bw,
  65. branch_depth = cfg.fpn_block_dw,
  66. act_type = cfg.fpn_act,
  67. norm_type = cfg.fpn_norm,
  68. depthwise = cfg.fpn_depthwise,
  69. )
  70. # ----------------------------- Head conv layers -----------------------------
  71. ## Head convs
  72. self.head_conv_1 = BasicConv(round(128*cfg.width), round(256*cfg.width),
  73. kernel_size=3, padding=1, stride=1,
  74. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  75. self.head_conv_2 = BasicConv(round(256*cfg.width), round(512*cfg.width),
  76. kernel_size=3, padding=1, stride=1,
  77. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  78. self.head_conv_3 = BasicConv(round(512*cfg.width), round(1024*cfg.width),
  79. kernel_size=3, padding=1, stride=1,
  80. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  81. # ---------------------- Yolox's output projection ----------------------
  82. self.out_layers = nn.ModuleList([
  83. BasicConv(in_dim, round(cfg.head_dim*cfg.width), kernel_size=1,
  84. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  85. for in_dim in [round(256*cfg.width), round(512*cfg.width), round(1024*cfg.width)]
  86. ])
  87. self.out_dims = [round(cfg.head_dim*cfg.width)] * 3
  88. # Initialize all layers
  89. self.init_weights()
  90. def init_weights(self):
  91. """Initialize the parameters."""
  92. for m in self.modules():
  93. if isinstance(m, torch.nn.Conv2d):
  94. # In order to be consistent with the source code,
  95. # reset the Conv2d initialization parameters
  96. m.reset_parameters()
  97. def forward(self, features):
  98. c3, c4, c5 = features
  99. # ------------------ Top down FPN ------------------
  100. ## P5 -> P4
  101. p5 = self.reduce_layer_1(c5)
  102. p5_up = F.interpolate(p5, scale_factor=2.0)
  103. p4 = self.reduce_layer_2(c4)
  104. p4 = self.top_down_layer_1(torch.cat([p5_up, p4], dim=1))
  105. ## P4 -> P3
  106. p4_in = self.reduce_layer_3(p4)
  107. p4_up = F.interpolate(p4_in, scale_factor=2.0)
  108. p3 = self.reduce_layer_4(c3)
  109. p3 = self.top_down_layer_2(torch.cat([p4_up, p3], dim=1))
  110. # ------------------ Bottom up PAN ------------------
  111. ## P3 -> P4
  112. p3_ds = self.downsample_layer_1(p3)
  113. p4 = torch.cat([p3_ds, p4], dim=1)
  114. p4 = self.bottom_up_layer_1(p4)
  115. ## P4 -> P5
  116. p4_ds = self.downsample_layer_2(p4)
  117. p5 = torch.cat([p4_ds, c5], dim=1)
  118. p5 = self.bottom_up_layer_2(p5)
  119. out_feats = [self.head_conv_1(p3), self.head_conv_2(p4), self.head_conv_3(p5)]
  120. # output proj layers
  121. out_feats_proj = []
  122. for feat, layer in zip(out_feats, self.out_layers):
  123. out_feats_proj.append(layer(feat))
  124. return out_feats_proj
  125. if __name__=='__main__':
  126. import time
  127. from thop import profile
  128. # Model config
  129. # YOLOv7-Base config
  130. class Yolov7BaseConfig(object):
  131. def __init__(self) -> None:
  132. # ---------------- Model config ----------------
  133. self.width = 0.50
  134. self.depth = 0.34
  135. self.out_stride = [8, 16, 32]
  136. self.max_stride = 32
  137. self.num_levels = 3
  138. ## FPN
  139. self.fpn_act = 'silu'
  140. self.fpn_norm = 'BN'
  141. self.fpn_depthwise = False
  142. ## Head
  143. self.head_dim = 256
  144. cfg = Yolov7BaseConfig()
  145. # Build a head
  146. in_dims = [128, 256, 512]
  147. fpn = Yolov7PaFPN(cfg, in_dims)
  148. # Inference
  149. x = [torch.randn(1, in_dims[0], 80, 80),
  150. torch.randn(1, in_dims[1], 40, 40),
  151. torch.randn(1, in_dims[2], 20, 20)]
  152. t0 = time.time()
  153. output = fpn(x)
  154. t1 = time.time()
  155. print('Time: ', t1 - t0)
  156. print('====== FPN output ====== ')
  157. for level, feat in enumerate(output):
  158. print("- Level-{} : ".format(level), feat.shape)
  159. flops, params = profile(fpn, inputs=(x, ), verbose=False)
  160. print('==============================')
  161. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  162. print('Params : {:.2f} M'.format(params / 1e6))