rtcdet_pafpn.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. try:
  5. from .rtcdet_basic import Conv, RTCBlock
  6. except:
  7. from rtcdet_basic import Conv, RTCBlock
  8. # PaFPN of RTCDet
  9. class RTCDetPaFPN(nn.Module):
  10. def __init__(self,
  11. in_dims = [256, 512, 512],
  12. out_dim = None,
  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(RTCDetPaFPN, self).__init__()
  20. print('==============================')
  21. print('FPN: {}'.format("RTCDet 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 ----------------
  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 ----------------
  47. ## P3 -> P4
  48. self.dowmsample_layer_1 = Conv(round(256*width), round(256*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  49. self.bottom_up_layer_1 = RTCBlock(in_dim = round(256*width) + round(512*width),
  50. out_dim = round(512*width),
  51. num_blocks = round(3*depth),
  52. shortcut = False,
  53. act_type = act_type,
  54. norm_type = norm_type,
  55. depthwise = depthwise,
  56. )
  57. ## P4 -> P5
  58. self.dowmsample_layer_2 = Conv(round(512*width), round(512*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  59. self.bottom_up_layer_2 = RTCBlock(in_dim = round(512 * width) + c5,
  60. out_dim = round(512 * width * ratio),
  61. num_blocks = round(3*depth),
  62. shortcut = False,
  63. act_type = act_type,
  64. norm_type = norm_type,
  65. depthwise = depthwise,
  66. )
  67. ## output proj layers
  68. if out_dim is not None:
  69. self.out_layers = nn.ModuleList([
  70. Conv(in_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  71. for in_dim in [round(256*width), round(512*width), round(512 * width * ratio)]
  72. ])
  73. self.out_dim = [out_dim] * 3
  74. else:
  75. self.out_layers = None
  76. self.out_dim = [round(256*width), round(512*width), round(512 * width * ratio)]
  77. self.init_weights()
  78. def init_weights(self):
  79. """Initialize the parameters."""
  80. for m in self.modules():
  81. if isinstance(m, torch.nn.Conv2d):
  82. # In order to be consistent with the source code,
  83. # reset the Conv2d initialization parameters
  84. m.reset_parameters()
  85. def forward(self, features):
  86. c3, c4, c5 = features
  87. # Top down
  88. ## P5 -> P4
  89. c6 = F.interpolate(c5, scale_factor=2.0)
  90. c7 = torch.cat([c6, c4], dim=1)
  91. c8 = self.top_down_layer_1(c7)
  92. ## P4 -> P3
  93. c9 = F.interpolate(c8, scale_factor=2.0)
  94. c10 = torch.cat([c9, c3], dim=1)
  95. c11 = self.top_down_layer_2(c10)
  96. # Bottom up
  97. # p3 -> P4
  98. c12 = self.dowmsample_layer_1(c11)
  99. c13 = torch.cat([c12, c8], dim=1)
  100. c14 = self.bottom_up_layer_1(c13)
  101. # P4 -> P5
  102. c15 = self.dowmsample_layer_2(c14)
  103. c16 = torch.cat([c15, c5], dim=1)
  104. c17 = self.bottom_up_layer_2(c16)
  105. out_feats = [c11, c14, c17] # [P3, P4, P5]
  106. # output proj layers
  107. if self.out_layers is not None:
  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. return out_feats
  113. def build_fpn(cfg, in_dims, out_dim=None):
  114. model = cfg['fpn']
  115. # build neck
  116. if model == 'rtcdet_pafpn':
  117. fpn_net = RTCDetPaFPN(in_dims = in_dims,
  118. out_dim = out_dim,
  119. width = cfg['width'],
  120. depth = cfg['depth'],
  121. ratio = cfg['ratio'],
  122. act_type = cfg['fpn_act'],
  123. norm_type = cfg['fpn_norm'],
  124. depthwise = cfg['fpn_depthwise']
  125. )
  126. else:
  127. raise NotImplementedError
  128. return fpn_net
  129. if __name__ == '__main__':
  130. import time
  131. from thop import profile
  132. cfg = {
  133. 'fpn': 'rtcdet_pafpn',
  134. 'fpn_act': 'silu',
  135. 'fpn_norm': 'BN',
  136. 'fpn_depthwise': False,
  137. 'width': 1.0,
  138. 'depth': 1.0,
  139. 'ratio': 1.0
  140. }
  141. fpn_dims = [256, 512, 512]
  142. out_dim=256
  143. model = build_fpn(cfg, fpn_dims, out_dim)
  144. pyramid_feats = [torch.randn(1, fpn_dims[0], 80, 80), torch.randn(1, fpn_dims[1], 40, 40), torch.randn(1, fpn_dims[2], 20, 20)]
  145. t0 = time.time()
  146. outputs = model(pyramid_feats)
  147. t1 = time.time()
  148. print('Time: ', t1 - t0)
  149. for out in outputs:
  150. print(out.shape)
  151. print('==============================')
  152. flops, params = profile(model, inputs=(pyramid_feats, ), verbose=False)
  153. print('==============================')
  154. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  155. print('Params : {:.2f} M'.format(params / 1e6))