sparse_rcnn.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. from ppdet.core.workspace import register, create
  18. from .meta_arch import BaseArch
  19. __all__ = ["SparseRCNN"]
  20. @register
  21. class SparseRCNN(BaseArch):
  22. __category__ = 'architecture'
  23. __inject__ = ["postprocess"]
  24. def __init__(self,
  25. backbone,
  26. neck,
  27. head="SparsercnnHead",
  28. postprocess="SparsePostProcess"):
  29. super(SparseRCNN, self).__init__()
  30. self.backbone = backbone
  31. self.neck = neck
  32. self.head = head
  33. self.postprocess = postprocess
  34. @classmethod
  35. def from_config(cls, cfg, *args, **kwargs):
  36. backbone = create(cfg['backbone'])
  37. kwargs = {'input_shape': backbone.out_shape}
  38. neck = create(cfg['neck'], **kwargs)
  39. kwargs = {'roi_input_shape': neck.out_shape}
  40. head = create(cfg['head'], **kwargs)
  41. return {
  42. 'backbone': backbone,
  43. 'neck': neck,
  44. "head": head,
  45. }
  46. def _forward(self):
  47. body_feats = self.backbone(self.inputs)
  48. fpn_feats = self.neck(body_feats)
  49. head_outs = self.head(fpn_feats, self.inputs["img_whwh"])
  50. if not self.training:
  51. bboxes = self.postprocess(
  52. head_outs["pred_logits"], head_outs["pred_boxes"],
  53. self.inputs["scale_factor_wh"], self.inputs["img_whwh"])
  54. return bboxes
  55. else:
  56. return head_outs
  57. def get_loss(self):
  58. batch_gt_class = self.inputs["gt_class"]
  59. batch_gt_box = self.inputs["gt_bbox"]
  60. batch_whwh = self.inputs["img_whwh"]
  61. targets = []
  62. for i in range(len(batch_gt_class)):
  63. boxes = batch_gt_box[i]
  64. labels = batch_gt_class[i].squeeze(-1)
  65. img_whwh = batch_whwh[i]
  66. img_whwh_tgt = img_whwh.unsqueeze(0).tile([int(boxes.shape[0]), 1])
  67. targets.append({
  68. "boxes": boxes,
  69. "labels": labels,
  70. "img_whwh": img_whwh,
  71. "img_whwh_tgt": img_whwh_tgt
  72. })
  73. outputs = self._forward()
  74. loss_dict = self.head.get_loss(outputs, targets)
  75. acc = loss_dict["acc"]
  76. loss_dict.pop("acc")
  77. total_loss = sum(loss_dict.values())
  78. loss_dict.update({"loss": total_loss, "acc": acc})
  79. return loss_dict
  80. def get_pred(self):
  81. bbox_pred, bbox_num = self._forward()
  82. output = {'bbox': bbox_pred, 'bbox_num': bbox_num}
  83. return output