parta2_rpn_head.py 13.5 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
wuyuefeng's avatar
wuyuefeng committed
2
3
4
5
from __future__ import division

import numpy as np
import torch
6
7
from mmcv.ops import nms_bev as nms_gpu
from mmcv.ops import nms_normal_bev as nms_normal_gpu
8
from mmcv.runner import force_fp32
wuyuefeng's avatar
wuyuefeng committed
9

zhangwenwei's avatar
zhangwenwei committed
10
from mmdet3d.core import limit_period, xywhr2xyxyr
wuyuefeng's avatar
wuyuefeng committed
11
from mmdet.models import HEADS
zhangwenwei's avatar
zhangwenwei committed
12
from .anchor3d_head import Anchor3DHead
wuyuefeng's avatar
wuyuefeng committed
13
14


15
@HEADS.register_module()
zhangwenwei's avatar
zhangwenwei committed
16
class PartA2RPNHead(Anchor3DHead):
zhangwenwei's avatar
zhangwenwei committed
17
    """RPN head for PartA2.
zhangwenwei's avatar
zhangwenwei committed
18
19
20
21
22
23
24
25
26
27
28

    Note:
        The main difference between the PartA2 RPN head and the Anchor3DHead
        lies in their output during inference. PartA2 RPN head further returns
        the original classification score for the second stage since the bbox
        head in RoI head does not do classification task.

        Different from RPN heads in 2D detectors, this RPN head does
        multi-class classification task and uses FocalLoss like the SECOND and
        PointPillars do. But this head uses class agnostic nms rather than
        multi-class nms.
wuyuefeng's avatar
wuyuefeng committed
29
30

    Args:
zhangwenwei's avatar
zhangwenwei committed
31
        num_classes (int): Number of classes.
wuyuefeng's avatar
wuyuefeng committed
32
        in_channels (int): Number of channels in the input feature map.
wangtai's avatar
wangtai committed
33
34
        train_cfg (dict): Train configs.
        test_cfg (dict): Test configs.
wuyuefeng's avatar
wuyuefeng committed
35
36
37
38
39
40
41
42
43
44
        feat_channels (int): Number of channels of the feature map.
        use_direction_classifier (bool): Whether to add a direction classifier.
        anchor_generator(dict): Config dict of anchor generator.
        assigner_per_size (bool): Whether to do assignment for each separate
            anchor size.
        assign_per_class (bool): Whether to do assignment for each class.
        diff_rad_by_sin (bool): Whether to change the difference into sin
            difference for box regression loss.
        dir_offset (float | int): The offset of BEV rotation angles
            (TODO: may be moved into box coder)
wuyuefeng's avatar
wuyuefeng committed
45
46
47
        dir_limit_offset (float | int): The limited range of BEV
            rotation angles. (TODO: may be moved into box coder)
        bbox_coder (dict): Config dict of box coders.
wuyuefeng's avatar
wuyuefeng committed
48
49
50
        loss_cls (dict): Config of classification loss.
        loss_bbox (dict): Config of localization loss.
        loss_dir (dict): Config of direction classifier loss.
zhangwenwei's avatar
zhangwenwei committed
51
    """
wuyuefeng's avatar
wuyuefeng committed
52
53

    def __init__(self,
zhangwenwei's avatar
zhangwenwei committed
54
                 num_classes,
wuyuefeng's avatar
wuyuefeng committed
55
56
57
58
59
60
61
62
63
                 in_channels,
                 train_cfg,
                 test_cfg,
                 feat_channels=256,
                 use_direction_classifier=True,
                 anchor_generator=dict(
                     type='Anchor3DRangeGenerator',
                     range=[0, -39.68, -1.78, 69.12, 39.68, -1.78],
                     strides=[2],
64
                     sizes=[[3.9, 1.6, 1.56]],
wuyuefeng's avatar
wuyuefeng committed
65
66
67
68
69
70
                     rotations=[0, 1.57],
                     custom_values=[],
                     reshape_out=False),
                 assigner_per_size=False,
                 assign_per_class=False,
                 diff_rad_by_sin=True,
71
72
                 dir_offset=-np.pi / 2,
                 dir_limit_offset=0,
wuyuefeng's avatar
wuyuefeng committed
73
74
75
76
77
78
79
                 bbox_coder=dict(type='DeltaXYZWLHRBBoxCoder'),
                 loss_cls=dict(
                     type='CrossEntropyLoss',
                     use_sigmoid=True,
                     loss_weight=1.0),
                 loss_bbox=dict(
                     type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=2.0),
80
81
                 loss_dir=dict(type='CrossEntropyLoss', loss_weight=0.2),
                 init_cfg=None):
zhangwenwei's avatar
zhangwenwei committed
82
        super().__init__(num_classes, in_channels, train_cfg, test_cfg,
wuyuefeng's avatar
wuyuefeng committed
83
                         feat_channels, use_direction_classifier,
zhangwenwei's avatar
zhangwenwei committed
84
85
                         anchor_generator, assigner_per_size, assign_per_class,
                         diff_rad_by_sin, dir_offset, dir_limit_offset,
86
                         bbox_coder, loss_cls, loss_bbox, loss_dir, init_cfg)
wuyuefeng's avatar
wuyuefeng committed
87

88
    @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'dir_cls_preds'))
zhangwenwei's avatar
zhangwenwei committed
89
90
91
92
93
94
95
96
    def loss(self,
             cls_scores,
             bbox_preds,
             dir_cls_preds,
             gt_bboxes,
             gt_labels,
             input_metas,
             gt_bboxes_ignore=None):
97
98
99
100
101
102
103
        """Calculate losses.

        Args:
            cls_scores (list[torch.Tensor]): Multi-level class scores.
            bbox_preds (list[torch.Tensor]): Multi-level bbox predictions.
            dir_cls_preds (list[torch.Tensor]): Multi-level direction
                class predictions.
104
            gt_bboxes (list[:obj:`BaseInstance3DBoxes`]): Ground truth boxes
105
                of each sample.
wangtai's avatar
wangtai committed
106
107
            gt_labels (list[torch.Tensor]): Labels of each sample.
            input_metas (list[dict]): Point cloud and image's meta info.
108
            gt_bboxes_ignore (list[torch.Tensor]): Specify
109
110
111
                which bounding.

        Returns:
112
            dict[str, list[torch.Tensor]]: Classification, bbox, and
zhangwenwei's avatar
zhangwenwei committed
113
                direction losses of each level.
114
115
116

                - loss_rpn_cls (list[torch.Tensor]): Classification losses.
                - loss_rpn_bbox (list[torch.Tensor]): Box regression losses.
117
                - loss_rpn_dir (list[torch.Tensor]): Direction classification
118
119
                    losses.
        """
zhangwenwei's avatar
zhangwenwei committed
120
121
122
123
124
125
126
127
128
        loss_dict = super().loss(cls_scores, bbox_preds, dir_cls_preds,
                                 gt_bboxes, gt_labels, input_metas,
                                 gt_bboxes_ignore)
        # change the loss key names to avoid conflict
        return dict(
            loss_rpn_cls=loss_dict['loss_cls'],
            loss_rpn_bbox=loss_dict['loss_bbox'],
            loss_rpn_dir=loss_dict['loss_dir'])

wuyuefeng's avatar
wuyuefeng committed
129
130
131
132
133
134
135
136
    def get_bboxes_single(self,
                          cls_scores,
                          bbox_preds,
                          dir_cls_preds,
                          mlvl_anchors,
                          input_meta,
                          cfg,
                          rescale=False):
wuyuefeng's avatar
wuyuefeng committed
137
138
139
        """Get bboxes of single branch.

        Args:
liyinhao's avatar
liyinhao committed
140
141
142
143
144
            cls_scores (torch.Tensor): Class score in single batch.
            bbox_preds (torch.Tensor): Bbox prediction in single batch.
            dir_cls_preds (torch.Tensor): Predictions of direction class
                in single batch.
            mlvl_anchors (List[torch.Tensor]): Multi-level anchors
wuyuefeng's avatar
wuyuefeng committed
145
146
                in single batch.
            input_meta (list[dict]): Contain pcd and img's meta info.
147
            cfg (:obj:`ConfigDict`): Training or testing config.
liyinhao's avatar
liyinhao committed
148
            rescale (list[torch.Tensor]): whether th rescale bbox.
wuyuefeng's avatar
wuyuefeng committed
149
150

        Returns:
zhangwenwei's avatar
zhangwenwei committed
151
            dict: Predictions of single batch containing the following keys:
152

zhangwenwei's avatar
zhangwenwei committed
153
                - boxes_3d (:obj:`BaseInstance3DBoxes`): Predicted 3d bboxes.
liyinhao's avatar
liyinhao committed
154
155
156
                - scores_3d (torch.Tensor): Score of each bbox.
                - labels_3d (torch.Tensor): Label of each bbox.
                - cls_preds (torch.Tensor): Class score of each bbox.
wuyuefeng's avatar
wuyuefeng committed
157
        """
wuyuefeng's avatar
wuyuefeng committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        assert len(cls_scores) == len(bbox_preds) == len(mlvl_anchors)
        mlvl_bboxes = []
        mlvl_max_scores = []
        mlvl_label_pred = []
        mlvl_dir_scores = []
        mlvl_cls_score = []
        for cls_score, bbox_pred, dir_cls_pred, anchors in zip(
                cls_scores, bbox_preds, dir_cls_preds, mlvl_anchors):
            assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
            assert cls_score.size()[-2:] == dir_cls_pred.size()[-2:]
            dir_cls_pred = dir_cls_pred.permute(1, 2, 0).reshape(-1, 2)
            dir_cls_score = torch.max(dir_cls_pred, dim=-1)[1]

            cls_score = cls_score.permute(1, 2,
                                          0).reshape(-1, self.num_classes)

            if self.use_sigmoid_cls:
                scores = cls_score.sigmoid()
            else:
                scores = cls_score.softmax(-1)
            bbox_pred = bbox_pred.permute(1, 2,
                                          0).reshape(-1, self.box_code_size)

            nms_pre = cfg.get('nms_pre', -1)
            if self.use_sigmoid_cls:
                max_scores, pred_labels = scores.max(dim=1)
            else:
                max_scores, pred_labels = scores[:, :-1].max(dim=1)
            # get topk
            if nms_pre > 0 and scores.shape[0] > nms_pre:
                topk_scores, topk_inds = max_scores.topk(nms_pre)
                anchors = anchors[topk_inds, :]
                bbox_pred = bbox_pred[topk_inds, :]
                max_scores = topk_scores
zhangwenwei's avatar
zhangwenwei committed
192
                cls_score = scores[topk_inds, :]
wuyuefeng's avatar
wuyuefeng committed
193
194
195
196
197
198
199
200
201
202
203
                dir_cls_score = dir_cls_score[topk_inds]
                pred_labels = pred_labels[topk_inds]

            bboxes = self.bbox_coder.decode(anchors, bbox_pred)
            mlvl_bboxes.append(bboxes)
            mlvl_max_scores.append(max_scores)
            mlvl_cls_score.append(cls_score)
            mlvl_label_pred.append(pred_labels)
            mlvl_dir_scores.append(dir_cls_score)

        mlvl_bboxes = torch.cat(mlvl_bboxes)
zhangwenwei's avatar
zhangwenwei committed
204
205
        mlvl_bboxes_for_nms = xywhr2xyxyr(input_meta['box_type_3d'](
            mlvl_bboxes, box_dim=self.box_code_size).bev)
wuyuefeng's avatar
wuyuefeng committed
206
207
208
        mlvl_max_scores = torch.cat(mlvl_max_scores)
        mlvl_label_pred = torch.cat(mlvl_label_pred)
        mlvl_dir_scores = torch.cat(mlvl_dir_scores)
zhangwenwei's avatar
zhangwenwei committed
209
210
        # shape [k, num_class] before sigmoid
        # PartA2 need to keep raw classification score
211
        # because the bbox head in the second stage does not have
zhangwenwei's avatar
zhangwenwei committed
212
213
214
        # classification branch,
        # roi head need this score as classification score
        mlvl_cls_score = torch.cat(mlvl_cls_score)
wuyuefeng's avatar
wuyuefeng committed
215
216
217
218
219

        score_thr = cfg.get('score_thr', 0)
        result = self.class_agnostic_nms(mlvl_bboxes, mlvl_bboxes_for_nms,
                                         mlvl_max_scores, mlvl_label_pred,
                                         mlvl_cls_score, mlvl_dir_scores,
220
221
                                         score_thr, cfg.nms_post, cfg,
                                         input_meta)
wuyuefeng's avatar
wuyuefeng committed
222
223
224
225
226

        return result

    def class_agnostic_nms(self, mlvl_bboxes, mlvl_bboxes_for_nms,
                           mlvl_max_scores, mlvl_label_pred, mlvl_cls_score,
227
228
                           mlvl_dir_scores, score_thr, max_num, cfg,
                           input_meta):
wuyuefeng's avatar
wuyuefeng committed
229
230
231
        """Class agnostic nms for single batch.

        Args:
liyinhao's avatar
liyinhao committed
232
233
234
235
236
237
238
239
240
241
            mlvl_bboxes (torch.Tensor): Bboxes from Multi-level.
            mlvl_bboxes_for_nms (torch.Tensor): Bboxes for nms
                (bev or minmax boxes) from Multi-level.
            mlvl_max_scores (torch.Tensor): Max scores of Multi-level bbox.
            mlvl_label_pred (torch.Tensor): Class predictions
                of Multi-level bbox.
            mlvl_cls_score (torch.Tensor): Class scores of
                Multi-level bbox.
            mlvl_dir_scores (torch.Tensor): Direction scores of
                Multi-level bbox.
wuyuefeng's avatar
wuyuefeng committed
242
243
            score_thr (int): Score threshold.
            max_num (int): Max number of bboxes after nms.
244
            cfg (:obj:`ConfigDict`): Training or testing config.
wuyuefeng's avatar
wuyuefeng committed
245
246
247
248
            input_meta (dict): Contain pcd and img's meta info.

        Returns:
            dict: Predictions of single batch. Contain the keys:
249

zhangwenwei's avatar
zhangwenwei committed
250
                - boxes_3d (:obj:`BaseInstance3DBoxes`): Predicted 3d bboxes.
liyinhao's avatar
liyinhao committed
251
252
253
                - scores_3d (torch.Tensor): Score of each bbox.
                - labels_3d (torch.Tensor): Label of each bbox.
                - cls_preds (torch.Tensor): Class score of each bbox.
wuyuefeng's avatar
wuyuefeng committed
254
        """
wuyuefeng's avatar
wuyuefeng committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        bboxes = []
        scores = []
        labels = []
        dir_scores = []
        cls_scores = []
        score_thr_inds = mlvl_max_scores > score_thr
        _scores = mlvl_max_scores[score_thr_inds]
        _bboxes_for_nms = mlvl_bboxes_for_nms[score_thr_inds, :]
        if cfg.use_rotate_nms:
            nms_func = nms_gpu
        else:
            nms_func = nms_normal_gpu
        selected = nms_func(_bboxes_for_nms, _scores, cfg.nms_thr)

        _mlvl_bboxes = mlvl_bboxes[score_thr_inds, :]
        _mlvl_dir_scores = mlvl_dir_scores[score_thr_inds]
        _mlvl_label_pred = mlvl_label_pred[score_thr_inds]
        _mlvl_cls_score = mlvl_cls_score[score_thr_inds]

        if len(selected) > 0:
            bboxes.append(_mlvl_bboxes[selected])
            scores.append(_scores[selected])
            labels.append(_mlvl_label_pred[selected])
            cls_scores.append(_mlvl_cls_score[selected])
            dir_scores.append(_mlvl_dir_scores[selected])
zhangwenwei's avatar
zhangwenwei committed
280
281
            dir_rot = limit_period(bboxes[-1][..., 6] - self.dir_offset,
                                   self.dir_limit_offset, np.pi)
wuyuefeng's avatar
wuyuefeng committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            bboxes[-1][..., 6] = (
                dir_rot + self.dir_offset +
                np.pi * dir_scores[-1].to(bboxes[-1].dtype))

        if bboxes:
            bboxes = torch.cat(bboxes, dim=0)
            scores = torch.cat(scores, dim=0)
            cls_scores = torch.cat(cls_scores, dim=0)
            labels = torch.cat(labels, dim=0)
            dir_scores = torch.cat(dir_scores, dim=0)
            if bboxes.shape[0] > max_num:
                _, inds = scores.sort(descending=True)
                inds = inds[:max_num]
                bboxes = bboxes[inds, :]
                labels = labels[inds]
                scores = scores[inds]
                cls_scores = cls_scores[inds]
299
300
            bboxes = input_meta['box_type_3d'](
                bboxes, box_dim=self.box_code_size)
wuyuefeng's avatar
wuyuefeng committed
301
            return dict(
zhangwenwei's avatar
zhangwenwei committed
302
303
304
                boxes_3d=bboxes,
                scores_3d=scores,
                labels_3d=labels,
wuyuefeng's avatar
wuyuefeng committed
305
                cls_preds=cls_scores  # raw scores [max_num, cls_num]
wuyuefeng's avatar
wuyuefeng committed
306
307
308
            )
        else:
            return dict(
309
310
311
                boxes_3d=input_meta['box_type_3d'](
                    mlvl_bboxes.new_zeros([0, self.box_code_size]),
                    box_dim=self.box_code_size),
zhangwenwei's avatar
zhangwenwei committed
312
313
                scores_3d=mlvl_bboxes.new_zeros([0]),
                labels_3d=mlvl_bboxes.new_zeros([0]),
wuyuefeng's avatar
wuyuefeng committed
314
                cls_preds=mlvl_bboxes.new_zeros([0, mlvl_cls_score.shape[-1]]))