point_sa_module.py 13.2 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
wuyuefeng's avatar
wuyuefeng committed
2
3
import torch
from mmcv.cnn import ConvModule
zhangwenwei's avatar
zhangwenwei committed
4
5
from torch import nn as nn
from torch.nn import functional as F
wuyuefeng's avatar
wuyuefeng committed
6

7
8
from mmdet3d.ops import (GroupAll, PAConv, Points_Sampler, QueryAndGroup,
                         gather_points)
9
from .builder import SA_MODULES
wuyuefeng's avatar
wuyuefeng committed
10
11


12
13
class BasePointSAModule(nn.Module):
    """Base module for point set abstraction module used in PointNets.
wuyuefeng's avatar
wuyuefeng committed
14
15
16
17
18

    Args:
        num_point (int): Number of points.
        radii (list[float]): List of radius in each ball query.
        sample_nums (list[int]): Number of samples in each ball query.
19
        mlp_channels (list[list[int]]): Specify of the pointnet before
wuyuefeng's avatar
wuyuefeng committed
20
            the global pooling for each scale.
21
        fps_mod (list[str], optional): Type of FPS method, valid mod
22
23
24
25
            ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS'].
            F-FPS: using feature distances for FPS.
            D-FPS: using Euclidean distances of points for FPS.
            FS: using F-FPS and D-FPS simultaneously.
26
27
28
        fps_sample_range_list (list[int], optional):
            Range of points to apply FPS. Default: [-1].
        dilated_group (bool, optional): Whether to use dilated ball query.
29
            Default: False.
30
        use_xyz (bool, optional): Whether to use xyz.
wuyuefeng's avatar
wuyuefeng committed
31
            Default: True.
32
        pool_mod (str, optional): Type of pooling method.
wuyuefeng's avatar
wuyuefeng committed
33
            Default: 'max_pool'.
34
35
36
37
38
39
        normalize_xyz (bool, optional): Whether to normalize local XYZ
            with radius. Default: False.
        grouper_return_grouped_xyz (bool, optional): Whether to return
            grouped xyz in `QueryAndGroup`. Defaults to False.
        grouper_return_grouped_idx (bool, optional): Whether to return
            grouped idx in `QueryAndGroup`. Defaults to False.
wuyuefeng's avatar
wuyuefeng committed
40
41
42
    """

    def __init__(self,
43
44
45
46
47
48
49
50
                 num_point,
                 radii,
                 sample_nums,
                 mlp_channels,
                 fps_mod=['D-FPS'],
                 fps_sample_range_list=[-1],
                 dilated_group=False,
                 use_xyz=True,
wuyuefeng's avatar
wuyuefeng committed
51
                 pool_mod='max',
52
53
54
55
                 normalize_xyz=False,
                 grouper_return_grouped_xyz=False,
                 grouper_return_grouped_idx=False):
        super(BasePointSAModule, self).__init__()
wuyuefeng's avatar
wuyuefeng committed
56
57
58

        assert len(radii) == len(sample_nums) == len(mlp_channels)
        assert pool_mod in ['max', 'avg']
59
60
61
62
63
64
65
        assert isinstance(fps_mod, list) or isinstance(fps_mod, tuple)
        assert isinstance(fps_sample_range_list, list) or isinstance(
            fps_sample_range_list, tuple)
        assert len(fps_mod) == len(fps_sample_range_list)

        if isinstance(mlp_channels, tuple):
            mlp_channels = list(map(list, mlp_channels))
66
        self.mlp_channels = mlp_channels
67
68
69
70
71
72
73

        if isinstance(num_point, int):
            self.num_point = [num_point]
        elif isinstance(num_point, list) or isinstance(num_point, tuple):
            self.num_point = num_point
        else:
            raise NotImplementedError('Error type of num_point!')
wuyuefeng's avatar
wuyuefeng committed
74
75
76
77

        self.pool_mod = pool_mod
        self.groupers = nn.ModuleList()
        self.mlps = nn.ModuleList()
78
79
80
81
82
        self.fps_mod_list = fps_mod
        self.fps_sample_range_list = fps_sample_range_list

        self.points_sampler = Points_Sampler(self.num_point, self.fps_mod_list,
                                             self.fps_sample_range_list)
wuyuefeng's avatar
wuyuefeng committed
83
84
85
86
87

        for i in range(len(radii)):
            radius = radii[i]
            sample_num = sample_nums[i]
            if num_point is not None:
88
89
90
91
                if dilated_group and i != 0:
                    min_radius = radii[i - 1]
                else:
                    min_radius = 0
wuyuefeng's avatar
wuyuefeng committed
92
93
94
                grouper = QueryAndGroup(
                    radius,
                    sample_num,
95
                    min_radius=min_radius,
wuyuefeng's avatar
wuyuefeng committed
96
                    use_xyz=use_xyz,
97
98
99
                    normalize_xyz=normalize_xyz,
                    return_grouped_xyz=grouper_return_grouped_xyz,
                    return_grouped_idx=grouper_return_grouped_idx)
wuyuefeng's avatar
wuyuefeng committed
100
101
102
103
            else:
                grouper = GroupAll(use_xyz)
            self.groupers.append(grouper)

104
105
    def _sample_points(self, points_xyz, features, indices, target_xyz):
        """Perform point sampling based on inputs.
wuyuefeng's avatar
wuyuefeng committed
106

107
108
109
        If `indices` is specified, directly sample corresponding points.
        Else if `target_xyz` is specified, use is as sampled points.
        Otherwise sample points using `self.points_sampler`.
wuyuefeng's avatar
wuyuefeng committed
110
111
112
113
114

        Args:
            points_xyz (Tensor): (B, N, 3) xyz coordinates of the features.
            features (Tensor): (B, C, N) features of each point.
            indices (Tensor): (B, num_point) Index of the features.
115
            target_xyz (Tensor): (B, M, 3) new_xyz coordinates of the outputs.
wuyuefeng's avatar
wuyuefeng committed
116
117

        Returns:
118
119
            Tensor: (B, num_point, 3) sampled xyz coordinates of points.
            Tensor: (B, num_point) sampled points' index.
wuyuefeng's avatar
wuyuefeng committed
120
121
        """
        xyz_flipped = points_xyz.transpose(1, 2).contiguous()
122
123
124
125
126
127
128
129
130
131
        if indices is not None:
            assert (indices.shape[1] == self.num_point[0])
            new_xyz = gather_points(xyz_flipped, indices).transpose(
                1, 2).contiguous() if self.num_point is not None else None
        elif target_xyz is not None:
            new_xyz = target_xyz.contiguous()
        else:
            indices = self.points_sampler(points_xyz, features)
            new_xyz = gather_points(xyz_flipped, indices).transpose(
                1, 2).contiguous() if self.num_point is not None else None
wuyuefeng's avatar
wuyuefeng committed
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
159
160
161
162
163
164
165
166
167
168
169
        return new_xyz, indices

    def _pool_features(self, features):
        """Perform feature aggregation using pooling operation.

        Args:
            features (torch.Tensor): (B, C, N, K)
                Features of locally grouped points before pooling.

        Returns:
            torch.Tensor: (B, C, N)
                Pooled features aggregating local information.
        """
        if self.pool_mod == 'max':
            # (B, C, N, 1)
            new_features = F.max_pool2d(
                features, kernel_size=[1, features.size(3)])
        elif self.pool_mod == 'avg':
            # (B, C, N, 1)
            new_features = F.avg_pool2d(
                features, kernel_size=[1, features.size(3)])
        else:
            raise NotImplementedError

        return new_features.squeeze(-1).contiguous()

    def forward(
        self,
        points_xyz,
        features=None,
        indices=None,
        target_xyz=None,
    ):
        """forward.

        Args:
            points_xyz (Tensor): (B, N, 3) xyz coordinates of the features.
170
            features (Tensor, optional): (B, C, N) features of each point.
171
                Default: None.
172
173
174
            indices (Tensor, optional): (B, num_point) Index of the features.
                Default: None.
            target_xyz (Tensor, optional): (B, M, 3) new coords of the outputs.
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
                Default: None.

        Returns:
            Tensor: (B, M, 3) where M is the number of points.
                New features xyz.
            Tensor: (B, M, sum_k(mlps[k][-1])) where M is the number
                of points. New feature descriptors.
            Tensor: (B, M) where M is the number of points.
                Index of the features.
        """
        new_features_list = []

        # sample points, (B, num_point, 3), (B, num_point)
        new_xyz, indices = self._sample_points(points_xyz, features, indices,
                                               target_xyz)

wuyuefeng's avatar
wuyuefeng committed
191
        for i in range(len(self.groupers)):
192
193
194
195
196
            # grouped_results may contain:
            # - grouped_features: (B, C, num_point, nsample)
            # - grouped_xyz: (B, 3, num_point, nsample)
            # - grouped_idx: (B, num_point, nsample)
            grouped_results = self.groupers[i](points_xyz, new_xyz, features)
wuyuefeng's avatar
wuyuefeng committed
197
198

            # (B, mlp[-1], num_point, nsample)
199
            new_features = self.mlps[i](grouped_results)
wuyuefeng's avatar
wuyuefeng committed
200

201
202
203
204
205
206
207
208
            # this is a bit hack because PAConv outputs two values
            # we take the first one as feature
            if isinstance(self.mlps[i][0], PAConv):
                assert isinstance(new_features, tuple)
                new_features = new_features[0]

            # (B, mlp[-1], num_point)
            new_features = self._pool_features(new_features)
wuyuefeng's avatar
wuyuefeng committed
209
210
211
212
213
            new_features_list.append(new_features)

        return new_xyz, torch.cat(new_features_list, dim=1), indices


214
215
216
217
218
219
220
221
222
223
224
@SA_MODULES.register_module()
class PointSAModuleMSG(BasePointSAModule):
    """Point set abstraction module with multi-scale grouping (MSG) used in
    PointNets.

    Args:
        num_point (int): Number of points.
        radii (list[float]): List of radius in each ball query.
        sample_nums (list[int]): Number of samples in each ball query.
        mlp_channels (list[list[int]]): Specify of the pointnet before
            the global pooling for each scale.
225
        fps_mod (list[str], optional): Type of FPS method, valid mod
226
227
228
229
            ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS'].
            F-FPS: using feature distances for FPS.
            D-FPS: using Euclidean distances of points for FPS.
            FS: using F-FPS and D-FPS simultaneously.
230
231
232
        fps_sample_range_list (list[int], optional): Range of points to
            apply FPS. Default: [-1].
        dilated_group (bool, optional): Whether to use dilated ball query.
233
            Default: False.
234
        norm_cfg (dict, optional): Type of normalization method.
235
            Default: dict(type='BN2d').
236
        use_xyz (bool, optional): Whether to use xyz.
237
            Default: True.
238
        pool_mod (str, optional): Type of pooling method.
239
            Default: 'max_pool'.
240
241
242
243
244
        normalize_xyz (bool, optional): Whether to normalize local XYZ
            with radius. Default: False.
        bias (bool | str, optional): If specified as `auto`, it will be
            decided by `norm_cfg`. `bias` will be set as True if
            `norm_cfg` is None, otherwise False. Default: 'auto'.
245
246
247
248
249
250
251
252
253
254
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
280
281
282
283
284
285
286
287
288
289
290
291
    """

    def __init__(self,
                 num_point,
                 radii,
                 sample_nums,
                 mlp_channels,
                 fps_mod=['D-FPS'],
                 fps_sample_range_list=[-1],
                 dilated_group=False,
                 norm_cfg=dict(type='BN2d'),
                 use_xyz=True,
                 pool_mod='max',
                 normalize_xyz=False,
                 bias='auto'):
        super(PointSAModuleMSG, self).__init__(
            num_point=num_point,
            radii=radii,
            sample_nums=sample_nums,
            mlp_channels=mlp_channels,
            fps_mod=fps_mod,
            fps_sample_range_list=fps_sample_range_list,
            dilated_group=dilated_group,
            use_xyz=use_xyz,
            pool_mod=pool_mod,
            normalize_xyz=normalize_xyz)

        for i in range(len(self.mlp_channels)):
            mlp_channel = self.mlp_channels[i]
            if use_xyz:
                mlp_channel[0] += 3

            mlp = nn.Sequential()
            for i in range(len(mlp_channel) - 1):
                mlp.add_module(
                    f'layer{i}',
                    ConvModule(
                        mlp_channel[i],
                        mlp_channel[i + 1],
                        kernel_size=(1, 1),
                        stride=(1, 1),
                        conv_cfg=dict(type='Conv2d'),
                        norm_cfg=norm_cfg,
                        bias=bias))
            self.mlps.append(mlp)


292
@SA_MODULES.register_module()
wuyuefeng's avatar
wuyuefeng committed
293
class PointSAModule(PointSAModuleMSG):
294
295
    """Point set abstraction module with single-scale grouping (SSG) used in
    PointNets.
wuyuefeng's avatar
wuyuefeng committed
296
297
298
299

    Args:
        mlp_channels (list[int]): Specify of the pointnet before
            the global pooling for each scale.
300
        num_point (int, optional): Number of points.
wuyuefeng's avatar
wuyuefeng committed
301
            Default: None.
302
        radius (float, optional): Radius to group with.
wuyuefeng's avatar
wuyuefeng committed
303
            Default: None.
304
        num_sample (int, optional): Number of samples in each ball query.
wuyuefeng's avatar
wuyuefeng committed
305
            Default: None.
306
        norm_cfg (dict, optional): Type of normalization method.
wuyuefeng's avatar
wuyuefeng committed
307
            Default: dict(type='BN2d').
308
        use_xyz (bool, optional): Whether to use xyz.
wuyuefeng's avatar
wuyuefeng committed
309
            Default: True.
310
        pool_mod (str, optional): Type of pooling method.
wuyuefeng's avatar
wuyuefeng committed
311
            Default: 'max_pool'.
312
        fps_mod (list[str], optional): Type of FPS method, valid mod
313
            ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS'].
314
315
316
317
        fps_sample_range_list (list[int], optional): Range of points
            to apply FPS. Default: [-1].
        normalize_xyz (bool, optional): Whether to normalize local XYZ
            with radius. Default: False.
wuyuefeng's avatar
wuyuefeng committed
318
319
320
    """

    def __init__(self,
321
322
323
324
325
326
327
328
329
330
331
                 mlp_channels,
                 num_point=None,
                 radius=None,
                 num_sample=None,
                 norm_cfg=dict(type='BN2d'),
                 use_xyz=True,
                 pool_mod='max',
                 fps_mod=['D-FPS'],
                 fps_sample_range_list=[-1],
                 normalize_xyz=False):
        super(PointSAModule, self).__init__(
wuyuefeng's avatar
wuyuefeng committed
332
333
334
335
336
337
338
            mlp_channels=[mlp_channels],
            num_point=num_point,
            radii=[radius],
            sample_nums=[num_sample],
            norm_cfg=norm_cfg,
            use_xyz=use_xyz,
            pool_mod=pool_mod,
339
340
            fps_mod=fps_mod,
            fps_sample_range_list=fps_sample_range_list,
wuyuefeng's avatar
wuyuefeng committed
341
            normalize_xyz=normalize_xyz)