yolov10_pafpn.py 5.6 KB

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