yolov6_pafpn.py 6.0 KB

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