yolov7_af_pafpn.py 8.1 KB

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