"examples/resnet_cifar.py" did not exist on "02ceae8327f894d95ec13c80403d515f375f0f93"
point_sa_module.py 8.85 KB
Newer Older
wuyuefeng's avatar
wuyuefeng committed
1
2
import torch
from mmcv.cnn import ConvModule
zhangwenwei's avatar
zhangwenwei committed
3
4
5
from torch import nn as nn
from torch.nn import functional as F
from typing import List
wuyuefeng's avatar
wuyuefeng committed
6

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


11
@SA_MODULES.register_module()
wuyuefeng's avatar
wuyuefeng committed
12
class PointSAModuleMSG(nn.Module):
zhangwenwei's avatar
zhangwenwei committed
13
14
    """Point set abstraction module with multi-scale grouping used in
    Pointnets.
wuyuefeng's avatar
wuyuefeng committed
15
16
17
18
19
20
21

    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[int]): Specify of the pointnet before
            the global pooling for each scale.
22
23
24
25
26
27
28
        fps_mod (list[str]: Type of FPS method, valid mod
            ['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.
        fps_sample_range_list (list[int]): Range of points to apply FPS.
            Default: [-1].
29
30
        dilated_group (bool): Whether to use dilated ball query.
            Default: False.
wuyuefeng's avatar
wuyuefeng committed
31
32
33
34
35
36
37
38
        norm_cfg (dict): Type of normalization method.
            Default: dict(type='BN2d').
        use_xyz (bool): Whether to use xyz.
            Default: True.
        pool_mod (str): Type of pooling method.
            Default: 'max_pool'.
        normalize_xyz (bool): Whether to normalize local XYZ with radius.
            Default: False.
39
40
41
        bias (bool | str): If specified as `auto`, it will be decided by the
            norm_cfg. Bias will be set as True if `norm_cfg` is None, otherwise
            False. Default: "auto".
wuyuefeng's avatar
wuyuefeng committed
42
43
44
45
46
47
48
    """

    def __init__(self,
                 num_point: int,
                 radii: List[float],
                 sample_nums: List[int],
                 mlp_channels: List[List[int]],
49
50
                 fps_mod: List[str] = ['D-FPS'],
                 fps_sample_range_list: List[int] = [-1],
51
                 dilated_group: bool = False,
wuyuefeng's avatar
wuyuefeng committed
52
53
54
                 norm_cfg: dict = dict(type='BN2d'),
                 use_xyz: bool = True,
                 pool_mod='max',
55
56
                 normalize_xyz: bool = False,
                 bias='auto'):
wuyuefeng's avatar
wuyuefeng committed
57
58
59
60
        super().__init__()

        assert len(radii) == len(sample_nums) == len(mlp_channels)
        assert pool_mod in ['max', 'avg']
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        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))

        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
75
76
77
78

        self.pool_mod = pool_mod
        self.groupers = nn.ModuleList()
        self.mlps = nn.ModuleList()
79
80
81
82
83
        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
84
85
86
87
88

        for i in range(len(radii)):
            radius = radii[i]
            sample_num = sample_nums[i]
            if num_point is not None:
89
90
91
92
                if dilated_group and i != 0:
                    min_radius = radii[i - 1]
                else:
                    min_radius = 0
wuyuefeng's avatar
wuyuefeng committed
93
94
95
                grouper = QueryAndGroup(
                    radius,
                    sample_num,
96
                    min_radius=min_radius,
wuyuefeng's avatar
wuyuefeng committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
                    use_xyz=use_xyz,
                    normalize_xyz=normalize_xyz)
            else:
                grouper = GroupAll(use_xyz)
            self.groupers.append(grouper)

            mlp_spec = mlp_channels[i]
            if use_xyz:
                mlp_spec[0] += 3

            mlp = nn.Sequential()
            for i in range(len(mlp_spec) - 1):
                mlp.add_module(
                    f'layer{i}',
                    ConvModule(
                        mlp_spec[i],
                        mlp_spec[i + 1],
                        kernel_size=(1, 1),
                        stride=(1, 1),
                        conv_cfg=dict(type='Conv2d'),
117
118
                        norm_cfg=norm_cfg,
                        bias=bias))
wuyuefeng's avatar
wuyuefeng committed
119
120
121
122
123
124
            self.mlps.append(mlp)

    def forward(
        self,
        points_xyz: torch.Tensor,
        features: torch.Tensor = None,
125
126
127
        indices: torch.Tensor = None,
        target_xyz: torch.Tensor = None,
    ) -> (torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor):
wuyuefeng's avatar
wuyuefeng committed
128
129
130
131
132
133
134
135
        """forward.

        Args:
            points_xyz (Tensor): (B, N, 3) xyz coordinates of the features.
            features (Tensor): (B, C, N) features of each point.
                Default: None.
            indices (Tensor): (B, num_point) Index of the features.
                Default: None.
136
            target_xyz (Tensor): (B, M, 3) new_xyz coordinates of the outputs.
wuyuefeng's avatar
wuyuefeng committed
137
138
139
140
141
142
143
144
145
146
147

        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 = []
        xyz_flipped = points_xyz.transpose(1, 2).contiguous()
148
149
150
151
152
153
154
155
156
157
        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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

        for i in range(len(self.groupers)):
            # (B, C, num_point, nsample)
            new_features = self.groupers[i](points_xyz, new_xyz, features)

            # (B, mlp[-1], num_point, nsample)
            new_features = self.mlps[i](new_features)
            if self.pool_mod == 'max':
                # (B, mlp[-1], num_point, 1)
                new_features = F.max_pool2d(
                    new_features, kernel_size=[1, new_features.size(3)])
            elif self.pool_mod == 'avg':
                # (B, mlp[-1], num_point, 1)
                new_features = F.avg_pool2d(
                    new_features, kernel_size=[1, new_features.size(3)])
            else:
                raise NotImplementedError

            new_features = new_features.squeeze(-1)  # (B, mlp[-1], num_point)
            new_features_list.append(new_features)

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


182
@SA_MODULES.register_module()
wuyuefeng's avatar
wuyuefeng committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class PointSAModule(PointSAModuleMSG):
    """Point set abstraction module used in Pointnets.

    Args:
        mlp_channels (list[int]): Specify of the pointnet before
            the global pooling for each scale.
        num_point (int): Number of points.
            Default: None.
        radius (float): Radius to group with.
            Default: None.
        num_sample (int): Number of samples in each ball query.
            Default: None.
        norm_cfg (dict): Type of normalization method.
            Default: dict(type='BN2d').
        use_xyz (bool): Whether to use xyz.
            Default: True.
        pool_mod (str): Type of pooling method.
            Default: 'max_pool'.
201
202
203
204
        fps_mod (list[str]: Type of FPS method, valid mod
            ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS'].
        fps_sample_range_list (list[int]): Range of points to apply FPS.
            Default: [-1].
wuyuefeng's avatar
wuyuefeng committed
205
206
207
208
209
210
211
212
213
214
215
216
        normalize_xyz (bool): Whether to normalize local XYZ with radius.
            Default: False.
    """

    def __init__(self,
                 mlp_channels: List[int],
                 num_point: int = None,
                 radius: float = None,
                 num_sample: int = None,
                 norm_cfg: dict = dict(type='BN2d'),
                 use_xyz: bool = True,
                 pool_mod: str = 'max',
217
218
                 fps_mod: List[str] = ['D-FPS'],
                 fps_sample_range_list: List[int] = [-1],
wuyuefeng's avatar
wuyuefeng committed
219
220
221
222
223
224
225
226
227
                 normalize_xyz: bool = False):
        super().__init__(
            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,
228
229
            fps_mod=fps_mod,
            fps_sample_range_list=fps_sample_range_list,
wuyuefeng's avatar
wuyuefeng committed
230
            normalize_xyz=normalize_xyz)