gfl.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (c) 2021 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. import paddle
  18. from ppdet.core.workspace import register, create
  19. from .meta_arch import BaseArch
  20. __all__ = ['GFL']
  21. @register
  22. class GFL(BaseArch):
  23. """
  24. Generalized Focal Loss network, see https://arxiv.org/abs/2006.04388
  25. Args:
  26. backbone (object): backbone instance
  27. neck (object): 'FPN' instance
  28. head (object): 'GFLHead' instance
  29. """
  30. __category__ = 'architecture'
  31. def __init__(self, backbone, neck, head='GFLHead'):
  32. super(GFL, self).__init__()
  33. self.backbone = backbone
  34. self.neck = neck
  35. self.head = head
  36. @classmethod
  37. def from_config(cls, cfg, *args, **kwargs):
  38. backbone = create(cfg['backbone'])
  39. kwargs = {'input_shape': backbone.out_shape}
  40. neck = create(cfg['neck'], **kwargs)
  41. kwargs = {'input_shape': neck.out_shape}
  42. head = create(cfg['head'], **kwargs)
  43. return {
  44. 'backbone': backbone,
  45. 'neck': neck,
  46. "head": head,
  47. }
  48. def _forward(self):
  49. body_feats = self.backbone(self.inputs)
  50. fpn_feats = self.neck(body_feats)
  51. head_outs = self.head(fpn_feats)
  52. if not self.training:
  53. im_shape = self.inputs['im_shape']
  54. scale_factor = self.inputs['scale_factor']
  55. bboxes, bbox_num = self.head.post_process(head_outs, im_shape,
  56. scale_factor)
  57. return bboxes, bbox_num
  58. else:
  59. return head_outs
  60. def get_loss(self, ):
  61. loss = {}
  62. head_outs = self._forward()
  63. loss_gfl = self.head.get_loss(head_outs, self.inputs)
  64. loss.update(loss_gfl)
  65. total_loss = paddle.add_n(list(loss.values()))
  66. loss.update({'loss': total_loss})
  67. return loss
  68. def get_pred(self):
  69. bbox_pred, bbox_num = self._forward()
  70. output = {'bbox': bbox_pred, 'bbox_num': bbox_num}
  71. return output