rtcdet_pafpn.py 7.2 KB

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