gelan_pafpn.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from typing import List
  5. try:
  6. from .gelan_basic import RepGElanLayer, ADown
  7. except:
  8. from gelan_basic import RepGElanLayer, ADown
  9. # PaFPN-ELAN
  10. class GElanPaFPN(nn.Module):
  11. def __init__(self,
  12. cfg,
  13. in_dims :List = [256, 512, 256],
  14. ) -> None:
  15. super(GElanPaFPN, self).__init__()
  16. print('==============================')
  17. print('FPN: {}'.format("GELAN PaFPN"))
  18. # --------------------------- Basic Parameters ---------------------------
  19. self.in_dims = in_dims[::-1]
  20. self.out_dims = [cfg.fpn_feats_td["p3"][1], cfg.fpn_feats_bu["p4"][1], cfg.fpn_feats_bu["p5"][1]]
  21. # ---------------- Top dwon ----------------
  22. ## P5 -> P4
  23. self.top_down_layer_1 = RepGElanLayer(in_dim = self.in_dims[0] + self.in_dims[1],
  24. inter_dims = cfg.fpn_feats_td["p4"][0],
  25. out_dim = cfg.fpn_feats_td["p4"][1],
  26. num_blocks = cfg.fpn_depth,
  27. shortcut = False,
  28. act_type = cfg.fpn_act,
  29. norm_type = cfg.fpn_norm,
  30. depthwise = cfg.fpn_depthwise,
  31. )
  32. ## P4 -> P3
  33. self.top_down_layer_2 = RepGElanLayer(in_dim = cfg.fpn_feats_td["p4"][1] + self.in_dims[2],
  34. inter_dims = cfg.fpn_feats_td["p3"][0],
  35. out_dim = cfg.fpn_feats_td["p3"][1],
  36. num_blocks = cfg.fpn_depth,
  37. shortcut = False,
  38. act_type = cfg.fpn_act,
  39. norm_type = cfg.fpn_norm,
  40. depthwise = cfg.fpn_depthwise,
  41. )
  42. # ---------------- Bottom up ----------------
  43. ## P3 -> P4
  44. self.dowmsample_layer_1 = ADown(cfg.fpn_feats_td["p3"][1], cfg.fpn_feats_td["p3"][1],
  45. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  46. self.bottom_up_layer_1 = RepGElanLayer(in_dim = cfg.fpn_feats_td["p3"][1] + cfg.fpn_feats_td["p4"][1],
  47. inter_dims = cfg.fpn_feats_bu["p4"][0],
  48. out_dim = cfg.fpn_feats_bu["p4"][1],
  49. num_blocks = cfg.fpn_depth,
  50. shortcut = False,
  51. act_type = cfg.fpn_act,
  52. norm_type = cfg.fpn_norm,
  53. depthwise = cfg.fpn_depthwise,
  54. )
  55. ## P4 -> P5
  56. self.dowmsample_layer_2 = ADown(cfg.fpn_feats_bu["p4"][1], cfg.fpn_feats_bu["p4"][1],
  57. act_type=cfg.fpn_act, norm_type=cfg.fpn_norm, depthwise=cfg.fpn_depthwise)
  58. self.bottom_up_layer_2 = RepGElanLayer(in_dim = cfg.fpn_feats_td["p4"][1] + self.in_dims[0],
  59. inter_dims = cfg.fpn_feats_bu["p5"][0],
  60. out_dim = cfg.fpn_feats_bu["p5"][1],
  61. num_blocks = cfg.fpn_depth,
  62. shortcut = False,
  63. act_type = cfg.fpn_act,
  64. norm_type = cfg.fpn_norm,
  65. depthwise = cfg.fpn_depthwise,
  66. )
  67. self.init_weights()
  68. def init_weights(self):
  69. """Initialize the parameters."""
  70. for m in self.modules():
  71. if isinstance(m, torch.nn.Conv2d):
  72. # In order to be consistent with the source code,
  73. # reset the Conv2d initialization parameters
  74. m.reset_parameters()
  75. def forward(self, features):
  76. c3, c4, c5 = features
  77. # ------------------ Top down FPN ------------------
  78. ## P5 -> P4
  79. p5_up = F.interpolate(c5, scale_factor=2.0)
  80. p4 = self.top_down_layer_1(torch.cat([p5_up, c4], dim=1))
  81. ## P4 -> P3
  82. p4_up = F.interpolate(p4, scale_factor=2.0)
  83. p3 = self.top_down_layer_2(torch.cat([p4_up, c3], dim=1))
  84. # ------------------ Bottom up FPN ------------------
  85. ## p3 -> P4
  86. p3_ds = self.dowmsample_layer_1(p3)
  87. p4 = self.bottom_up_layer_1(torch.cat([p3_ds, p4], dim=1))
  88. ## P4 -> 5
  89. p4_ds = self.dowmsample_layer_2(p4)
  90. p5 = self.bottom_up_layer_2(torch.cat([p4_ds, c5], dim=1))
  91. out_feats = [p3, p4, p5] # [P3, P4, P5]
  92. return out_feats
  93. if __name__=='__main__':
  94. import time
  95. from thop import profile
  96. # Model config
  97. # GElan-Base config
  98. class GElanBaseConfig(object):
  99. def __init__(self) -> None:
  100. # ---------------- Model config ----------------
  101. self.width = 0.50
  102. self.depth = 0.34
  103. self.ratio = 2.0
  104. self.out_stride = [8, 16, 32]
  105. self.max_stride = 32
  106. self.num_levels = 3
  107. ## FPN
  108. self.fpn = 'gelan_pafpn'
  109. self.fpn_act = 'silu'
  110. self.fpn_norm = 'BN'
  111. self.fpn_depthwise = False
  112. self.fpn_depth = 3
  113. self.fpn_feats_td = {
  114. "p4": [[256, 128], 256],
  115. "p3": [[128, 64], 128],
  116. }
  117. self.fpn_feats_bu = {
  118. "p4": [[256, 128], 256],
  119. "p5": [[256, 128], 256],
  120. }
  121. cfg = GElanBaseConfig()
  122. # Build a head
  123. in_dims = [128, 256, 256]
  124. fpn = GElanPaFPN(cfg, in_dims)
  125. # Inference
  126. x = [torch.randn(1, in_dims[0], 80, 80),
  127. torch.randn(1, in_dims[1], 40, 40),
  128. torch.randn(1, in_dims[2], 20, 20)]
  129. t0 = time.time()
  130. output = fpn(x)
  131. t1 = time.time()
  132. print('Time: ', t1 - t0)
  133. print('====== FPN output ====== ')
  134. for level, feat in enumerate(output):
  135. print("- Level-{} : ".format(level), feat.shape)
  136. flops, params = profile(fpn, inputs=(x, ), verbose=False)
  137. print('==============================')
  138. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  139. print('Params : {:.2f} M'.format(params / 1e6))