detr.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 .meta_arch import BaseArch
  19. from ppdet.core.workspace import register, create
  20. __all__ = ['DETR']
  21. @register
  22. class DETR(BaseArch):
  23. __category__ = 'architecture'
  24. __inject__ = ['post_process']
  25. def __init__(self,
  26. backbone,
  27. transformer,
  28. detr_head,
  29. post_process='DETRBBoxPostProcess'):
  30. super(DETR, self).__init__()
  31. self.backbone = backbone
  32. self.transformer = transformer
  33. self.detr_head = detr_head
  34. self.post_process = post_process
  35. @classmethod
  36. def from_config(cls, cfg, *args, **kwargs):
  37. # backbone
  38. backbone = create(cfg['backbone'])
  39. # transformer
  40. kwargs = {'input_shape': backbone.out_shape}
  41. transformer = create(cfg['transformer'], **kwargs)
  42. # head
  43. kwargs = {
  44. 'hidden_dim': transformer.hidden_dim,
  45. 'nhead': transformer.nhead,
  46. 'input_shape': backbone.out_shape
  47. }
  48. detr_head = create(cfg['detr_head'], **kwargs)
  49. return {
  50. 'backbone': backbone,
  51. 'transformer': transformer,
  52. "detr_head": detr_head,
  53. }
  54. def _forward(self):
  55. # Backbone
  56. body_feats = self.backbone(self.inputs)
  57. # Transformer
  58. out_transformer = self.transformer(body_feats, self.inputs['pad_mask'])
  59. # DETR Head
  60. if self.training:
  61. return self.detr_head(out_transformer, body_feats, self.inputs)
  62. else:
  63. preds = self.detr_head(out_transformer, body_feats)
  64. bbox, bbox_num = self.post_process(preds, self.inputs['im_shape'],
  65. self.inputs['scale_factor'])
  66. return bbox, bbox_num
  67. def get_loss(self, ):
  68. losses = self._forward()
  69. losses.update({
  70. 'loss':
  71. paddle.add_n([v for k, v in losses.items() if 'log' not in k])
  72. })
  73. return losses
  74. def get_pred(self):
  75. bbox_pred, bbox_num = self._forward()
  76. output = {
  77. "bbox": bbox_pred,
  78. "bbox_num": bbox_num,
  79. }
  80. return output