sparse_encoder.py 20 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
2
3
from typing import List, Tuple

Wenbo Yu's avatar
Wenbo Yu committed
4
5
import torch
from mmcv.ops import points_in_boxes_all, three_interpolate, three_nn
6
from mmdet.models.losses import sigmoid_focal_loss, smooth_l1_loss
7
from torch import Tensor
zhangwenwei's avatar
zhangwenwei committed
8
from torch import nn as nn
zhangwenwei's avatar
zhangwenwei committed
9

zhangshilong's avatar
zhangshilong committed
10
11
from mmdet3d.models.layers import SparseBasicBlock, make_sparse_convmodule
from mmdet3d.models.layers.spconv import IS_SPCONV2_AVAILABLE
12
from mmdet3d.registry import MODELS
13
from mmdet3d.structures import BaseInstance3DBoxes
zhangwenwei's avatar
zhangwenwei committed
14

VVsssssk's avatar
VVsssssk committed
15
16
17
18
19
if IS_SPCONV2_AVAILABLE:
    from spconv.pytorch import SparseConvTensor, SparseSequential
else:
    from mmcv.ops import SparseConvTensor, SparseSequential

zhangwenwei's avatar
zhangwenwei committed
20

21
@MODELS.register_module()
zhangwenwei's avatar
zhangwenwei committed
22
class SparseEncoder(nn.Module):
zhangwenwei's avatar
zhangwenwei committed
23
    r"""Sparse encoder for SECOND and Part-A2.
wuyuefeng's avatar
wuyuefeng committed
24
25

    Args:
wangtai's avatar
wangtai committed
26
27
        in_channels (int): The number of input channels.
        sparse_shape (list[int]): The sparse shape of input tensor.
28
29
30
        order (list[str], optional): Order of conv module.
            Defaults to ('conv', 'norm', 'act').
        norm_cfg (dict, optional): Config of normalization layer. Defaults to
31
            dict(type='BN1d', eps=1e-3, momentum=0.01).
32
        base_channels (int, optional): Out channels for conv_input layer.
33
            Defaults to 16.
34
        output_channels (int, optional): Out channels for conv_out layer.
35
            Defaults to 128.
36
        encoder_channels (tuple[tuple[int]], optional):
wangtai's avatar
wangtai committed
37
            Convolutional channels of each encode block.
Wenbo Yu's avatar
Wenbo Yu committed
38
            Defaults to ((16, ), (32, 32, 32), (64, 64, 64), (64, 64, 64)).
39
40
        encoder_paddings (tuple[tuple[int]], optional):
            Paddings of each encode block.
Wenbo Yu's avatar
Wenbo Yu committed
41
            Defaults to ((1, ), (1, 1, 1), (1, 1, 1), ((0, 1, 1), 1, 1)).
42
43
        block_type (str, optional): Type of the block to use.
            Defaults to 'conv_module'.
44
45
        return_middle_feats (bool): Whether output middle features.
            Default to False.
wuyuefeng's avatar
wuyuefeng committed
46
    """
zhangwenwei's avatar
zhangwenwei committed
47
48
49

    def __init__(self,
                 in_channels,
wuyuefeng's avatar
wuyuefeng committed
50
51
52
53
54
55
56
57
                 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,
58
                                                                 1)),
59
60
                 block_type='conv_module',
                 return_middle_feats=False):
zhangwenwei's avatar
zhangwenwei committed
61
        super().__init__()
62
        assert block_type in ['conv_module', 'basicblock']
wuyuefeng's avatar
wuyuefeng committed
63
        self.sparse_shape = sparse_shape
zhangwenwei's avatar
zhangwenwei committed
64
        self.in_channels = in_channels
wuyuefeng's avatar
wuyuefeng committed
65
66
67
68
69
70
        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)
71
        self.fp16_enabled = False
72
        self.return_middle_feats = return_middle_feats
zhangwenwei's avatar
zhangwenwei committed
73
        # Spconv init all weight on its own
wuyuefeng's avatar
wuyuefeng committed
74
75
76
77
78
79
80
81

        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
82
83
84
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
85
86
87
88
89
90
91
                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
92
93
94
                3,
                norm_cfg=norm_cfg,
                padding=1,
wuyuefeng's avatar
wuyuefeng committed
95
96
97
98
                indice_key='subm1',
                conv_type='SubMConv3d')

        encoder_out_channels = self.make_encoder_layers(
99
100
101
102
            make_sparse_convmodule,
            norm_cfg,
            self.base_channels,
            block_type=block_type)
wuyuefeng's avatar
wuyuefeng committed
103
104
105
106
107
108
109
110
111
112

        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
113
114

    def forward(self, voxel_features, coors, batch_size):
zhangwenwei's avatar
zhangwenwei committed
115
        """Forward of SparseEncoder.
wuyuefeng's avatar
wuyuefeng committed
116
117

        Args:
Wenbo Yu's avatar
Wenbo Yu committed
118
119
            voxel_features (torch.Tensor): Voxel features in shape (N, C).
            coors (torch.Tensor): Coordinates in shape (N, 4),
wangtai's avatar
wangtai committed
120
121
                the columns in the order of (batch_idx, z_idx, y_idx, x_idx).
            batch_size (int): Batch size.
wuyuefeng's avatar
wuyuefeng committed
122
123

        Returns:
124
125
126
127
128
129
130
131
            torch.Tensor | tuple[torch.Tensor, list]: Return spatial features
                include:

            - spatial_features (torch.Tensor): Spatial features are out from
                the last layer.
            - encode_features (List[SparseConvTensor], optional): Middle layer
                output features. When self.return_middle_feats is True, the
                module returns middle features.
zhangwenwei's avatar
zhangwenwei committed
132
133
        """
        coors = coors.int()
134
135
        input_sp_tensor = SparseConvTensor(voxel_features, coors,
                                           self.sparse_shape, batch_size)
zhangwenwei's avatar
zhangwenwei committed
136
137
        x = self.conv_input(input_sp_tensor)

wuyuefeng's avatar
wuyuefeng committed
138
139
140
141
        encode_features = []
        for encoder_layer in self.encoder_layers:
            x = encoder_layer(x)
            encode_features.append(x)
zhangwenwei's avatar
zhangwenwei committed
142
143
144

        # for detection head
        # [200, 176, 5] -> [200, 176, 2]
wuyuefeng's avatar
wuyuefeng committed
145
        out = self.conv_out(encode_features[-1])
zhangwenwei's avatar
zhangwenwei committed
146
147
148
149
150
        spatial_features = out.dense()

        N, C, D, H, W = spatial_features.shape
        spatial_features = spatial_features.view(N, C * D, H, W)

151
152
153
154
        if self.return_middle_feats:
            return spatial_features, encode_features
        else:
            return spatial_features
zhangwenwei's avatar
zhangwenwei committed
155

156
157
158
159
160
161
    def make_encoder_layers(self,
                            make_block,
                            norm_cfg,
                            in_channels,
                            block_type='conv_module',
                            conv_cfg=dict(type='SubMConv3d')):
zhangwenwei's avatar
zhangwenwei committed
162
        """make encoder layers using sparse convs.
wuyuefeng's avatar
wuyuefeng committed
163
164

        Args:
wangtai's avatar
wangtai committed
165
166
167
            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.
168
169
170
            block_type (str, optional): Type of the block to use.
                Defaults to 'conv_module'.
            conv_cfg (dict, optional): Config of conv layer. Defaults to
171
                dict(type='SubMConv3d').
wuyuefeng's avatar
wuyuefeng committed
172
173

        Returns:
wangtai's avatar
wangtai committed
174
            int: The number of encoder output channels.
wuyuefeng's avatar
wuyuefeng committed
175
        """
176
        assert block_type in ['conv_module', 'basicblock']
177
        self.encoder_layers = SparseSequential()
wuyuefeng's avatar
wuyuefeng committed
178
179
180
181
182
183
184

        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
185
                if i != 0 and j == 0 and block_type == 'conv_module':
wuyuefeng's avatar
wuyuefeng committed
186
187
188
189
190
191
192
193
194
195
                    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'))
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
                elif block_type == 'basicblock':
                    if j == len(blocks) - 1 and i != len(
                            self.encoder_channels) - 1:
                        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(
                            SparseBasicBlock(
                                out_channels,
                                out_channels,
                                norm_cfg=norm_cfg,
                                conv_cfg=conv_cfg))
wuyuefeng's avatar
wuyuefeng committed
216
217
218
219
220
221
222
223
224
225
226
227
                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}'
228
            stage_layers = SparseSequential(*blocks_list)
wuyuefeng's avatar
wuyuefeng committed
229
230
            self.encoder_layers.add_module(stage_name, stage_layers)
        return out_channels
Wenbo Yu's avatar
Wenbo Yu committed
231
232


VVsssssk's avatar
VVsssssk committed
233
@MODELS.register_module()
Wenbo Yu's avatar
Wenbo Yu committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
class SparseEncoderSASSD(SparseEncoder):
    r"""Sparse encoder for `SASSD <https://github.com/skyhehe123/SA-SSD>`_

    Args:
        in_channels (int): The number of input channels.
        sparse_shape (list[int]): The sparse shape of input tensor.
        order (list[str], optional): Order of conv module.
            Defaults to ('conv', 'norm', 'act').
        norm_cfg (dict, optional): Config of normalization layer. Defaults to
            dict(type='BN1d', eps=1e-3, momentum=0.01).
        base_channels (int, optional): Out channels for conv_input layer.
            Defaults to 16.
        output_channels (int, optional): Out channels for conv_out layer.
            Defaults to 128.
        encoder_channels (tuple[tuple[int]], optional):
            Convolutional channels of each encode block.
            Defaults to ((16, ), (32, 32, 32), (64, 64, 64), (64, 64, 64)).
        encoder_paddings (tuple[tuple[int]], optional):
            Paddings of each encode block.
            Defaults to ((1, ), (1, 1, 1), (1, 1, 1), ((0, 1, 1), 1, 1)).
        block_type (str, optional): Type of the block to use.
            Defaults to 'conv_module'.
    """

    def __init__(self,
259
260
261
262
263
264
265
266
267
268
269
                 in_channels: int,
                 sparse_shape: List[int],
                 order: Tuple[str] = ('conv', 'norm', 'act'),
                 norm_cfg: dict = dict(type='BN1d', eps=1e-3, momentum=0.01),
                 base_channels: int = 16,
                 output_channels: int = 128,
                 encoder_channels: Tuple[tuple] = ((16, ), (32, 32, 32),
                                                   (64, 64, 64), (64, 64, 64)),
                 encoder_paddings: Tuple[tuple] = ((1, ), (1, 1, 1), (1, 1, 1),
                                                   ((0, 1, 1), 1, 1)),
                 block_type: str = 'conv_module'):
Wenbo Yu's avatar
Wenbo Yu committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        super(SparseEncoderSASSD, self).__init__(
            in_channels=in_channels,
            sparse_shape=sparse_shape,
            order=order,
            norm_cfg=norm_cfg,
            base_channels=base_channels,
            output_channels=output_channels,
            encoder_channels=encoder_channels,
            encoder_paddings=encoder_paddings,
            block_type=block_type)

        self.point_fc = nn.Linear(112, 64, bias=False)
        self.point_cls = nn.Linear(64, 1, bias=False)
        self.point_reg = nn.Linear(64, 3, bias=False)

285
286
287
288
289
    def forward(self,
                voxel_features: Tensor,
                coors: Tensor,
                batch_size: Tensor,
                test_mode: bool = False) -> Tuple[Tensor, tuple]:
Wenbo Yu's avatar
Wenbo Yu committed
290
291
292
293
294
295
296
297
298
299
300
        """Forward of SparseEncoder.

        Args:
            voxel_features (torch.Tensor): Voxel features in shape (N, C).
            coors (torch.Tensor): Coordinates in shape (N, 4),
                the columns in the order of (batch_idx, z_idx, y_idx, x_idx).
            batch_size (int): Batch size.
            test_mode (bool, optional): Whether in test mode.
                Defaults to False.

        Returns:
301
            Tensor: Backbone features.
Wenbo Yu's avatar
Wenbo Yu committed
302
            tuple[torch.Tensor]: Mean feature value of the points,
303
                Classification result of the points,
Wenbo Yu's avatar
Wenbo Yu committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
                Regression offsets of the points.
        """
        coors = coors.int()
        input_sp_tensor = SparseConvTensor(voxel_features, coors,
                                           self.sparse_shape, batch_size)
        x = self.conv_input(input_sp_tensor)

        encode_features = []
        for encoder_layer in self.encoder_layers:
            x = encoder_layer(x)
            encode_features.append(x)

        # for detection head
        # [200, 176, 5] -> [200, 176, 2]
        out = self.conv_out(encode_features[-1])
        spatial_features = out.dense()

        N, C, D, H, W = spatial_features.shape
        spatial_features = spatial_features.view(N, C * D, H, W)

        if test_mode:
            return spatial_features, None

        points_mean = torch.zeros_like(voxel_features)
        points_mean[:, 0] = coors[:, 0]
        points_mean[:, 1:] = voxel_features[:, :3]

        # auxiliary network
        p0 = self.make_auxiliary_points(
            encode_features[0],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.1, .1, .2))

        p1 = self.make_auxiliary_points(
            encode_features[1],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.2, .2, .4))

        p2 = self.make_auxiliary_points(
            encode_features[2],
            points_mean,
            offset=(0, -40., -3.),
            voxel_size=(.4, .4, .8))

        pointwise = torch.cat([p0, p1, p2], dim=-1)
        pointwise = self.point_fc(pointwise)
        point_cls = self.point_cls(pointwise)
        point_reg = self.point_reg(pointwise)
        point_misc = (points_mean, point_cls, point_reg)

        return spatial_features, point_misc

358
359
360
361
    def get_auxiliary_targets(self,
                              points_feats: Tensor,
                              gt_bboxes_3d: List[BaseInstance3DBoxes],
                              enlarge: float = 1.0) -> Tuple[Tensor, Tensor]:
Wenbo Yu's avatar
Wenbo Yu committed
362
363
364
        """Get auxiliary target.

        Args:
365
366
367
368
            points_feats (torch.Tensor): Mean features of the points.
            gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]):  Ground truth
                boxes for each sample.
            enlarge (float, optional): Enlaged scale. Defaults to 1.0.
Wenbo Yu's avatar
Wenbo Yu committed
369
370
371
372
373
374
375

        Returns:
            tuple[torch.Tensor]: Label of the points and
                center offsets of the points.
        """
        center_offsets = list()
        pts_labels = list()
376
377
378
379
        for i in range(len(gt_bboxes_3d)):
            boxes3d = gt_bboxes_3d[i].tensor.detach().clone()
            idx = torch.nonzero(points_feats[:, 0] == i).view(-1)
            point_xyz = points_feats[idx, 1:].detach().clone()
Wenbo Yu's avatar
Wenbo Yu committed
380
381
382
383

            boxes3d[:, 3:6] *= enlarge

            pts_in_flag, center_offset = self.calculate_pts_offsets(
384
                point_xyz, boxes3d)
Wenbo Yu's avatar
Wenbo Yu committed
385
386
387
388
            pts_label = pts_in_flag.max(0)[0].byte()
            pts_labels.append(pts_label)
            center_offsets.append(center_offset)

389
        center_offsets = torch.cat(center_offsets)
Wenbo Yu's avatar
Wenbo Yu committed
390
391
392
393
        pts_labels = torch.cat(pts_labels).to(center_offsets.device)

        return pts_labels, center_offsets

394
395
    def calculate_pts_offsets(self, points: Tensor,
                              bboxes_3d: Tensor) -> Tuple[Tensor, Tensor]:
Wenbo Yu's avatar
Wenbo Yu committed
396
397
398
399
        """Find all boxes in which each point is, as well as the offsets from
        the box centers.

        Args:
400
401
            points (torch.Tensor): [M, 3], [x, y, z] in LiDAR coordinate
            bboxes_3d (torch.Tensor): [T, 7],
Wenbo Yu's avatar
Wenbo Yu committed
402
403
404
405
406
407
408
409
410
411
                num_valid_boxes <= T, [x, y, z, x_size, y_size, z_size, rz],
                (x, y, z) is the bottom center.

        Returns:
            tuple[torch.Tensor]: Point indices of boxes with the shape of
                (T, M). Default background = 0.
                And offsets from the box centers of points,
                if it belows to the box, with the shape of (M, 3).
                Default background = 0.
        """
412
        boxes_num = len(bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
413
414
        pts_num = len(points)

415
        box_indices = points_in_boxes_all(points[None, ...], bboxes_3d[None,
Wenbo Yu's avatar
Wenbo Yu committed
416
                                                                       ...])
417
        pts_indices = box_indices.squeeze(0).transpose(0, 1)
Wenbo Yu's avatar
Wenbo Yu committed
418
419
420
421
422
        center_offsets = torch.zeros_like(points).to(points.device)

        for i in range(boxes_num):
            for j in range(pts_num):
                if pts_indices[i][j] == 1:
423
424
                    center_offsets[j][0] = points[j][0] - bboxes_3d[i][0]
                    center_offsets[j][1] = points[j][1] - bboxes_3d[i][1]
Wenbo Yu's avatar
Wenbo Yu committed
425
                    center_offsets[j][2] = (
426
427
428
                        points[j][2] -
                        (bboxes_3d[i][2] + bboxes_3d[i][2] / 2.0))
        return pts_indices, center_offsets
Wenbo Yu's avatar
Wenbo Yu committed
429

430
431
    def aux_loss(self, points: Tensor, point_cls: Tensor, point_reg: Tensor,
                 gt_bboxes_3d: Tensor) -> dict:
Wenbo Yu's avatar
Wenbo Yu committed
432
433
434
435
        """Calculate auxiliary loss.

        Args:
            points (torch.Tensor): Mean feature value of the points.
436
            point_cls (torch.Tensor): Classification result of the points.
Wenbo Yu's avatar
Wenbo Yu committed
437
            point_reg (torch.Tensor): Regression offsets of the points.
438
            gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]): Ground truth
Wenbo Yu's avatar
Wenbo Yu committed
439
440
441
                boxes for each sample.

        Returns:
442
            dict: Auxiliary loss.
Wenbo Yu's avatar
Wenbo Yu committed
443
        """
444
        num_boxes = len(gt_bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
445
        pts_labels, center_targets = self.get_auxiliary_targets(
446
            points, gt_bboxes_3d)
Wenbo Yu's avatar
Wenbo Yu committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

        rpn_cls_target = pts_labels.long()
        pos = (pts_labels > 0).float()
        neg = (pts_labels == 0).float()

        pos_normalizer = pos.sum().clamp(min=1.0)

        cls_weights = pos + neg
        reg_weights = pos
        reg_weights = reg_weights / pos_normalizer

        aux_loss_cls = sigmoid_focal_loss(
            point_cls,
            rpn_cls_target,
            weight=cls_weights,
            avg_factor=pos_normalizer)

        aux_loss_cls /= num_boxes

        weight = reg_weights[..., None]
        aux_loss_reg = smooth_l1_loss(point_reg, center_targets, beta=1 / 9.)
        aux_loss_reg = torch.sum(aux_loss_reg * weight)[None]
        aux_loss_reg /= num_boxes

        aux_loss_cls, aux_loss_reg = [aux_loss_cls], [aux_loss_reg]

        return dict(aux_loss_cls=aux_loss_cls, aux_loss_reg=aux_loss_reg)

475
476
477
478
479
480
481
    def make_auxiliary_points(
        self,
        source_tensor: Tensor,
        target: Tensor,
        offset: Tuple = (0., -40., -3.),
        voxel_size: Tuple = (.05, .05, .1)
    ) -> Tensor:
Wenbo Yu's avatar
Wenbo Yu committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
        """Make auxiliary points for loss computation.

        Args:
            source_tensor (torch.Tensor): (M, C) features to be propigated.
            target (torch.Tensor): (N, 4) bxyz positions of the
                target features.
            offset (tuple[float], optional): Voxelization offset.
                Defaults to (0., -40., -3.)
            voxel_size (tuple[float], optional): Voxelization size.
                Defaults to (.05, .05, .1)

        Returns:
            torch.Tensor: (N, C) tensor of the features of the target features.
        """
        # Tansfer tensor to points
        source = source_tensor.indices.float()
        offset = torch.Tensor(offset).to(source.device)
        voxel_size = torch.Tensor(voxel_size).to(source.device)
        source[:, 1:] = (
            source[:, [3, 2, 1]] * voxel_size + offset + .5 * voxel_size)

        source_feats = source_tensor.features[None, ...].transpose(1, 2)

        # Interplate auxiliary points
        dist, idx = three_nn(target[None, ...], source[None, ...])
        dist_recip = 1.0 / (dist + 1e-8)
        norm = torch.sum(dist_recip, dim=2, keepdim=True)
        weight = dist_recip / norm
        new_features = three_interpolate(source_feats.contiguous(), idx,
                                         weight)

        return new_features.squeeze(0).transpose(0, 1)