yolov8_pafpn.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from typing import List
  5. try:
  6. from .yolov8_basic import BasicConv, ELANLayer
  7. except:
  8. from yolov8_basic import BasicConv, ELANLayer
  9. # YOLOv8's PaFPN
  10. class Yolov8PaFPN(nn.Module):
  11. def __init__(self,
  12. cfg,
  13. in_dims :List = [256, 512, 1024],
  14. ) -> None:
  15. super(Yolov8PaFPN, self).__init__()
  16. print('==============================')
  17. print('FPN: {}'.format("Yolo PaFPN"))
  18. # --------------------------- Basic Parameters ---------------------------
  19. self.in_dims = in_dims[::-1]
  20. self.out_dims = [round(256*cfg.width), round(512*cfg.width), round(512*cfg.width*cfg.ratio)]
  21. # ----------------------------- Yolov8's Top-down FPN -----------------------------
  22. ## P5 -> P4
  23. self.top_down_layer_1 = ELANLayer(in_dim = self.in_dims[0] + self.in_dims[1],
  24. out_dim = round(512*cfg.width),
  25. expansion = 0.5,
  26. num_blocks = round(3 * cfg.depth),
  27. shortcut = False,
  28. act_type = cfg.fpn_act,
  29. norm_type = cfg.fpn_norm,
  30. depthwise = cfg.fpn_depthwise,
  31. )
  32. ## P4 -> P3
  33. self.top_down_layer_2 = ELANLayer(in_dim = self.in_dims[2] + round(512*cfg.width),
  34. out_dim = round(256*cfg.width),
  35. expansion = 0.5,
  36. num_blocks = round(3 * cfg.depth),
  37. shortcut = False,
  38. act_type = cfg.fpn_act,
  39. norm_type = cfg.fpn_norm,
  40. depthwise = cfg.fpn_depthwise,
  41. )
  42. # ----------------------------- Yolov8's Bottom-up PAN -----------------------------
  43. ## P3 -> P4
  44. self.dowmsample_layer_1 = BasicConv(round(256*cfg.width), round(256*cfg.width),
  45. kernel_size=3, padding=1, stride=2,
  46. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  47. self.bottom_up_layer_1 = ELANLayer(in_dim = round(256*cfg.width) + round(512*cfg.width),
  48. out_dim = round(512*cfg.width),
  49. expansion = 0.5,
  50. num_blocks = round(3 * cfg.depth),
  51. shortcut = False,
  52. act_type = cfg.fpn_act,
  53. norm_type = cfg.fpn_norm,
  54. depthwise = cfg.fpn_depthwise,
  55. )
  56. ## P4 -> P5
  57. self.dowmsample_layer_2 = BasicConv(round(512*cfg.width), round(512*cfg.width),
  58. kernel_size=3, padding=1, stride=2,
  59. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  60. self.bottom_up_layer_2 = ELANLayer(in_dim = round(512*cfg.width) + self.in_dims[0],
  61. out_dim = round(512*cfg.width*cfg.ratio),
  62. expansion = 0.5,
  63. num_blocks = round(3 * cfg.depth),
  64. shortcut = False,
  65. act_type = cfg.fpn_act,
  66. norm_type = cfg.fpn_norm,
  67. depthwise = cfg.fpn_depthwise,
  68. )
  69. self.init_weights()
  70. def init_weights(self):
  71. """Initialize the parameters."""
  72. for m in self.modules():
  73. if isinstance(m, torch.nn.Conv2d):
  74. # In order to be consistent with the source code,
  75. # reset the Conv2d initialization parameters
  76. m.reset_parameters()
  77. def forward(self, features):
  78. c3, c4, c5 = features
  79. # ------------------ Top down FPN ------------------
  80. ## P5 -> P4
  81. p5_up = F.interpolate(c5, scale_factor=2.0)
  82. p4 = self.top_down_layer_1(torch.cat([p5_up, c4], dim=1))
  83. ## P4 -> P3
  84. p4_up = F.interpolate(p4, scale_factor=2.0)
  85. p3 = self.top_down_layer_2(torch.cat([p4_up, c3], dim=1))
  86. # ------------------ Bottom up FPN ------------------
  87. ## p3 -> P4
  88. p3_ds = self.dowmsample_layer_1(p3)
  89. p4 = self.bottom_up_layer_1(torch.cat([p3_ds, p4], dim=1))
  90. ## P4 -> 5
  91. p4_ds = self.dowmsample_layer_2(p4)
  92. p5 = self.bottom_up_layer_2(torch.cat([p4_ds, c5], dim=1))
  93. out_feats = [p3, p4, p5] # [P3, P4, P5]
  94. return out_feats
  95. if __name__=='__main__':
  96. import time
  97. from thop import profile
  98. # Model config
  99. # YOLOv8-Base config
  100. class Yolov8BaseConfig(object):
  101. def __init__(self) -> None:
  102. # ---------------- Model config ----------------
  103. self.width = 0.50
  104. self.depth = 0.34
  105. self.ratio = 2.0
  106. self.out_stride = [8, 16, 32]
  107. self.max_stride = 32
  108. self.num_levels = 3
  109. ## FPN
  110. self.fpn_act = 'silu'
  111. self.fpn_norm = 'BN'
  112. self.fpn_depthwise = False
  113. ## Head
  114. self.head_dim = 256
  115. cfg = Yolov8BaseConfig()
  116. # Build a head
  117. in_dims = [128, 256, 512]
  118. fpn = Yolov8PaFPN(cfg, in_dims)
  119. # Inference
  120. x = [torch.randn(1, in_dims[0], 80, 80),
  121. torch.randn(1, in_dims[1], 40, 40),
  122. torch.randn(1, in_dims[2], 20, 20)]
  123. t0 = time.time()
  124. output = fpn(x)
  125. t1 = time.time()
  126. print('Time: ', t1 - t0)
  127. print('====== FPN output ====== ')
  128. for level, feat in enumerate(output):
  129. print("- Level-{} : ".format(level), feat.shape)
  130. flops, params = profile(fpn, inputs=(x, ), verbose=False)
  131. print('==============================')
  132. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  133. print('Params : {:.2f} M'.format(params / 1e6))