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