vote_module.py 7.31 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
wuyuefeng's avatar
wuyuefeng committed
2
import torch
3
from mmcv import is_tuple_of
wuyuefeng's avatar
wuyuefeng committed
4
from mmcv.cnn import ConvModule
zhangwenwei's avatar
zhangwenwei committed
5
from torch import nn as nn
wuyuefeng's avatar
Votenet  
wuyuefeng committed
6
7

from mmdet3d.models.builder import build_loss
wuyuefeng's avatar
wuyuefeng committed
8
9
10
11
12
13
14
15
16


class VoteModule(nn.Module):
    """Vote module.

    Generate votes from seed point features.

    Args:
        in_channels (int): Number of channels of seed point features.
17
18
19
20
21
22
23
24
25
        vote_per_seed (int, optional): Number of votes generated from
            each seed point. Default: 1.
        gt_per_seed (int, optional): Number of ground truth votes generated
            from each seed point. Default: 3.
        num_points (int, optional): Number of points to be used for voting.
            Default: 1.
        conv_channels (tuple[int], optional): Out channels of vote
            generating convolution. Default: (16, 16).
        conv_cfg (dict, optional): Config of convolution.
wuyuefeng's avatar
wuyuefeng committed
26
            Default: dict(type='Conv1d').
27
        norm_cfg (dict, optional): Config of normalization.
wuyuefeng's avatar
wuyuefeng committed
28
            Default: dict(type='BN1d').
29
        norm_feats (bool, optional): Whether to normalize features.
wuyuefeng's avatar
wuyuefeng committed
30
            Default: True.
31
        with_res_feat (bool, optional): Whether to predict residual features.
32
            Default: True.
33
34
35
        vote_xyz_range (list[float], optional):
            The range of points translation. Default: None.
        vote_loss (dict, optional): Config of vote loss. Default: None.
wuyuefeng's avatar
wuyuefeng committed
36
37
38
39
40
41
    """

    def __init__(self,
                 in_channels,
                 vote_per_seed=1,
                 gt_per_seed=3,
42
                 num_points=-1,
wuyuefeng's avatar
wuyuefeng committed
43
44
45
                 conv_channels=(16, 16),
                 conv_cfg=dict(type='Conv1d'),
                 norm_cfg=dict(type='BN1d'),
46
                 act_cfg=dict(type='ReLU'),
wuyuefeng's avatar
wuyuefeng committed
47
                 norm_feats=True,
48
49
                 with_res_feat=True,
                 vote_xyz_range=None,
wuyuefeng's avatar
Votenet  
wuyuefeng committed
50
                 vote_loss=None):
wuyuefeng's avatar
wuyuefeng committed
51
52
53
54
        super().__init__()
        self.in_channels = in_channels
        self.vote_per_seed = vote_per_seed
        self.gt_per_seed = gt_per_seed
55
        self.num_points = num_points
wuyuefeng's avatar
wuyuefeng committed
56
        self.norm_feats = norm_feats
57
58
59
60
61
62
63
        self.with_res_feat = with_res_feat

        assert vote_xyz_range is None or is_tuple_of(vote_xyz_range, float)
        self.vote_xyz_range = vote_xyz_range

        if vote_loss is not None:
            self.vote_loss = build_loss(vote_loss)
wuyuefeng's avatar
wuyuefeng committed
64
65
66
67
68
69
70
71
72
73
74
75

        prev_channels = in_channels
        vote_conv_list = list()
        for k in range(len(conv_channels)):
            vote_conv_list.append(
                ConvModule(
                    prev_channels,
                    conv_channels[k],
                    1,
                    padding=0,
                    conv_cfg=conv_cfg,
                    norm_cfg=norm_cfg,
76
                    act_cfg=act_cfg,
wuyuefeng's avatar
wuyuefeng committed
77
78
79
80
81
82
                    bias=True,
                    inplace=True))
            prev_channels = conv_channels[k]
        self.vote_conv = nn.Sequential(*vote_conv_list)

        # conv_out predicts coordinate and residual features
83
84
85
86
        if with_res_feat:
            out_channel = (3 + in_channels) * self.vote_per_seed
        else:
            out_channel = 3 * self.vote_per_seed
wuyuefeng's avatar
wuyuefeng committed
87
88
89
90
91
92
        self.conv_out = nn.Conv1d(prev_channels, out_channel, 1)

    def forward(self, seed_points, seed_feats):
        """forward.

        Args:
zhangwenwei's avatar
zhangwenwei committed
93
94
95
96
            seed_points (torch.Tensor): Coordinate of the seed
                points in shape (B, N, 3).
            seed_feats (torch.Tensor): Features of the seed points in shape
                (B, C, N).
wuyuefeng's avatar
wuyuefeng committed
97
98

        Returns:
99
100
            tuple[torch.Tensor]:

101
                - vote_points: Voted xyz based on the seed points
zhangwenwei's avatar
zhangwenwei committed
102
                    with shape (B, M, 3), ``M=num_seed*vote_per_seed``.
103
104
                - vote_features: Voted features based on the seed points with
                    shape (B, C, M) where ``M=num_seed*vote_per_seed``,
zhangwenwei's avatar
zhangwenwei committed
105
                    ``C=vote_feature_dim``.
wuyuefeng's avatar
wuyuefeng committed
106
        """
107
108
109
110
111
112
113
        if self.num_points != -1:
            assert self.num_points < seed_points.shape[1], \
                f'Number of vote points ({self.num_points}) should be '\
                f'smaller than seed points size ({seed_points.shape[1]})'
            seed_points = seed_points[:, :self.num_points]
            seed_feats = seed_feats[..., :self.num_points]

wuyuefeng's avatar
wuyuefeng committed
114
115
116
117
118
119
120
121
122
        batch_size, feat_channels, num_seed = seed_feats.shape
        num_vote = num_seed * self.vote_per_seed
        x = self.vote_conv(seed_feats)
        # (batch_size, (3+out_dim)*vote_per_seed, num_seed)
        votes = self.conv_out(x)

        votes = votes.transpose(2, 1).view(batch_size, num_seed,
                                           self.vote_per_seed, -1)

123
124
125
126
127
128
129
130
131
132
133
134
        offset = votes[:, :, :, 0:3]
        if self.vote_xyz_range is not None:
            limited_offset_list = []
            for axis in range(len(self.vote_xyz_range)):
                limited_offset_list.append(offset[..., axis].clamp(
                    min=-self.vote_xyz_range[axis],
                    max=self.vote_xyz_range[axis]))
            limited_offset = torch.stack(limited_offset_list, -1)
            vote_points = (seed_points.unsqueeze(2) +
                           limited_offset).contiguous()
        else:
            vote_points = (seed_points.unsqueeze(2) + offset).contiguous()
wuyuefeng's avatar
wuyuefeng committed
135
        vote_points = vote_points.view(batch_size, num_vote, 3)
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        offset = offset.reshape(batch_size, num_vote, 3).transpose(2, 1)

        if self.with_res_feat:
            res_feats = votes[:, :, :, 3:]
            vote_feats = (seed_feats.transpose(2, 1).unsqueeze(2) +
                          res_feats).contiguous()
            vote_feats = vote_feats.view(batch_size,
                                         num_vote, feat_channels).transpose(
                                             2, 1).contiguous()

            if self.norm_feats:
                features_norm = torch.norm(vote_feats, p=2, dim=1)
                vote_feats = vote_feats.div(features_norm.unsqueeze(1))
        else:
            vote_feats = seed_feats
        return vote_points, vote_feats, offset
wuyuefeng's avatar
wuyuefeng committed
152
153
154
155
156
157

    def get_loss(self, seed_points, vote_points, seed_indices,
                 vote_targets_mask, vote_targets):
        """Calculate loss of voting module.

        Args:
zhangwenwei's avatar
zhangwenwei committed
158
159
160
161
162
            seed_points (torch.Tensor): Coordinate of the seed points.
            vote_points (torch.Tensor): Coordinate of the vote points.
            seed_indices (torch.Tensor): Indices of seed points in raw points.
            vote_targets_mask (torch.Tensor): Mask of valid vote targets.
            vote_targets (torch.Tensor): Targets of votes.
wuyuefeng's avatar
wuyuefeng committed
163
164

        Returns:
zhangwenwei's avatar
zhangwenwei committed
165
            torch.Tensor: Weighted vote loss.
wuyuefeng's avatar
wuyuefeng committed
166
167
168
169
170
        """
        batch_size, num_seed = seed_points.shape[:2]

        seed_gt_votes_mask = torch.gather(vote_targets_mask, 1,
                                          seed_indices).float()
wuyuefeng's avatar
Votenet  
wuyuefeng committed
171

wuyuefeng's avatar
wuyuefeng committed
172
173
174
        seed_indices_expand = seed_indices.unsqueeze(-1).repeat(
            1, 1, 3 * self.gt_per_seed)
        seed_gt_votes = torch.gather(vote_targets, 1, seed_indices_expand)
encore-zhou's avatar
encore-zhou committed
175
        seed_gt_votes += seed_points.repeat(1, 1, self.gt_per_seed)
wuyuefeng's avatar
wuyuefeng committed
176

wuyuefeng's avatar
Votenet  
wuyuefeng committed
177
178
        weight = seed_gt_votes_mask / (torch.sum(seed_gt_votes_mask) + 1e-6)
        distance = self.vote_loss(
wuyuefeng's avatar
wuyuefeng committed
179
180
            vote_points.view(batch_size * num_seed, -1, 3),
            seed_gt_votes.view(batch_size * num_seed, -1, 3),
wuyuefeng's avatar
Votenet  
wuyuefeng committed
181
182
            dst_weight=weight.view(batch_size * num_seed, 1))[1]
        vote_loss = torch.sum(torch.min(distance, dim=1)[0])
wuyuefeng's avatar
wuyuefeng committed
183

wuyuefeng's avatar
Votenet  
wuyuefeng committed
184
        return vote_loss