FCE_Fpn.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is refer from:
  16. https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.3/ppdet/modeling/necks/fpn.py
  17. """
  18. import torch.nn as nn
  19. import torch.nn.functional as F
  20. __all__ = ['FCEFPN']
  21. class FCEFPN(nn.Module):
  22. def __init__(self,
  23. in_channels,
  24. out_channels,
  25. use_c5=True,
  26. ):
  27. super(FCEFPN, self).__init__()
  28. self.out_channels = out_channels
  29. self.use_c5 = use_c5
  30. self.lateral_convs = nn.ModuleList()
  31. self.fpn_convs =nn.ModuleList()
  32. # stage index 0,1,2,3 stands for res2,res3,res4,res5 on ResNet Backbone
  33. # 0 <= st_stage < ed_stage <= 3
  34. st_stage = 4 - len(in_channels)
  35. ed_stage = st_stage + len(in_channels) - 1
  36. for i in range(st_stage, ed_stage + 1):
  37. in_c = in_channels[i - st_stage]
  38. self.lateral_convs.append( nn.Conv2d(
  39. in_channels=in_c,
  40. out_channels=out_channels,
  41. kernel_size=1))
  42. for i in range(st_stage, ed_stage + 1):
  43. self.fpn_convs.append(nn.Conv2d(
  44. in_channels=out_channels,
  45. out_channels=out_channels,
  46. kernel_size=3,
  47. padding=1))
  48. # add extra conv levels for RetinaNet(use_c5)/FCOS(use_p5)
  49. def forward(self, body_feats):
  50. laterals = []
  51. num_levels = len(body_feats)
  52. for i in range(num_levels):
  53. laterals.append(self.lateral_convs[i](body_feats[i]))
  54. for i in range(1, num_levels):
  55. lvl = num_levels - i
  56. upsample = F.interpolate(
  57. laterals[lvl],
  58. scale_factor=2.,
  59. mode='nearest')
  60. laterals[lvl - 1] += upsample
  61. fpn_output = []
  62. for lvl in range(num_levels):
  63. fpn_output.append(self.fpn_convs[lvl](laterals[lvl]))
  64. return fpn_output