sparse_encoder.py 19.4 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
2
3
from typing import List, Tuple

Wenbo Yu's avatar
Wenbo Yu committed
4
5
import torch
from mmcv.ops import points_in_boxes_all, three_interpolate, three_nn
6
from torch import Tensor
zhangwenwei's avatar
zhangwenwei committed
7
from torch import nn as nn
zhangwenwei's avatar
zhangwenwei committed
8

zhangshilong's avatar
zhangshilong committed
9
10
from mmdet3d.models.layers import SparseBasicBlock, make_sparse_convmodule
from mmdet3d.models.layers.spconv import IS_SPCONV2_AVAILABLE
11
from mmdet3d.registry import MODELS
12
from mmdet3d.structures import BaseInstance3DBoxes
VVsssssk's avatar
VVsssssk committed
13
from mmdet.models.losses import sigmoid_focal_loss, smooth_l1_loss
zhangwenwei's avatar
zhangwenwei committed
14

VVsssssk's avatar
VVsssssk committed
15
16
17
18
19
if IS_SPCONV2_AVAILABLE:
    from spconv.pytorch import SparseConvTensor, SparseSequential
else:
    from mmcv.ops import SparseConvTensor, SparseSequential

zhangwenwei's avatar
zhangwenwei committed
20

21
@MODELS.register_module()
zhangwenwei's avatar
zhangwenwei committed
22
class SparseEncoder(nn.Module):
zhangwenwei's avatar
zhangwenwei committed
23
    r"""Sparse encoder for SECOND and Part-A2.
wuyuefeng's avatar
wuyuefeng committed
24
25

    Args:
wangtai's avatar
wangtai committed
26
27
        in_channels (int): The number of input channels.
        sparse_shape (list[int]): The sparse shape of input tensor.
28
29
30
        order (list[str], optional): Order of conv module.
            Defaults to ('conv', 'norm', 'act').
        norm_cfg (dict, optional): Config of normalization layer. Defaults to
31
            dict(type='BN1d', eps=1e-3, momentum=0.01).
32
        base_channels (int, optional): Out channels for conv_input layer.
33
            Defaults to 16.
34
        output_channels (int, optional): Out channels for conv_out layer.
35
            Defaults to 128.
36
        encoder_channels (tuple[tuple[int]], optional):
wangtai's avatar
wangtai committed
37
            Convolutional channels of each encode block.
Wenbo Yu's avatar
Wenbo Yu committed
38
            Defaults to ((16, ), (32, 32, 32), (64, 64, 64), (64, 64, 64)).
39
40
        encoder_paddings (tuple[tuple[int]], optional):
            Paddings of each encode block.
Wenbo Yu's avatar
Wenbo Yu committed
41
            Defaults to ((1, ), (1, 1, 1), (1, 1, 1), ((0, 1, 1), 1, 1)).
42
43
        block_type (str, optional): Type of the block to use.
            Defaults to 'conv_module'.
wuyuefeng's avatar
wuyuefeng committed
44
    """
zhangwenwei's avatar
zhangwenwei committed
45
46
47

    def __init__(self,
                 in_channels,
wuyuefeng's avatar
wuyuefeng committed
48
49
50
51
52
53
54
55
                 sparse_shape,
                 order=('conv', 'norm', 'act'),
                 norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01),
                 base_channels=16,
                 output_channels=128,
                 encoder_channels=((16, ), (32, 32, 32), (64, 64, 64), (64, 64,
                                                                        64)),
                 encoder_paddings=((1, ), (1, 1, 1), (1, 1, 1), ((0, 1, 1), 1,
56
57
                                                                 1)),
                 block_type='conv_module'):
zhangwenwei's avatar
zhangwenwei committed
58
        super().__init__()
59
        assert block_type in ['conv_module', 'basicblock']
wuyuefeng's avatar
wuyuefeng committed
60
        self.sparse_shape = sparse_shape
zhangwenwei's avatar
zhangwenwei committed
61
        self.in_channels = in_channels
wuyuefeng's avatar
wuyuefeng committed
62
63
64
65
66
67
        self.order = order
        self.base_channels = base_channels
        self.output_channels = output_channels
        self.encoder_channels = encoder_channels
        self.encoder_paddings = encoder_paddings
        self.stage_num = len(self.encoder_channels)
68
        self.fp16_enabled = False
zhangwenwei's avatar
zhangwenwei committed
69
        # Spconv init all weight on its own
wuyuefeng's avatar
wuyuefeng committed
70
71
72
73
74
75
76
77

        assert isinstance(order, tuple) and len(order) == 3
        assert set(order) == {'conv', 'norm', 'act'}

        if self.order[0] != 'conv':  # pre activate
            self.conv_input = make_sparse_convmodule(
                in_channels,
                self.base_channels,
zhangwenwei's avatar
zhangwenwei committed
78
79
80
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
81
82
83
84
85
86
87
                indice_key='subm1',
                conv_type='SubMConv3d',
                order=('conv', ))
        else:  # post activate
            self.conv_input = make_sparse_convmodule(
                in_channels,
                self.base_channels,
zhangwenwei's avatar
zhangwenwei committed
88
89
90
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
91
92
93
94
                indice_key='subm1',
                conv_type='SubMConv3d')

        encoder_out_channels = self.make_encoder_layers(
95
96
97
98
            make_sparse_convmodule,
            norm_cfg,
            self.base_channels,
            block_type=block_type)
wuyuefeng's avatar
wuyuefeng committed
99
100
101
102
103
104
105
106
107
108

        self.conv_out = make_sparse_convmodule(
            encoder_out_channels,
            self.output_channels,
            kernel_size=(3, 1, 1),
            stride=(2, 1, 1),
            norm_cfg=norm_cfg,
            padding=0,
            indice_key='spconv_down2',
            conv_type='SparseConv3d')
zhangwenwei's avatar
zhangwenwei committed
109
110

    def forward(self, voxel_features, coors, batch_size):
zhangwenwei's avatar
zhangwenwei committed
111
        """Forward of SparseEncoder.
wuyuefeng's avatar
wuyuefeng committed
112
113

        Args:
Wenbo Yu's avatar
Wenbo Yu committed
114
115
            voxel_features (torch.Tensor): Voxel features in shape (N, C).
            coors (torch.Tensor): Coordinates in shape (N, 4),
wangtai's avatar
wangtai committed
116
117
                the columns in the order of (batch_idx, z_idx, y_idx, x_idx).
            batch_size (int): Batch size.
wuyuefeng's avatar
wuyuefeng committed
118
119

        Returns:
wangtai's avatar
wangtai committed
120
            dict: Backbone features.
zhangwenwei's avatar
zhangwenwei committed
121
122
        """
        coors = coors.int()
123
124
        input_sp_tensor = SparseConvTensor(voxel_features, coors,
                                           self.sparse_shape, batch_size)
zhangwenwei's avatar
zhangwenwei committed
125
126
        x = self.conv_input(input_sp_tensor)

wuyuefeng's avatar
wuyuefeng committed
127
128
129
130
        encode_features = []
        for encoder_layer in self.encoder_layers:
            x = encoder_layer(x)
            encode_features.append(x)
zhangwenwei's avatar
zhangwenwei committed
131
132
133

        # for detection head
        # [200, 176, 5] -> [200, 176, 2]
wuyuefeng's avatar
wuyuefeng committed
134
        out = self.conv_out(encode_features[-1])
zhangwenwei's avatar
zhangwenwei committed
135
136
137
138
139
140
141
        spatial_features = out.dense()

        N, C, D, H, W = spatial_features.shape
        spatial_features = spatial_features.view(N, C * D, H, W)

        return spatial_features

142
143
144
145
146
147
    def make_encoder_layers(self,
                            make_block,
                            norm_cfg,
                            in_channels,
                            block_type='conv_module',
                            conv_cfg=dict(type='SubMConv3d')):
zhangwenwei's avatar
zhangwenwei committed
148
        """make encoder layers using sparse convs.
wuyuefeng's avatar
wuyuefeng committed
149
150

        Args:
wangtai's avatar
wangtai committed
151
152
153
            make_block (method): A bounded function to build blocks.
            norm_cfg (dict[str]): Config of normalization layer.
            in_channels (int): The number of encoder input channels.
154
155
156
            block_type (str, optional): Type of the block to use.
                Defaults to 'conv_module'.
            conv_cfg (dict, optional): Config of conv layer. Defaults to
157
                dict(type='SubMConv3d').
wuyuefeng's avatar
wuyuefeng committed
158
159

        Returns:
wangtai's avatar
wangtai committed
160
            int: The number of encoder output channels.
wuyuefeng's avatar
wuyuefeng committed
161
        """
162
        assert block_type in ['conv_module', 'basicblock']
163
        self.encoder_layers = SparseSequential()
wuyuefeng's avatar
wuyuefeng committed
164
165
166
167
168
169
170

        for i, blocks in enumerate(self.encoder_channels):
            blocks_list = []
            for j, out_channels in enumerate(tuple(blocks)):
                padding = tuple(self.encoder_paddings[i])[j]
                # each stage started with a spconv layer
                # except the first stage
171
                if i != 0 and j == 0 and block_type == 'conv_module':
wuyuefeng's avatar
wuyuefeng committed
172
173
174
175
176
177
178
179
180
181
                    blocks_list.append(
                        make_block(
                            in_channels,
                            out_channels,
                            3,
                            norm_cfg=norm_cfg,
                            stride=2,
                            padding=padding,
                            indice_key=f'spconv{i + 1}',
                            conv_type='SparseConv3d'))
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                elif block_type == 'basicblock':
                    if j == len(blocks) - 1 and i != len(
                            self.encoder_channels) - 1:
                        blocks_list.append(
                            make_block(
                                in_channels,
                                out_channels,
                                3,
                                norm_cfg=norm_cfg,
                                stride=2,
                                padding=padding,
                                indice_key=f'spconv{i + 1}',
                                conv_type='SparseConv3d'))
                    else:
                        blocks_list.append(
                            SparseBasicBlock(
                                out_channels,
                                out_channels,
                                norm_cfg=norm_cfg,
                                conv_cfg=conv_cfg))
wuyuefeng's avatar
wuyuefeng committed
202
203
204
205
206
207
208
209
210
211
212
213
                else:
                    blocks_list.append(
                        make_block(
                            in_channels,
                            out_channels,
                            3,
                            norm_cfg=norm_cfg,
                            padding=padding,
                            indice_key=f'subm{i + 1}',
                            conv_type='SubMConv3d'))
                in_channels = out_channels
            stage_name = f'encoder_layer{i + 1}'
214
            stage_layers = SparseSequential(*blocks_list)
wuyuefeng's avatar
wuyuefeng committed
215
216
            self.encoder_layers.add_module(stage_name, stage_layers)
        return out_channels
Wenbo Yu's avatar
Wenbo Yu committed
217
218


VVsssssk's avatar
VVsssssk committed
219
@MODELS.register_module()
Wenbo Yu's avatar
Wenbo Yu committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
class SparseEncoderSASSD(SparseEncoder):
    r"""Sparse encoder for `SASSD <https://github.com/skyhehe123/SA-SSD>`_

    Args:
        in_channels (int): The number of input channels.
        sparse_shape (list[int]): The sparse shape of input tensor.
        order (list[str], optional): Order of conv module.
            Defaults to ('conv', 'norm', 'act').
        norm_cfg (dict, optional): Config of normalization layer. Defaults to
            dict(type='BN1d', eps=1e-3, momentum=0.01).
        base_channels (int, optional): Out channels for conv_input layer.
            Defaults to 16.
        output_channels (int, optional): Out channels for conv_out layer.
            Defaults to 128.
        encoder_channels (tuple[tuple[int]], optional):
            Convolutional channels of each encode block.
            Defaults to ((16, ), (32, 32, 32), (64, 64, 64), (64, 64, 64)).
        encoder_paddings (tuple[tuple[int]], optional):
            Paddings of each encode block.
            Defaults to ((1, ), (1, 1, 1), (1, 1, 1), ((0, 1, 1), 1, 1)).
        block_type (str, optional): Type of the block to use.
            Defaults to 'conv_module'.
    """

    def __init__(self,
245
246
247
248
249
250
251
252
253
254
255
                 in_channels: int,
                 sparse_shape: List[int],
                 order: Tuple[str] = ('conv', 'norm', 'act'),
                 norm_cfg: dict = dict(type='BN1d', eps=1e-3, momentum=0.01),
                 base_channels: int = 16,
                 output_channels: int = 128,
                 encoder_channels: Tuple[tuple] = ((16, ), (32, 32, 32),
                                                   (64, 64, 64), (64, 64, 64)),
                 encoder_paddings: Tuple[tuple] = ((1, ), (1, 1, 1), (1, 1, 1),
                                                   ((0, 1, 1), 1, 1)),
                 block_type: str = 'conv_module'):
Wenbo Yu's avatar
Wenbo Yu committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
        super(SparseEncoderSASSD, self).__init__(
            in_channels=in_channels,
            sparse_shape=sparse_shape,
            order=order,
            norm_cfg=norm_cfg,
            base_channels=base_channels,
            output_channels=output_channels,
            encoder_channels=encoder_channels,
            encoder_paddings=encoder_paddings,
            block_type=block_type)

        self.point_fc = nn.Linear(112, 64, bias=False)
        self.point_cls = nn.Linear(64, 1, bias=False)
        self.point_reg = nn.Linear(64, 3, bias=False)

271
272
273
274
275
    def forward(self,
                voxel_features: Tensor,
                coors: Tensor,
                batch_size: Tensor,
                test_mode: bool = False) -> Tuple[Tensor, tuple]:
Wenbo Yu's avatar
Wenbo Yu committed
276
277
278
279
280
281
282
283
284
285
286
        """Forward of SparseEncoder.

        Args:
            voxel_features (torch.Tensor): Voxel features in shape (N, C).
            coors (torch.Tensor): Coordinates in shape (N, 4),
                the columns in the order of (batch_idx, z_idx, y_idx, x_idx).
            batch_size (int): Batch size.
            test_mode (bool, optional): Whether in test mode.
                Defaults to False.

        Returns:
287
            Tensor: Backbone features.
Wenbo Yu's avatar
Wenbo Yu committed
288
            tuple[torch.Tensor]: Mean feature value of the points,
289
                Classification result of the points,
Wenbo Yu's avatar
Wenbo Yu committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
                Regression offsets of the points.
        """
        coors = coors.int()
        input_sp_tensor = SparseConvTensor(voxel_features, coors,
                                           self.sparse_shape, batch_size)
        x = self.conv_input(input_sp_tensor)

        encode_features = []
        for encoder_layer in self.encoder_layers:
            x = encoder_layer(x)
            encode_features.append(x)

        # for detection head
        # [200, 176, 5] -> [200, 176, 2]
        out = self.conv_out(encode_features[-1])
        spatial_features = out.dense()

        N, C, D, H, W = spatial_features.shape
        spatial_features = spatial_features.view(N, C * D, H, W)

        if test_mode:
            return spatial_features, None

        points_mean = torch.zeros_like(voxel_features)
        points_mean[:, 0] = coors[:, 0]
        points_mean[:, 1:] = voxel_features[:, :3]

        # auxiliary network
        p0 = self.make_auxiliary_points(
            encode_features[0],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.1, .1, .2))

        p1 = self.make_auxiliary_points(
            encode_features[1],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.2, .2, .4))

        p2 = self.make_auxiliary_points(
            encode_features[2],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.4, .4, .8))

        pointwise = torch.cat([p0, p1, p2], dim=-1)
        pointwise = self.point_fc(pointwise)
        point_cls = self.point_cls(pointwise)
        point_reg = self.point_reg(pointwise)
        point_misc = (points_mean, point_cls, point_reg)

        return spatial_features, point_misc

344
345
346
347
    def get_auxiliary_targets(self,
                              points_feats: Tensor,
                              gt_bboxes_3d: List[BaseInstance3DBoxes],
                              enlarge: float = 1.0) -> Tuple[Tensor, Tensor]:
Wenbo Yu's avatar
Wenbo Yu committed
348
349
350
        """Get auxiliary target.

        Args:
351
352
353
354
            points_feats (torch.Tensor): Mean features of the points.
            gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]):  Ground truth
                boxes for each sample.
            enlarge (float, optional): Enlaged scale. Defaults to 1.0.
Wenbo Yu's avatar
Wenbo Yu committed
355
356
357
358
359
360
361

        Returns:
            tuple[torch.Tensor]: Label of the points and
                center offsets of the points.
        """
        center_offsets = list()
        pts_labels = list()
362
363
364
365
        for i in range(len(gt_bboxes_3d)):
            boxes3d = gt_bboxes_3d[i].tensor.detach().clone()
            idx = torch.nonzero(points_feats[:, 0] == i).view(-1)
            point_xyz = points_feats[idx, 1:].detach().clone()
Wenbo Yu's avatar
Wenbo Yu committed
366
367
368
369

            boxes3d[:, 3:6] *= enlarge

            pts_in_flag, center_offset = self.calculate_pts_offsets(
370
                point_xyz, boxes3d)
Wenbo Yu's avatar
Wenbo Yu committed
371
372
373
374
            pts_label = pts_in_flag.max(0)[0].byte()
            pts_labels.append(pts_label)
            center_offsets.append(center_offset)

375
        center_offsets = torch.cat(center_offsets)
Wenbo Yu's avatar
Wenbo Yu committed
376
377
378
379
        pts_labels = torch.cat(pts_labels).to(center_offsets.device)

        return pts_labels, center_offsets

380
381
    def calculate_pts_offsets(self, points: Tensor,
                              bboxes_3d: Tensor) -> Tuple[Tensor, Tensor]:
Wenbo Yu's avatar
Wenbo Yu committed
382
383
384
385
        """Find all boxes in which each point is, as well as the offsets from
        the box centers.

        Args:
386
387
            points (torch.Tensor): [M, 3], [x, y, z] in LiDAR coordinate
            bboxes_3d (torch.Tensor): [T, 7],
Wenbo Yu's avatar
Wenbo Yu committed
388
389
390
391
392
393
394
395
396
397
                num_valid_boxes <= T, [x, y, z, x_size, y_size, z_size, rz],
                (x, y, z) is the bottom center.

        Returns:
            tuple[torch.Tensor]: Point indices of boxes with the shape of
                (T, M). Default background = 0.
                And offsets from the box centers of points,
                if it belows to the box, with the shape of (M, 3).
                Default background = 0.
        """
398
        boxes_num = len(bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
399
400
        pts_num = len(points)

401
        box_indices = points_in_boxes_all(points[None, ...], bboxes_3d[None,
Wenbo Yu's avatar
Wenbo Yu committed
402
                                                                       ...])
403
        pts_indices = box_indices.squeeze(0).transpose(0, 1)
Wenbo Yu's avatar
Wenbo Yu committed
404
405
406
407
408
        center_offsets = torch.zeros_like(points).to(points.device)

        for i in range(boxes_num):
            for j in range(pts_num):
                if pts_indices[i][j] == 1:
409
410
                    center_offsets[j][0] = points[j][0] - bboxes_3d[i][0]
                    center_offsets[j][1] = points[j][1] - bboxes_3d[i][1]
Wenbo Yu's avatar
Wenbo Yu committed
411
                    center_offsets[j][2] = (
412
413
414
                        points[j][2] -
                        (bboxes_3d[i][2] + bboxes_3d[i][2] / 2.0))
        return pts_indices, center_offsets
Wenbo Yu's avatar
Wenbo Yu committed
415

416
417
    def aux_loss(self, points: Tensor, point_cls: Tensor, point_reg: Tensor,
                 gt_bboxes_3d: Tensor) -> dict:
Wenbo Yu's avatar
Wenbo Yu committed
418
419
420
421
        """Calculate auxiliary loss.

        Args:
            points (torch.Tensor): Mean feature value of the points.
422
            point_cls (torch.Tensor): Classification result of the points.
Wenbo Yu's avatar
Wenbo Yu committed
423
            point_reg (torch.Tensor): Regression offsets of the points.
424
            gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]): Ground truth
Wenbo Yu's avatar
Wenbo Yu committed
425
426
427
                boxes for each sample.

        Returns:
428
            dict: Auxiliary loss.
Wenbo Yu's avatar
Wenbo Yu committed
429
        """
430
        num_boxes = len(gt_bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
431
        pts_labels, center_targets = self.get_auxiliary_targets(
432
            points, gt_bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

        rpn_cls_target = pts_labels.long()
        pos = (pts_labels > 0).float()
        neg = (pts_labels == 0).float()

        pos_normalizer = pos.sum().clamp(min=1.0)

        cls_weights = pos + neg
        reg_weights = pos
        reg_weights = reg_weights / pos_normalizer

        aux_loss_cls = sigmoid_focal_loss(
            point_cls,
            rpn_cls_target,
            weight=cls_weights,
            avg_factor=pos_normalizer)

        aux_loss_cls /= num_boxes

        weight = reg_weights[..., None]
        aux_loss_reg = smooth_l1_loss(point_reg, center_targets, beta=1 / 9.)
        aux_loss_reg = torch.sum(aux_loss_reg * weight)[None]
        aux_loss_reg /= num_boxes

        aux_loss_cls, aux_loss_reg = [aux_loss_cls], [aux_loss_reg]

        return dict(aux_loss_cls=aux_loss_cls, aux_loss_reg=aux_loss_reg)

461
462
463
464
465
466
467
    def make_auxiliary_points(
        self,
        source_tensor: Tensor,
        target: Tensor,
        offset: Tuple = (0., -40., -3.),
        voxel_size: Tuple = (.05, .05, .1)
    ) -> Tensor:
Wenbo Yu's avatar
Wenbo Yu committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
        """Make auxiliary points for loss computation.

        Args:
            source_tensor (torch.Tensor): (M, C) features to be propigated.
            target (torch.Tensor): (N, 4) bxyz positions of the
                target features.
            offset (tuple[float], optional): Voxelization offset.
                Defaults to (0., -40., -3.)
            voxel_size (tuple[float], optional): Voxelization size.
                Defaults to (.05, .05, .1)

        Returns:
            torch.Tensor: (N, C) tensor of the features of the target features.
        """
        # Tansfer tensor to points
        source = source_tensor.indices.float()
        offset = torch.Tensor(offset).to(source.device)
        voxel_size = torch.Tensor(voxel_size).to(source.device)
        source[:, 1:] = (
            source[:, [3, 2, 1]] * voxel_size + offset + .5 * voxel_size)

        source_feats = source_tensor.features[None, ...].transpose(1, 2)

        # Interplate auxiliary points
        dist, idx = three_nn(target[None, ...], source[None, ...])
        dist_recip = 1.0 / (dist + 1e-8)
        norm = torch.sum(dist_recip, dim=2, keepdim=True)
        weight = dist_recip / norm
        new_features = three_interpolate(source_feats.contiguous(), idx,
                                         weight)

        return new_features.squeeze(0).transpose(0, 1)