yolov3_fpn.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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, ResBlock
  7. except:
  8. from modules import ConvModule, 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.reduce_layer_1 = ConvModule(round(512*cfg.width), round(256*cfg.width), kernel_size=1, padding=0, stride=1)
  19. self.top_down_layer_1 = ResBlock(in_dim = c5,
  20. out_dim = round(512*cfg.width),
  21. num_blocks = round(3*cfg.depth),
  22. expansion = 0.5,
  23. shortcut = False,
  24. )
  25. ## P4 -> P3
  26. self.reduce_layer_2 = ConvModule(round(256*cfg.width), round(128*cfg.width), kernel_size=1, padding=0, stride=1)
  27. self.top_down_layer_2 = ResBlock(in_dim = c4 + round(256*cfg.width),
  28. out_dim = round(256*cfg.width),
  29. num_blocks = round(3*cfg.depth),
  30. expansion = 0.5,
  31. shortcut = False,
  32. )
  33. ## P3
  34. self.top_down_layer_3 = ResBlock(in_dim = c3 + round(128*cfg.width),
  35. out_dim = round(128*cfg.width),
  36. num_blocks = round(3*cfg.depth),
  37. expansion = 0.5,
  38. shortcut = False,
  39. )
  40. # ---------------------- Yolov3's output projection ----------------------
  41. self.out_layers = nn.ModuleList([
  42. ConvModule(in_dim, round(cfg.head_dim*cfg.width), kernel_size=1)
  43. for in_dim in [round(128*cfg.width), round(256*cfg.width), round(512*cfg.width)]
  44. ])
  45. self.out_dims = [round(cfg.head_dim*cfg.width)] * 3
  46. # Initialize all layers
  47. self.init_weights()
  48. def init_weights(self):
  49. """Initialize the parameters."""
  50. for m in self.modules():
  51. if isinstance(m, torch.nn.Conv2d):
  52. m.reset_parameters()
  53. def forward(self, features):
  54. c3, c4, c5 = features
  55. # p5/32
  56. p5 = self.top_down_layer_1(c5)
  57. # p4/16
  58. p5_up = F.interpolate(self.reduce_layer_1(p5), scale_factor=2.0)
  59. p4 = self.top_down_layer_2(torch.cat([c4, p5_up], dim=1))
  60. # P3/8
  61. p4_up = F.interpolate(self.reduce_layer_2(p4), scale_factor=2.0)
  62. p3 = self.top_down_layer_3(torch.cat([c3, p4_up], dim=1))
  63. out_feats = [p3, p4, p5]
  64. # output proj layers
  65. out_feats_proj = []
  66. for feat, layer in zip(out_feats, self.out_layers):
  67. out_feats_proj.append(layer(feat))
  68. return out_feats_proj
  69. if __name__=='__main__':
  70. import time
  71. from thop import profile
  72. # Model config
  73. # YOLOv2-Base config
  74. class Yolov3BaseConfig(object):
  75. def __init__(self) -> None:
  76. # ---------------- Model config ----------------
  77. self.width = 0.50
  78. self.depth = 0.34
  79. self.out_stride = [8, 16, 32]
  80. self.max_stride = 32
  81. self.num_levels = 3
  82. ## Head
  83. self.head_dim = 256
  84. cfg = Yolov3BaseConfig()
  85. # Build a head
  86. in_dims = [128, 256, 512]
  87. fpn = Yolov3FPN(cfg, in_dims)
  88. # Inference
  89. x = [torch.randn(1, in_dims[0], 80, 80),
  90. torch.randn(1, in_dims[1], 40, 40),
  91. torch.randn(1, in_dims[2], 20, 20)]
  92. t0 = time.time()
  93. output = fpn(x)
  94. t1 = time.time()
  95. print('Time: ', t1 - t0)
  96. print('====== FPN output ====== ')
  97. for level, feat in enumerate(output):
  98. print("- Level-{} : ".format(level), feat.shape)
  99. flops, params = profile(fpn, inputs=(x, ), verbose=False)
  100. print('==============================')
  101. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  102. print('Params : {:.2f} M'.format(params / 1e6))