yolo11_pafpn.py 5.3 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, C3k2fBlock
  7. except:
  8. from modules import ConvModule, C3k2fBlock
  9. class Yolo11PaFPN(nn.Module):
  10. def __init__(self, cfg, in_dims :List = [256, 512, 1024]):
  11. super(Yolo11PaFPN, self).__init__()
  12. # --------------------------- Basic Parameters ---------------------------
  13. self.model_scale = cfg.model_scale
  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. # ----------------------------- Yolo11's Top-down FPN -----------------------------
  17. ## P5 -> P4
  18. self.top_down_layer_1 = C3k2fBlock(in_dim = self.in_dims[0] + self.in_dims[1],
  19. out_dim = round(512*cfg.width),
  20. num_blocks = round(2 * cfg.depth),
  21. shortcut = True,
  22. expansion = 0.5,
  23. use_c3k = False if self.model_scale in "ns" else True,
  24. )
  25. ## P4 -> P3
  26. self.top_down_layer_2 = C3k2fBlock(in_dim = self.in_dims[2] + round(512*cfg.width),
  27. out_dim = round(256*cfg.width),
  28. num_blocks = round(2 * cfg.depth),
  29. shortcut = True,
  30. expansion = 0.5,
  31. use_c3k = False if self.model_scale in "ns" else True,
  32. )
  33. # ----------------------------- Yolo11's Bottom-up PAN -----------------------------
  34. ## P3 -> P4
  35. self.dowmsample_layer_1 = ConvModule(round(256*cfg.width), round(256*cfg.width), kernel_size=3, stride=2)
  36. self.bottom_up_layer_1 = C3k2fBlock(in_dim = round(256*cfg.width) + round(512*cfg.width),
  37. out_dim = round(512*cfg.width),
  38. num_blocks = round(2 * cfg.depth),
  39. shortcut = True,
  40. expansion = 0.5,
  41. use_c3k = False if self.model_scale in "ns" else True,
  42. )
  43. ## P4 -> P5
  44. self.dowmsample_layer_2 = ConvModule(round(512*cfg.width), round(512*cfg.width), kernel_size=3, stride=2)
  45. self.bottom_up_layer_2 = C3k2fBlock(in_dim = round(512*cfg.width) + self.in_dims[0],
  46. out_dim = round(512*cfg.width*cfg.ratio),
  47. num_blocks = round(2 * cfg.depth),
  48. shortcut = True,
  49. expansion = 0.5,
  50. use_c3k = True,
  51. )
  52. self.init_weights()
  53. def init_weights(self):
  54. """Initialize the parameters."""
  55. for m in self.modules():
  56. if isinstance(m, torch.nn.Conv2d):
  57. m.reset_parameters()
  58. def forward(self, features):
  59. c3, c4, c5 = features
  60. # ------------------ Top down FPN ------------------
  61. ## P5 -> P4
  62. p5_up = F.interpolate(c5, scale_factor=2.0)
  63. p4 = self.top_down_layer_1(torch.cat([p5_up, c4], dim=1))
  64. ## P4 -> P3
  65. p4_up = F.interpolate(p4, scale_factor=2.0)
  66. p3 = self.top_down_layer_2(torch.cat([p4_up, c3], dim=1))
  67. # ------------------ Bottom up FPN ------------------
  68. ## p3 -> P4
  69. p3_ds = self.dowmsample_layer_1(p3)
  70. p4 = self.bottom_up_layer_1(torch.cat([p3_ds, p4], dim=1))
  71. ## P4 -> 5
  72. p4_ds = self.dowmsample_layer_2(p4)
  73. p5 = self.bottom_up_layer_2(torch.cat([p4_ds, c5], dim=1))
  74. out_feats = [p3, p4, p5] # [P3, P4, P5]
  75. return out_feats
  76. if __name__=='__main__':
  77. import time
  78. from thop import profile
  79. # Model config
  80. # YOLOv8-Base config
  81. class Yolov8BaseConfig(object):
  82. def __init__(self) -> None:
  83. # ---------------- Model config ----------------
  84. self.width = 0.50
  85. self.depth = 0.34
  86. self.ratio = 2.0
  87. self.out_stride = [8, 16, 32]
  88. self.max_stride = 32
  89. self.model_scale = "s"
  90. cfg = Yolov8BaseConfig()
  91. # Build a head
  92. in_dims = [128, 256, 512]
  93. fpn = Yolo11PaFPN(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))