yolox_pafpn.py 5.5 KB

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