yolov7_pafpn.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 .modules import ConvModule, ELANLayerFPN, MDown
  7. except:
  8. from modules import ConvModule, 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 = ConvModule(c5, round(256*cfg.width), kernel_size=1)
  19. self.reduce_layer_2 = ConvModule(c4, round(256*cfg.width), kernel_size=1)
  20. self.top_down_layer_1 = ELANLayerFPN(in_dim = round(256*cfg.width) + round(256*cfg.width),
  21. out_dim = round(256*cfg.width),
  22. expansions = cfg.fpn_expansions,
  23. branch_width = cfg.fpn_block_bw,
  24. branch_depth = cfg.fpn_block_dw,
  25. )
  26. ## P4 -> P3
  27. self.reduce_layer_3 = ConvModule(round(256*cfg.width), round(128*cfg.width), kernel_size=1)
  28. self.reduce_layer_4 = ConvModule(c3, round(128*cfg.width), kernel_size=1)
  29. self.top_down_layer_2 = ELANLayerFPN(in_dim = round(128*cfg.width) + round(128*cfg.width),
  30. out_dim = round(128*cfg.width),
  31. expansions = cfg.fpn_expansions,
  32. branch_width = cfg.fpn_block_bw,
  33. branch_depth = cfg.fpn_block_dw,
  34. )
  35. # ----------------------------- Yolov7's Bottom-up PAN -----------------------------
  36. ## P3 -> P4
  37. self.downsample_layer_1 = MDown(round(128*cfg.width), round(256*cfg.width))
  38. self.bottom_up_layer_1 = ELANLayerFPN(in_dim = round(256*cfg.width) + round(256*cfg.width),
  39. out_dim = round(256*cfg.width),
  40. expansions = cfg.fpn_expansions,
  41. branch_width = cfg.fpn_block_bw,
  42. branch_depth = cfg.fpn_block_dw,
  43. )
  44. ## P4 -> P5
  45. self.downsample_layer_2 = MDown(round(256*cfg.width), round(512*cfg.width))
  46. self.bottom_up_layer_2 = ELANLayerFPN(in_dim = round(512*cfg.width) + c5,
  47. out_dim = round(512*cfg.width),
  48. expansions = cfg.fpn_expansions,
  49. branch_width = cfg.fpn_block_bw,
  50. branch_depth = cfg.fpn_block_dw,
  51. )
  52. # ----------------------------- Head conv layers -----------------------------
  53. ## Head convs
  54. self.head_conv_1 = ConvModule(round(128*cfg.width), round(256*cfg.width), kernel_size=3, padding=1, stride=1)
  55. self.head_conv_2 = ConvModule(round(256*cfg.width), round(512*cfg.width), kernel_size=3, padding=1, stride=1)
  56. self.head_conv_3 = ConvModule(round(512*cfg.width), round(1024*cfg.width), kernel_size=3, padding=1, stride=1)
  57. # ---------------------- Yolox's output projection ----------------------
  58. self.out_layers = nn.ModuleList([
  59. ConvModule(in_dim, round(cfg.head_dim*cfg.width), kernel_size=1)
  60. for in_dim in [round(256*cfg.width), round(512*cfg.width), round(1024*cfg.width)]
  61. ])
  62. self.out_dims = [round(cfg.head_dim*cfg.width)] * 3
  63. # Initialize all layers
  64. self.init_weights()
  65. def init_weights(self):
  66. """Initialize the parameters."""
  67. for m in self.modules():
  68. if isinstance(m, torch.nn.Conv2d):
  69. m.reset_parameters()
  70. def forward(self, features):
  71. c3, c4, c5 = features
  72. # ------------------ Top down FPN ------------------
  73. ## P5 -> P4
  74. p5 = self.reduce_layer_1(c5)
  75. p5_up = F.interpolate(p5, scale_factor=2.0)
  76. p4 = self.reduce_layer_2(c4)
  77. p4 = self.top_down_layer_1(torch.cat([p5_up, p4], dim=1))
  78. ## P4 -> P3
  79. p4_in = self.reduce_layer_3(p4)
  80. p4_up = F.interpolate(p4_in, scale_factor=2.0)
  81. p3 = self.reduce_layer_4(c3)
  82. p3 = self.top_down_layer_2(torch.cat([p4_up, p3], dim=1))
  83. # ------------------ Bottom up PAN ------------------
  84. ## P3 -> P4
  85. p3_ds = self.downsample_layer_1(p3)
  86. p4 = torch.cat([p3_ds, p4], dim=1)
  87. p4 = self.bottom_up_layer_1(p4)
  88. ## P4 -> P5
  89. p4_ds = self.downsample_layer_2(p4)
  90. p5 = torch.cat([p4_ds, c5], dim=1)
  91. p5 = self.bottom_up_layer_2(p5)
  92. out_feats = [self.head_conv_1(p3), self.head_conv_2(p4), self.head_conv_3(p5)]
  93. # output proj layers
  94. out_feats_proj = []
  95. for feat, layer in zip(out_feats, self.out_layers):
  96. out_feats_proj.append(layer(feat))
  97. return out_feats_proj
  98. if __name__=='__main__':
  99. import time
  100. from thop import profile
  101. # Model config
  102. # YOLOv7-Base config
  103. class Yolov7BaseConfig(object):
  104. def __init__(self) -> None:
  105. # ---------------- Model config ----------------
  106. self.width = 0.50
  107. self.depth = 0.34
  108. self.out_stride = [8, 16, 32]
  109. self.max_stride = 32
  110. self.num_levels = 3
  111. self.fpn_expansions = [0.5, 0.5]
  112. self.fpn_block_bw = 4
  113. self.fpn_block_dw = 1
  114. ## Head
  115. self.head_dim = 256
  116. cfg = Yolov7BaseConfig()
  117. # Build a head
  118. in_dims = [128, 256, 512]
  119. fpn = Yolov7PaFPN(cfg, in_dims)
  120. # Inference
  121. x = [torch.randn(1, in_dims[0], 80, 80),
  122. torch.randn(1, in_dims[1], 40, 40),
  123. torch.randn(1, in_dims[2], 20, 20)]
  124. t0 = time.time()
  125. output = fpn(x)
  126. t1 = time.time()
  127. print('Time: ', t1 - t0)
  128. print('====== FPN output ====== ')
  129. for level, feat in enumerate(output):
  130. print("- Level-{} : ".format(level), feat.shape)
  131. flops, params = profile(fpn, inputs=(x, ), verbose=False)
  132. print('==============================')
  133. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  134. print('Params : {:.2f} M'.format(params / 1e6))