knn.cpp 2.11 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
5
6
#include <Python.h>
#include <torch/script.h>

#ifdef WITH_CUDA
#include "cuda/knn_cuda.h"
#endif
7
#include "cpu/knn_cpu.h"
rusty1s's avatar
rusty1s committed
8
9
10
11
12

#ifdef _WIN32
PyMODINIT_FUNC PyInit__knn(void) { return NULL; }
#endif

13
14
torch::Tensor knn(torch::Tensor x, torch::Tensor y, torch::optional<torch::Tensor> ptr_x,
                  torch::optional<torch::Tensor> ptr_y, int64_t k, bool cosine, int64_t n_threads) {
rusty1s's avatar
rusty1s committed
15
16
  if (x.device().is_cuda()) {
#ifdef WITH_CUDA
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  if (!(ptr_x.has_value()) && !(ptr_y.has_value())) {
    auto batch_x = torch::tensor({0,torch::size(x,0)}).to(torch::kLong).to(torch::kCUDA);
    auto batch_y = torch::tensor({0,torch::size(y,0)}).to(torch::kLong).to(torch::kCUDA);
    return knn_cuda(x, y, batch_x, batch_y, k, cosine);
  }
  else if (!(ptr_x.has_value())) {
    auto batch_x = torch::tensor({0,torch::size(x,0)}).to(torch::kLong).to(torch::kCUDA);
    auto batch_y = ptr_y.value();
    return knn_cuda(x, y, batch_x, batch_y, k, cosine);
  }
  else if (!(ptr_y.has_value())) {
    auto batch_x = ptr_x.value();
    auto batch_y = torch::tensor({0,torch::size(y,0)}).to(torch::kLong).to(torch::kCUDA);
    return knn_cuda(x, y, batch_x, batch_y, k, cosine);
  }
  auto batch_x = ptr_x.value();
  auto batch_y = ptr_y.value();
  return knn_cuda(x, y, batch_x, batch_y, k, cosine);
rusty1s's avatar
rusty1s committed
35
36
37
38
#else
    AT_ERROR("Not compiled with CUDA support");
#endif
  } else {
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    if (cosine) {
      AT_ERROR("`cosine` argument not supported on CPU");
    }
    if (!(ptr_x.has_value()) && !(ptr_y.has_value())) {
      return knn_cpu(x,y,k,n_threads);
    }
    if (!(ptr_x.has_value())) {
      auto batch_x = torch::zeros({torch::size(x,0)}).to(torch::kLong);
      auto batch_y = ptr_y.value();
      return batch_knn_cpu(x, y, batch_x, batch_y, k);
    }
    else if (!(ptr_y.has_value())) {
      auto batch_x = ptr_x.value();
      auto batch_y = torch::zeros({torch::size(y,0)}).to(torch::kLong);
      return batch_knn_cpu(x, y, batch_x, batch_y, k);
    }
    auto batch_x = ptr_x.value();
    auto batch_y = ptr_y.value();
    return batch_knn_cpu(x, y, batch_x, batch_y, k);
rusty1s's avatar
rusty1s committed
58
59
60
61
62
  }
}

static auto registry =
    torch::RegisterOperators().op("torch_cluster::knn", &knn);