knn.py 2.34 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
2
3
4
5
6
7
8
import torch
from torch.autograd import Function

from . import knn_ext


class KNN(Function):
9
10
11
    r"""KNN (CUDA) based on heap data structure.
    Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/
    scene_seg/lib/pointops/src/knnquery_heap>`_.
12
13
14
15
16
17
18
19

    Find k-nearest points.
    """

    @staticmethod
    def forward(ctx,
                k: int,
                xyz: torch.Tensor,
20
                center_xyz: torch.Tensor = None,
21
                transposed: bool = False) -> torch.Tensor:
22
        """Forward.
23
24
25
26
27
28
29
30

        Args:
            k (int): number of nearest neighbors.
            xyz (Tensor): (B, N, 3) if transposed == False, else (B, 3, N).
                xyz coordinates of the features.
            center_xyz (Tensor): (B, npoint, 3) if transposed == False,
                else (B, 3, npoint). centers of the knn query.
            transposed (bool): whether the input tensors are transposed.
31
                defaults to False. Should not explicitly use this keyword
Yezhen Cong's avatar
Yezhen Cong committed
32
                when calling knn (=KNN.apply), just add the fourth param.
33
34

        Returns:
35
            Tensor: (B, k, npoint) tensor with the indices of
36
37
38
39
                the features that form k-nearest neighbours.
        """
        assert k > 0

40
41
42
43
        if center_xyz is None:
            center_xyz = xyz

        if transposed:
44
45
46
            xyz = xyz.transpose(2, 1).contiguous()
            center_xyz = center_xyz.transpose(2, 1).contiguous()

47
48
        assert xyz.is_contiguous()  # [B, N, 3]
        assert center_xyz.is_contiguous()  # [B, npoint, 3]
49
50
51
52
53
54
55

        center_xyz_device = center_xyz.get_device()
        assert center_xyz_device == xyz.get_device(), \
            'center_xyz and xyz should be put on the same device'
        if torch.cuda.current_device() != center_xyz_device:
            torch.cuda.set_device(center_xyz_device)

56
57
        B, npoint, _ = center_xyz.shape
        N = xyz.shape[1]
58

59
60
        idx = center_xyz.new_zeros((B, npoint, k)).int()
        dist2 = center_xyz.new_zeros((B, npoint, k)).float()
61

62
63
64
        knn_ext.knn_wrapper(B, N, npoint, k, xyz, center_xyz, idx, dist2)
        # idx shape to [B, k, npoint]
        idx = idx.transpose(2, 1).contiguous()
65
66
67
68
69
        ctx.mark_non_differentiable(idx)
        return idx

    @staticmethod
    def backward(ctx, a=None):
70
        return None, None, None
71
72
73


knn = KNN.apply