yolov8_pafpn.py 5.0 KB

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