sparse_encoder.py 5.96 KB
Newer Older
zhangwenwei's avatar
zhangwenwei committed
1
from torch import nn as nn
zhangwenwei's avatar
zhangwenwei committed
2

wuyuefeng's avatar
wuyuefeng committed
3
from mmdet3d.ops import make_sparse_convmodule
zhangwenwei's avatar
zhangwenwei committed
4
from mmdet3d.ops import spconv as spconv
zhangwenwei's avatar
zhangwenwei committed
5
6
7
from ..registry import MIDDLE_ENCODERS


8
@MIDDLE_ENCODERS.register_module()
zhangwenwei's avatar
zhangwenwei committed
9
class SparseEncoder(nn.Module):
zhangwenwei's avatar
zhangwenwei committed
10
    r"""Sparse encoder for SECOND and Part-A2.
wuyuefeng's avatar
wuyuefeng committed
11
12

    Args:
wangtai's avatar
wangtai committed
13
14
15
16
17
        in_channels (int): The number of input channels.
        sparse_shape (list[int]): The sparse shape of input tensor.
        norm_cfg (dict): Config of normalization layer.
        base_channels (int): Out channels for conv_input layer.
        output_channels (int): Out channels for conv_out layer.
wuyuefeng's avatar
wuyuefeng committed
18
        encoder_channels (tuple[tuple[int]]):
wangtai's avatar
wangtai committed
19
20
            Convolutional channels of each encode block.
        encoder_paddings (tuple[tuple[int]]): Paddings of each encode block.
wuyuefeng's avatar
wuyuefeng committed
21
    """
zhangwenwei's avatar
zhangwenwei committed
22
23
24

    def __init__(self,
                 in_channels,
wuyuefeng's avatar
wuyuefeng committed
25
26
27
28
29
30
31
32
33
                 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,
                                                                 1))):
zhangwenwei's avatar
zhangwenwei committed
34
        super().__init__()
wuyuefeng's avatar
wuyuefeng committed
35
        self.sparse_shape = sparse_shape
zhangwenwei's avatar
zhangwenwei committed
36
        self.in_channels = in_channels
wuyuefeng's avatar
wuyuefeng committed
37
38
39
40
41
42
        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)
zhangwenwei's avatar
zhangwenwei committed
43
        # Spconv init all weight on its own
wuyuefeng's avatar
wuyuefeng committed
44
45
46
47
48
49
50
51

        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
52
53
54
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
55
56
57
58
59
60
61
                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
62
63
64
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
                indice_key='subm1',
                conv_type='SubMConv3d')

        encoder_out_channels = self.make_encoder_layers(
            make_sparse_convmodule, norm_cfg, self.base_channels)

        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
80
81

    def forward(self, voxel_features, coors, batch_size):
zhangwenwei's avatar
zhangwenwei committed
82
        """Forward of SparseEncoder.
wuyuefeng's avatar
wuyuefeng committed
83
84

        Args:
wangtai's avatar
wangtai committed
85
86
87
88
            voxel_features (torch.float32): Voxel features in shape (N, C).
            coors (torch.int32): Coordinates in shape (N, 4), \
                the columns in the order of (batch_idx, z_idx, y_idx, x_idx).
            batch_size (int): Batch size.
wuyuefeng's avatar
wuyuefeng committed
89
90

        Returns:
wangtai's avatar
wangtai committed
91
            dict: Backbone features.
zhangwenwei's avatar
zhangwenwei committed
92
93
94
95
96
97
98
        """
        coors = coors.int()
        input_sp_tensor = spconv.SparseConvTensor(voxel_features, coors,
                                                  self.sparse_shape,
                                                  batch_size)
        x = self.conv_input(input_sp_tensor)

wuyuefeng's avatar
wuyuefeng committed
99
100
101
102
        encode_features = []
        for encoder_layer in self.encoder_layers:
            x = encoder_layer(x)
            encode_features.append(x)
zhangwenwei's avatar
zhangwenwei committed
103
104
105

        # for detection head
        # [200, 176, 5] -> [200, 176, 2]
wuyuefeng's avatar
wuyuefeng committed
106
        out = self.conv_out(encode_features[-1])
zhangwenwei's avatar
zhangwenwei committed
107
108
109
110
111
112
113
        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

wuyuefeng's avatar
wuyuefeng committed
114
    def make_encoder_layers(self, make_block, norm_cfg, in_channels):
zhangwenwei's avatar
zhangwenwei committed
115
        """make encoder layers using sparse convs.
wuyuefeng's avatar
wuyuefeng committed
116
117

        Args:
wangtai's avatar
wangtai committed
118
119
120
            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.
wuyuefeng's avatar
wuyuefeng committed
121
122

        Returns:
wangtai's avatar
wangtai committed
123
            int: The number of encoder output channels.
wuyuefeng's avatar
wuyuefeng committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        """
        self.encoder_layers = spconv.SparseSequential()

        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
                if i != 0 and j == 0:
                    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(
                        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}'
            stage_layers = spconv.SparseSequential(*blocks_list)
            self.encoder_layers.add_module(stage_name, stage_layers)
        return out_channels