yolov8_pafpn.py 4.9 KB

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