yolov5_af_pafpn.py 7.1 KB

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