knn.py 2.3 KB
Newer Older
1
2
3
4
5
6
7
import torch
from torch.autograd import Function

from . import knn_ext


class KNN(Function):
8
9
10
    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>`_.
11
12
13
14
15
16
17
18

    Find k-nearest points.
    """

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

        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.
30
                defaults to False. Should not explicitly use this keyword
Yezhen Cong's avatar
Yezhen Cong committed
31
                when calling knn (=KNN.apply), just add the fourth param.
32
33

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

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

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

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

        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)

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

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

61
62
63
        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()
64
65
66
67
68
        ctx.mark_non_differentiable(idx)
        return idx

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


knn = KNN.apply