rw_cpu.cpp 1.37 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
#include "rw_cpu.h"
rusty1s's avatar
rusty1s committed
2
3
4

#include "utils.h"

rusty1s's avatar
rusty1s committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
torch::Tensor random_walk_cpu(torch::Tensor rowptr, torch::Tensor col,
                              torch::Tensor start, int64_t walk_length,
                              double p, double q) {
  CHECK_CPU(rowptr);
  CHECK_CPU(col);
  CHECK_CPU(start);

  CHECK_INPUT(rowptr.dim() == 1);
  CHECK_INPUT(col.dim() == 1);
  CHECK_INPUT(start.dim() == 1);

  auto rand = torch::rand({start.size(0), walk_length},
                          start.options().dtype(torch::kFloat));

rusty1s's avatar
rusty1s committed
19
  auto out = torch::empty({start.size(0), walk_length + 1}, start.options());
rusty1s's avatar
rusty1s committed
20
21
22
23
24
25
26
27
28
29
30
31

  auto rowptr_data = rowptr.data_ptr<int64_t>();
  auto col_data = col.data_ptr<int64_t>();
  auto start_data = start.data_ptr<int64_t>();
  auto rand_data = rand.data_ptr<float>();
  auto out_data = out.data_ptr<int64_t>();

  for (auto n = 0; n < start.size(0); n++) {
    auto cur = start_data[n];
    auto offset = n * (walk_length + 1);
    out_data[offset] = cur;

rusty1s's avatar
rusty1s committed
32
    int64_t row_start, row_end, rnd;
rusty1s's avatar
rusty1s committed
33
    for (auto l = 1; l <= walk_length; l++) {
rusty1s's avatar
rusty1s committed
34
      row_start = rowptr_data[cur], row_end = rowptr_data[cur + 1];
rusty1s's avatar
rusty1s committed
35
36
37
38
39
40
41
      if (row_end - row_start == 0) {
        cur = n;
      } else {
        rnd = int64_t(rand_data[n * walk_length + (l - 1)] *
                      (row_end - row_start));
        cur = col_data[row_start + rnd];
      }
rusty1s's avatar
rusty1s committed
42
      out_data[offset + l] = cur;
rusty1s's avatar
rusty1s committed
43
44
45
46
47
    }
  }

  return out;
}