yolov5_pafpn.py 7.1 KB

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