fpn.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from collections import OrderedDict
  18. import copy
  19. from paddle import fluid
  20. from paddle.fluid.param_attr import ParamAttr
  21. from paddle.fluid.initializer import Xavier
  22. from paddle.fluid.regularizer import L2Decay
  23. from ppdet.core.workspace import register
  24. from ppdet.modeling.ops import ConvNorm
  25. __all__ = ['FPN']
  26. @register
  27. class FPN(object):
  28. """
  29. Feature Pyramid Network, see https://arxiv.org/abs/1612.03144
  30. Args:
  31. num_chan (int): number of feature channels
  32. min_level (int): lowest level of the backbone feature map to use
  33. max_level (int): highest level of the backbone feature map to use
  34. spatial_scale (list): feature map scaling factor
  35. has_extra_convs (bool): whether has extral convolutions in higher levels
  36. norm_type (str|None): normalization type, 'bn'/'sync_bn'/'affine_channel'
  37. norm_decay (float): weight decay for normalization layer weights.
  38. reverse_out (bool): whether to flip the output.
  39. """
  40. __shared__ = ['norm_type', 'freeze_norm']
  41. def __init__(self,
  42. num_chan=256,
  43. min_level=2,
  44. max_level=6,
  45. spatial_scale=[1. / 32., 1. / 16., 1. / 8., 1. / 4.],
  46. has_extra_convs=False,
  47. norm_type=None,
  48. norm_decay=0.,
  49. freeze_norm=False,
  50. use_c5=True,
  51. reverse_out=False):
  52. self.freeze_norm = freeze_norm
  53. self.num_chan = num_chan
  54. self.min_level = min_level
  55. self.max_level = max_level
  56. self.spatial_scale = spatial_scale
  57. self.has_extra_convs = has_extra_convs
  58. self.norm_type = norm_type
  59. self.norm_decay = norm_decay
  60. self.use_c5 = use_c5
  61. self.reverse_out = reverse_out
  62. def _add_topdown_lateral(self, body_name, body_input, upper_output):
  63. lateral_name = 'fpn_inner_' + body_name + '_lateral'
  64. topdown_name = 'fpn_topdown_' + body_name
  65. fan = body_input.shape[1]
  66. if self.norm_type:
  67. initializer = Xavier(fan_out=fan)
  68. lateral = ConvNorm(
  69. body_input,
  70. self.num_chan,
  71. 1,
  72. initializer=initializer,
  73. norm_type=self.norm_type,
  74. norm_decay=self.norm_decay,
  75. freeze_norm=self.freeze_norm,
  76. name=lateral_name,
  77. norm_name=lateral_name)
  78. else:
  79. lateral = fluid.layers.conv2d(
  80. body_input,
  81. self.num_chan,
  82. 1,
  83. param_attr=ParamAttr(
  84. name=lateral_name + "_w", initializer=Xavier(fan_out=fan)),
  85. bias_attr=ParamAttr(
  86. name=lateral_name + "_b",
  87. learning_rate=2.,
  88. regularizer=L2Decay(0.)),
  89. name=lateral_name)
  90. if body_input.shape[2] == -1 and body_input.shape[3] == -1:
  91. topdown = fluid.layers.resize_nearest(
  92. upper_output, scale=2., name=topdown_name)
  93. else:
  94. topdown = fluid.layers.resize_nearest(
  95. upper_output,
  96. out_shape=[body_input.shape[2], body_input.shape[3]],
  97. name=topdown_name)
  98. return fluid.layers.elementwise_add(lateral, topdown)
  99. def get_output(self, body_dict):
  100. """
  101. Add FPN onto backbone.
  102. Args:
  103. body_dict(OrderedDict): Dictionary of variables and each element is the
  104. output of backbone.
  105. Return:
  106. fpn_dict(OrderedDict): A dictionary represents the output of FPN with
  107. their name.
  108. spatial_scale(list): A list of multiplicative spatial scale factor.
  109. """
  110. spatial_scale = copy.deepcopy(self.spatial_scale)
  111. body_name_list = list(body_dict.keys())[::-1]
  112. num_backbone_stages = len(body_name_list)
  113. self.fpn_inner_output = [[] for _ in range(num_backbone_stages)]
  114. fpn_inner_name = 'fpn_inner_' + body_name_list[0]
  115. body_input = body_dict[body_name_list[0]]
  116. fan = body_input.shape[1]
  117. if self.norm_type:
  118. initializer = Xavier(fan_out=fan)
  119. self.fpn_inner_output[0] = ConvNorm(
  120. body_input,
  121. self.num_chan,
  122. 1,
  123. initializer=initializer,
  124. norm_type=self.norm_type,
  125. norm_decay=self.norm_decay,
  126. freeze_norm=self.freeze_norm,
  127. name=fpn_inner_name,
  128. norm_name=fpn_inner_name)
  129. else:
  130. self.fpn_inner_output[0] = fluid.layers.conv2d(
  131. body_input,
  132. self.num_chan,
  133. 1,
  134. param_attr=ParamAttr(
  135. name=fpn_inner_name + "_w",
  136. initializer=Xavier(fan_out=fan)),
  137. bias_attr=ParamAttr(
  138. name=fpn_inner_name + "_b",
  139. learning_rate=2.,
  140. regularizer=L2Decay(0.)),
  141. name=fpn_inner_name)
  142. for i in range(1, num_backbone_stages):
  143. body_name = body_name_list[i]
  144. body_input = body_dict[body_name]
  145. top_output = self.fpn_inner_output[i - 1]
  146. fpn_inner_single = self._add_topdown_lateral(body_name, body_input,
  147. top_output)
  148. self.fpn_inner_output[i] = fpn_inner_single
  149. fpn_dict = {}
  150. fpn_name_list = []
  151. for i in range(num_backbone_stages):
  152. fpn_name = 'fpn_' + body_name_list[i]
  153. fan = self.fpn_inner_output[i].shape[1] * 3 * 3
  154. if self.norm_type:
  155. initializer = Xavier(fan_out=fan)
  156. fpn_output = ConvNorm(
  157. self.fpn_inner_output[i],
  158. self.num_chan,
  159. 3,
  160. initializer=initializer,
  161. norm_type=self.norm_type,
  162. norm_decay=self.norm_decay,
  163. freeze_norm=self.freeze_norm,
  164. name=fpn_name,
  165. norm_name=fpn_name)
  166. else:
  167. fpn_output = fluid.layers.conv2d(
  168. self.fpn_inner_output[i],
  169. self.num_chan,
  170. filter_size=3,
  171. padding=1,
  172. param_attr=ParamAttr(
  173. name=fpn_name + "_w", initializer=Xavier(fan_out=fan)),
  174. bias_attr=ParamAttr(
  175. name=fpn_name + "_b",
  176. learning_rate=2.,
  177. regularizer=L2Decay(0.)),
  178. name=fpn_name)
  179. fpn_dict[fpn_name] = fpn_output
  180. fpn_name_list.append(fpn_name)
  181. if not self.has_extra_convs and self.max_level - self.min_level == len(
  182. spatial_scale):
  183. body_top_name = fpn_name_list[0]
  184. body_top_extension = fluid.layers.pool2d(
  185. fpn_dict[body_top_name],
  186. 1,
  187. 'max',
  188. pool_stride=2,
  189. name=body_top_name + '_subsampled_2x')
  190. fpn_dict[body_top_name + '_subsampled_2x'] = body_top_extension
  191. fpn_name_list.insert(0, body_top_name + '_subsampled_2x')
  192. spatial_scale.insert(0, spatial_scale[0] * 0.5)
  193. # Coarser FPN levels introduced for RetinaNet
  194. highest_backbone_level = self.min_level + len(spatial_scale) - 1
  195. if self.has_extra_convs and self.max_level > highest_backbone_level:
  196. if self.use_c5:
  197. fpn_blob = body_dict[body_name_list[0]]
  198. else:
  199. fpn_blob = fpn_dict[fpn_name_list[0]]
  200. for i in range(highest_backbone_level + 1, self.max_level + 1):
  201. fpn_blob_in = fpn_blob
  202. fpn_name = 'fpn_' + str(i)
  203. if i > highest_backbone_level + 1:
  204. fpn_blob_in = fluid.layers.relu(fpn_blob)
  205. fan = fpn_blob_in.shape[1] * 3 * 3
  206. fpn_blob = fluid.layers.conv2d(
  207. input=fpn_blob_in,
  208. num_filters=self.num_chan,
  209. filter_size=3,
  210. stride=2,
  211. padding=1,
  212. param_attr=ParamAttr(
  213. name=fpn_name + "_w", initializer=Xavier(fan_out=fan)),
  214. bias_attr=ParamAttr(
  215. name=fpn_name + "_b",
  216. learning_rate=2.,
  217. regularizer=L2Decay(0.)),
  218. name=fpn_name)
  219. fpn_dict[fpn_name] = fpn_blob
  220. fpn_name_list.insert(0, fpn_name)
  221. spatial_scale.insert(0, spatial_scale[0] * 0.5)
  222. if self.reverse_out:
  223. fpn_name_list = fpn_name_list[::-1]
  224. res_dict = OrderedDict([(k, fpn_dict[k]) for k in fpn_name_list])
  225. return res_dict, spatial_scale