rtcdet_pafpn.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. try:
  5. from .rtcdet_basic import BasicConv, RTCBlock
  6. except:
  7. from rtcdet_basic import BasicConv, RTCBlock
  8. # PaFPN-ELAN
  9. class RTCPaFPN(nn.Module):
  10. def __init__(self,
  11. in_dims = [256, 512, 512],
  12. out_dim = 256,
  13. width = 1.0,
  14. depth = 1.0,
  15. ratio = 1.0,
  16. act_type = 'silu',
  17. norm_type = 'BN',
  18. depthwise = False):
  19. super(RTCPaFPN, self).__init__()
  20. print('==============================')
  21. print('FPN: {}'.format("RTC PaFPN"))
  22. # ---------------- Basic parameters ----------------
  23. self.in_dims = in_dims
  24. self.width = width
  25. self.depth = depth
  26. c3, c4, c5 = in_dims
  27. # ---------------- Top dwon FPN----------------
  28. ## P5 -> P4
  29. self.top_down_layer_1 = RTCBlock(in_dim = c5 + c4,
  30. out_dim = round(512*width),
  31. num_blocks = round(3*depth),
  32. shortcut = False,
  33. act_type = act_type,
  34. norm_type = norm_type,
  35. depthwise = depthwise,
  36. )
  37. ## P4 -> P3
  38. self.top_down_layer_2 = RTCBlock(in_dim = round(512*width) + c3,
  39. out_dim = round(256*width),
  40. num_blocks = round(3*depth),
  41. shortcut = False,
  42. act_type = act_type,
  43. norm_type = norm_type,
  44. depthwise = depthwise,
  45. )
  46. # ---------------- Bottom up PAN----------------
  47. ## P3 -> P4
  48. self.dowmsample_layer_1 = BasicConv(round(256*width), round(256*width),
  49. kernel_size=3, padding=1, stride=2,
  50. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  51. self.bottom_up_layer_1 = RTCBlock(in_dim = round(256*width) + round(512*width),
  52. out_dim = round(512*width),
  53. num_blocks = round(3*depth),
  54. shortcut = False,
  55. act_type = act_type,
  56. norm_type = norm_type,
  57. depthwise = depthwise,
  58. )
  59. ## P4 -> P5
  60. self.dowmsample_layer_2 = BasicConv(round(512*width), round(512*width),
  61. kernel_size=3, padding=1, stride=2,
  62. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  63. self.bottom_up_layer_2 = RTCBlock(in_dim = round(512 * width) + c5,
  64. out_dim = round(512 * width * ratio),
  65. num_blocks = round(3*depth),
  66. shortcut = False,
  67. act_type = act_type,
  68. norm_type = norm_type,
  69. depthwise = depthwise,
  70. )
  71. # ---------------- Output projection ----------------
  72. ## Output projs
  73. self.out_layers = nn.ModuleList([
  74. BasicConv(in_dim, out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  75. for in_dim in [round(256*width), round(512*width), round(512*width * ratio)]
  76. ])
  77. self.out_dims = [out_dim] * 3
  78. self.init_weights()
  79. def init_weights(self):
  80. """Initialize the parameters."""
  81. for m in self.modules():
  82. if isinstance(m, torch.nn.Conv2d):
  83. # In order to be consistent with the source code,
  84. # reset the Conv2d initialization parameters
  85. m.reset_parameters()
  86. def forward(self, features):
  87. c3, c4, c5 = features
  88. # Top down
  89. ## P5 -> P4
  90. c6 = F.interpolate(c5, scale_factor=2.0)
  91. c7 = torch.cat([c6, c4], dim=1)
  92. c8 = self.top_down_layer_1(c7)
  93. ## P4 -> P3
  94. c9 = F.interpolate(c8, scale_factor=2.0)
  95. c10 = torch.cat([c9, c3], dim=1)
  96. c11 = self.top_down_layer_2(c10)
  97. # Bottom up
  98. # p3 -> P4
  99. c12 = self.dowmsample_layer_1(c11)
  100. c13 = torch.cat([c12, c8], dim=1)
  101. c14 = self.bottom_up_layer_1(c13)
  102. # P4 -> P5
  103. c15 = self.dowmsample_layer_2(c14)
  104. c16 = torch.cat([c15, c5], dim=1)
  105. c17 = self.bottom_up_layer_2(c16)
  106. out_feats = [c11, c14, c17] # [P3, P4, P5]
  107. # output proj layers
  108. out_feats_proj = []
  109. for feat, layer in zip(out_feats, self.out_layers):
  110. out_feats_proj.append(layer(feat))
  111. return out_feats_proj
  112. def build_fpn(cfg, in_dims, out_dim):
  113. # build neck
  114. if cfg['fpn'] == 'rtc_pafpn':
  115. fpn_net = RTCPaFPN(in_dims = in_dims,
  116. out_dim = out_dim,
  117. width = cfg['width'],
  118. depth = cfg['depth'],
  119. ratio = cfg['ratio'],
  120. act_type = cfg['fpn_act'],
  121. norm_type = cfg['fpn_norm'],
  122. depthwise = cfg['fpn_depthwise']
  123. )
  124. else:
  125. raise NotImplementedError("Unknown fpn: {}".format(cfg['fpn']))
  126. return fpn_net
  127. if __name__ == '__main__':
  128. import time
  129. from thop import profile
  130. cfg = {
  131. 'fpn': 'rtc_pafpn',
  132. 'fpn_act': 'silu',
  133. 'fpn_norm': 'BN',
  134. 'fpn_depthwise': False,
  135. 'width': 1.0,
  136. 'depth': 1.0,
  137. 'ratio': 1.0,
  138. }
  139. model = build_fpn(cfg, in_dims=[256, 512, 512], out_dim=256)
  140. pyramid_feats = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 512, 20, 20)]
  141. t0 = time.time()
  142. outputs = model(pyramid_feats)
  143. t1 = time.time()
  144. print('Time: ', t1 - t0)
  145. for out in outputs:
  146. print(out.shape)
  147. print('==============================')
  148. flops, params = profile(model, inputs=(pyramid_feats, ), verbose=False)
  149. print('==============================')
  150. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  151. print('Params : {:.2f} M'.format(params / 1e6))