yolov3_fpn.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 .yolov3_basic import BasicConv, ResBlock
  7. except:
  8. from yolov3_basic import BasicConv, ResBlock
  9. # Yolov3FPN
  10. class Yolov3FPN(nn.Module):
  11. def __init__(self, cfg, in_dims: List = [256, 512, 1024],
  12. ):
  13. super(Yolov3FPN, self).__init__()
  14. self.in_dims = in_dims
  15. c3, c4, c5 = in_dims
  16. # ---------------------- Yolov3's Top down FPN ----------------------
  17. ## P5 -> P4
  18. self.top_down_layer_1 = ResBlock(in_dim = c5,
  19. out_dim = round(512*cfg.width),
  20. num_blocks = round(3*cfg.depth),
  21. expansion = 0.5,
  22. shortcut = False,
  23. act_type = cfg.fpn_act,
  24. norm_type = cfg.fpn_norm,
  25. depthwise = cfg.fpn_depthwise)
  26. self.reduce_layer_1 = BasicConv(round(512*cfg.width), round(256*cfg.width),
  27. kernel_size=1, padding=0, stride=1,
  28. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  29. ## P4 -> P3
  30. self.top_down_layer_2 = ResBlock(in_dim = c4 + round(256*cfg.width),
  31. out_dim = round(256*cfg.width),
  32. num_blocks = round(3*cfg.depth),
  33. expansion = 0.5,
  34. shortcut = False,
  35. act_type = cfg.fpn_act,
  36. norm_type = cfg.fpn_norm,
  37. depthwise = cfg.fpn_depthwise)
  38. self.reduce_layer_2 = BasicConv(round(256*cfg.width), round(128*cfg.width),
  39. kernel_size=1, padding=0, stride=1,
  40. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  41. ## P3
  42. self.top_down_layer_3 = ResBlock(in_dim = c3 + round(128*cfg.width),
  43. out_dim = round(128*cfg.width),
  44. num_blocks = round(3*cfg.depth),
  45. expansion = 0.5,
  46. shortcut = False,
  47. act_type = cfg.fpn_act,
  48. norm_type = cfg.fpn_norm,
  49. depthwise = cfg.fpn_depthwise)
  50. # ---------------------- Yolov3's output projection ----------------------
  51. self.out_layers = nn.ModuleList([
  52. BasicConv(in_dim, round(cfg.head_dim*cfg.width), kernel_size=1,
  53. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm)
  54. for in_dim in [round(128*cfg.width), round(256*cfg.width), round(512*cfg.width)]
  55. ])
  56. self.out_dims = [round(cfg.head_dim*cfg.width)] * 3
  57. # Initialize all layers
  58. self.init_weights()
  59. def init_weights(self):
  60. """Initialize the parameters."""
  61. for m in self.modules():
  62. if isinstance(m, torch.nn.Conv2d):
  63. # In order to be consistent with the source code,
  64. # reset the Conv2d initialization parameters
  65. m.reset_parameters()
  66. def forward(self, features):
  67. c3, c4, c5 = features
  68. # p5/32
  69. p5 = self.top_down_layer_1(c5)
  70. # p4/16
  71. p5_up = F.interpolate(self.reduce_layer_1(p5), scale_factor=2.0)
  72. p4 = self.top_down_layer_2(torch.cat([c4, p5_up], dim=1))
  73. # P3/8
  74. p4_up = F.interpolate(self.reduce_layer_2(p4), scale_factor=2.0)
  75. p3 = self.top_down_layer_3(torch.cat([c3, p4_up], dim=1))
  76. out_feats = [p3, p4, p5]
  77. # output proj layers
  78. out_feats_proj = []
  79. for feat, layer in zip(out_feats, self.out_layers):
  80. out_feats_proj.append(layer(feat))
  81. return out_feats_proj
  82. if __name__=='__main__':
  83. import time
  84. from thop import profile
  85. # Model config
  86. # YOLOv2-Base config
  87. class Yolov3BaseConfig(object):
  88. def __init__(self) -> None:
  89. # ---------------- Model config ----------------
  90. self.width = 0.50
  91. self.depth = 0.34
  92. self.out_stride = [8, 16, 32]
  93. self.max_stride = 32
  94. self.num_levels = 3
  95. ## FPN
  96. self.fpn_act = 'silu'
  97. self.fpn_norm = 'BN'
  98. self.fpn_depthwise = False
  99. ## Head
  100. self.head_dim = 256
  101. cfg = Yolov3BaseConfig()
  102. # Build a head
  103. in_dims = [128, 256, 512]
  104. fpn = Yolov3FPN(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))