dgcnn_gf_module.py 8.72 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
2
3
from typing import List, Optional, Union

4
5
import torch
from mmcv.cnn import ConvModule
6
from mmcv.ops.group_points import GroupAll, QueryAndGroup, grouping_operation
7
from torch import Tensor
8
9
10
from torch import nn as nn
from torch.nn import functional as F

11
12
from mmdet3d.utils import ConfigType

13
14
15
16
17

class BaseDGCNNGFModule(nn.Module):
    """Base module for point graph feature module used in DGCNN.

    Args:
18
19
20
21
22
23
24
        radii (List[float]): List of radius in each knn or ball query.
        sample_nums (List[int]): Number of samples in each knn or ball query.
        mlp_channels (List[List[int]]): Specify of the dgcnn before the global
            pooling for each graph feature module.
        knn_modes (List[str]): Type of KNN method, valid mode
            ['F-KNN', 'D-KNN']. Defaults to ['F-KNN'].
        dilated_group (bool): Whether to use dilated ball query.
25
            Defaults to False.
26
        use_xyz (bool): Whether to use xyz as point features.
27
            Defaults to True.
28
29
30
31
32
33
34
        pool_mode (str): Type of pooling method. Defaults to 'max'.
        normalize_xyz (bool): If ball query, whether to normalize local XYZ
            with radius. Defaults to False.
        grouper_return_grouped_xyz (bool): Whether to return grouped xyz in
            `QueryAndGroup`. Defaults to False.
        grouper_return_grouped_idx (bool): Whether to return grouped idx in
            `QueryAndGroup`. Defaults to False.
35
36
37
    """

    def __init__(self,
38
39
40
41
42
43
44
45
46
47
                 radii: List[float],
                 sample_nums: List[int],
                 mlp_channels: List[List[int]],
                 knn_modes: List[str] = ['F-KNN'],
                 dilated_group: bool = False,
                 use_xyz: bool = True,
                 pool_mode: str = 'max',
                 normalize_xyz: bool = False,
                 grouper_return_grouped_xyz: bool = False,
                 grouper_return_grouped_idx: bool = False) -> None:
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        super(BaseDGCNNGFModule, self).__init__()

        assert len(sample_nums) == len(
            mlp_channels
        ), 'Num_samples and mlp_channels should have the same length.'
        assert pool_mode in ['max', 'avg'
                             ], "Pool_mode should be one of ['max', 'avg']."
        assert isinstance(knn_modes, list) or isinstance(
            knn_modes, tuple), 'The type of knn_modes should be list or tuple.'

        if isinstance(mlp_channels, tuple):
            mlp_channels = list(map(list, mlp_channels))
        self.mlp_channels = mlp_channels

        self.pool_mode = pool_mode
        self.groupers = nn.ModuleList()
        self.mlps = nn.ModuleList()
        self.knn_modes = knn_modes

        for i in range(len(sample_nums)):
            sample_num = sample_nums[i]
            if sample_num is not None:
                if self.knn_modes[i] == 'D-KNN':
                    grouper = QueryAndGroup(
                        radii[i],
                        sample_num,
                        use_xyz=use_xyz,
                        normalize_xyz=normalize_xyz,
                        return_grouped_xyz=grouper_return_grouped_xyz,
                        return_grouped_idx=True)
                else:
                    grouper = QueryAndGroup(
                        radii[i],
                        sample_num,
                        use_xyz=use_xyz,
                        normalize_xyz=normalize_xyz,
                        return_grouped_xyz=grouper_return_grouped_xyz,
                        return_grouped_idx=grouper_return_grouped_idx)
            else:
                grouper = GroupAll(use_xyz)
            self.groupers.append(grouper)

90
    def _pool_features(self, features: Tensor) -> Tensor:
91
92
93
        """Perform feature aggregation using pooling operation.

        Args:
94
95
            features (Tensor): (B, C, N, K) Features of locally grouped
                points before pooling.
96
97

        Returns:
98
            Tensor: (B, C, N) Pooled features aggregating local information.
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        """
        if self.pool_mode == 'max':
            # (B, C, N, 1)
            new_features = F.max_pool2d(
                features, kernel_size=[1, features.size(3)])
        elif self.pool_mode == '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()

113
    def forward(self, points: Tensor) -> Tensor:
114
115
116
        """forward.

        Args:
117
            points (Tensor): (B, N, C) Input points.
118
119

        Returns:
120
121
            Tensor: (B, N, C1) New points generated from each graph
            feature module.
122
123
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
159
160
161
        """
        new_points_list = [points]

        for i in range(len(self.groupers)):

            new_points = new_points_list[i]
            new_points_trans = new_points.transpose(
                1, 2).contiguous()  # (B, C, N)

            if self.knn_modes[i] == 'D-KNN':
                # (B, N, C) -> (B, N, K)
                idx = self.groupers[i](new_points[..., -3:].contiguous(),
                                       new_points[..., -3:].contiguous())[-1]

                grouped_results = grouping_operation(
                    new_points_trans, idx)  # (B, C, N) -> (B, C, N, K)
                grouped_results -= new_points_trans.unsqueeze(-1)
            else:
                grouped_results = self.groupers[i](
                    new_points, new_points)  # (B, N, C) -> (B, C, N, K)

            new_points = new_points_trans.unsqueeze(-1).repeat(
                1, 1, 1, grouped_results.shape[-1])
            new_points = torch.cat([grouped_results, new_points], dim=1)

            # (B, mlp[-1], N, K)
            new_points = self.mlps[i](new_points)

            # (B, mlp[-1], N)
            new_points = self._pool_features(new_points)
            new_points = new_points.transpose(1, 2).contiguous()
            new_points_list.append(new_points)

        return new_points


class DGCNNGFModule(BaseDGCNNGFModule):
    """Point graph feature module used in DGCNN.

    Args:
162
163
        mlp_channels (List[int]): Specify of the dgcnn before the global
            pooling for each graph feature module.
164
165
        num_sample (int, optional): Number of samples in each knn or ball
            query. Defaults to None.
166
167
168
169
        knn_mode (str): Type of KNN method, valid mode ['F-KNN', 'D-KNN'].
            Defaults to 'F-KNN'.
        radius (float, optional): Radius to group with. Defaults to None.
        dilated_group (bool): Whether to use dilated ball query.
170
            Defaults to False.
171
172
173
        norm_cfg (:obj:`ConfigDict` or dict): Config dict for normalization
            layer. Defaults to dict(type='BN2d').
        act_cfg (:obj:`ConfigDict` or dict): Config dict for activation layer.
174
            Defaults to dict(type='ReLU').
175
176
177
178
179
180
        use_xyz (bool): Whether to use xyz as point features. Defaults to True.
        pool_mode (str): Type of pooling method. Defaults to 'max'.
        normalize_xyz (bool): If ball query, whether to normalize local XYZ
            with radius. Defaults to False.
        bias (bool or str): If specified as `auto`, it will be decided by
            `norm_cfg`. `bias` will be set as True if `norm_cfg` is None,
181
182
183
184
            otherwise False. Defaults to 'auto'.
    """

    def __init__(self,
185
186
187
188
189
190
191
192
193
194
195
                 mlp_channels: List[int],
                 num_sample: Optional[int] = None,
                 knn_mode: str = 'F-KNN',
                 radius: Optional[float] = None,
                 dilated_group: bool = False,
                 norm_cfg: ConfigType = dict(type='BN2d'),
                 act_cfg: ConfigType = dict(type='ReLU'),
                 use_xyz: bool = True,
                 pool_mode: str = 'max',
                 normalize_xyz: bool = False,
                 bias: Union[bool, str] = 'auto') -> None:
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        super(DGCNNGFModule, self).__init__(
            mlp_channels=[mlp_channels],
            sample_nums=[num_sample],
            knn_modes=[knn_mode],
            radii=[radius],
            use_xyz=use_xyz,
            pool_mode=pool_mode,
            normalize_xyz=normalize_xyz,
            dilated_group=dilated_group)

        for i in range(len(self.mlp_channels)):
            mlp_channel = self.mlp_channels[i]

            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,
                        act_cfg=act_cfg,
                        bias=bias))
            self.mlps.append(mlp)