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

#include "utils.h"

rusty1s's avatar
rusty1s committed
5
6
7
8
#ifdef _WIN32
#include <process.h>
#endif

rusty1s's avatar
rusty1s committed
9
10
11
12
13
14
15
16
17
18
19
using namespace std;

namespace {

template <bool replace, bool directed>
tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
sample(const torch::Tensor &colptr, const torch::Tensor &row,
       const torch::Tensor &input_node, const vector<int64_t> num_neighbors) {

  // Initialize some data structures for the sampling process:
  vector<int64_t> samples;
20
  phmap::flat_hash_map<int64_t, int64_t> to_local_node;
rusty1s's avatar
rusty1s committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

  auto *colptr_data = colptr.data_ptr<int64_t>();
  auto *row_data = row.data_ptr<int64_t>();
  auto *input_node_data = input_node.data_ptr<int64_t>();

  for (int64_t i = 0; i < input_node.numel(); i++) {
    const auto &v = input_node_data[i];
    samples.push_back(v);
    to_local_node.insert({v, i});
  }

  vector<int64_t> rows, cols, edges;

  int64_t begin = 0, end = samples.size();
  for (int64_t ell = 0; ell < (int64_t)num_neighbors.size(); ell++) {
    const auto &num_samples = num_neighbors[ell];
    for (int64_t i = begin; i < end; i++) {
      const auto &w = samples[i];
      const auto &col_start = colptr_data[w];
      const auto &col_end = colptr_data[w + 1];
      const auto col_count = col_end - col_start;

      if (col_count == 0)
        continue;

rusty1s's avatar
bugfix  
rusty1s committed
46
47
      if ((num_samples < 0) || (!replace && (num_samples >= col_count))) {
        for (int64_t offset = col_start; offset < col_end; offset++) {
rusty1s's avatar
rusty1s committed
48
49
50
51
52
53
54
55
56
57
          const int64_t &v = row_data[offset];
          const auto res = to_local_node.insert({v, samples.size()});
          if (res.second)
            samples.push_back(v);
          if (directed) {
            cols.push_back(i);
            rows.push_back(res.first->second);
            edges.push_back(offset);
          }
        }
rusty1s's avatar
bugfix  
rusty1s committed
58
59
      } else if (replace) {
        for (int64_t j = 0; j < num_samples; j++) {
60
          const int64_t offset = col_start + uniform_randint(col_count);
rusty1s's avatar
rusty1s committed
61
62
63
64
65
66
67
68
69
70
71
72
73
          const int64_t &v = row_data[offset];
          const auto res = to_local_node.insert({v, samples.size()});
          if (res.second)
            samples.push_back(v);
          if (directed) {
            cols.push_back(i);
            rows.push_back(res.first->second);
            edges.push_back(offset);
          }
        }
      } else {
        unordered_set<int64_t> rnd_indices;
        for (int64_t j = col_count - num_samples; j < col_count; j++) {
74
          int64_t rnd = uniform_randint(j);
rusty1s's avatar
rusty1s committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
          if (!rnd_indices.insert(rnd).second) {
            rnd = j;
            rnd_indices.insert(j);
          }
          const int64_t offset = col_start + rnd;
          const int64_t &v = row_data[offset];
          const auto res = to_local_node.insert({v, samples.size()});
          if (res.second)
            samples.push_back(v);
          if (directed) {
            cols.push_back(i);
            rows.push_back(res.first->second);
            edges.push_back(offset);
          }
        }
      }
    }
    begin = end, end = samples.size();
  }

  if (!directed) {
96
    phmap::flat_hash_map<int64_t, int64_t>::iterator iter;
rusty1s's avatar
rusty1s committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    for (int64_t i = 0; i < (int64_t)samples.size(); i++) {
      const auto &w = samples[i];
      const auto &col_start = colptr_data[w];
      const auto &col_end = colptr_data[w + 1];
      for (int64_t offset = col_start; offset < col_end; offset++) {
        const auto &v = row_data[offset];
        iter = to_local_node.find(v);
        if (iter != to_local_node.end()) {
          rows.push_back(iter->second);
          cols.push_back(i);
          edges.push_back(offset);
        }
      }
    }
  }

  return make_tuple(from_vector<int64_t>(samples), from_vector<int64_t>(rows),
                    from_vector<int64_t>(cols), from_vector<int64_t>(edges));
}

117
inline bool satisfy_time(const c10::Dict<node_t, torch::Tensor> &node_time_dict,
118
119
                         const node_t &src_node_type, int64_t dst_time,
                         int64_t src_node) {
120
121
  try {
    // Check whether src -> dst obeys the time constraint
122
123
    const torch::Tensor &src_node_time = node_time_dict.at(src_node_type);
    return src_node_time.data_ptr<int64_t>()[src_node] <= dst_time;
124
125
  } catch (const std::out_of_range& e) {
    // If no time is given, fall back to normal sampling
Rex Ying's avatar
Rex Ying committed
126
127
128
129
130
    return true;
  }
}

template <bool replace, bool directed, bool temporal>
rusty1s's avatar
bugfix  
rusty1s committed
131
132
133
tuple<c10::Dict<node_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>,
      c10::Dict<rel_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>>
hetero_sample(const vector<node_t> &node_types,
Matthias Fey's avatar
Matthias Fey committed
134
135
136
137
138
              const vector<edge_t> &edge_types,
              const c10::Dict<rel_t, torch::Tensor> &colptr_dict,
              const c10::Dict<rel_t, torch::Tensor> &row_dict,
              const c10::Dict<node_t, torch::Tensor> &input_node_dict,
              const c10::Dict<rel_t, vector<int64_t>> &num_neighbors_dict,
139
140
141
              const c10::Dict<node_t, torch::Tensor> &node_time_dict,
              const int64_t num_hops) {

rusty1s's avatar
rusty1s committed
142
  // Create a mapping to convert single string relations to edge type triplets:
143
  phmap::flat_hash_map<rel_t, edge_t> to_edge_type;
rusty1s's avatar
rusty1s committed
144
145
146
147
  for (const auto &k : edge_types)
    to_edge_type[get<0>(k) + "__" + get<1>(k) + "__" + get<2>(k)] = k;

  // Initialize some data structures for the sampling process:
148
149
150
  phmap::flat_hash_map<node_t, vector<int64_t>> samples_dict;
  phmap::flat_hash_map<node_t, phmap::flat_hash_map<int64_t, int64_t>> to_local_node_dict;
  phmap::flat_hash_map<node_t, vector<int64_t>> root_time_dict;
Rex Ying's avatar
Rex Ying committed
151
152
153
154
155
156
  for (const auto &node_type : node_types) {
    samples_dict[node_type];
    to_local_node_dict[node_type];
    root_time_dict[node_type];
  }

157
  phmap::flat_hash_map<rel_t, vector<int64_t>> rows_dict, cols_dict, edges_dict;
158
159
160
161
162
163
164
  for (const auto &kv : colptr_dict) {
    const auto &rel_type = kv.key();
    rows_dict[rel_type];
    cols_dict[rel_type];
    edges_dict[rel_type];
  }

rusty1s's avatar
rusty1s committed
165
166
167
  // Add the input nodes to the output nodes:
  for (const auto &kv : input_node_dict) {
    const auto &node_type = kv.key();
Michał Marcinkiewicz's avatar
Michał Marcinkiewicz committed
168
    const torch::Tensor &input_node = kv.value();
rusty1s's avatar
rusty1s committed
169
    const auto *input_node_data = input_node.data_ptr<int64_t>();
170

Matthias Fey's avatar
Matthias Fey committed
171
    int64_t *node_time_data;
Rex Ying's avatar
Rex Ying committed
172
    if (temporal) {
173
      const torch::Tensor &node_time = node_time_dict.at(node_type);
Matthias Fey's avatar
Matthias Fey committed
174
      node_time_data = node_time.data_ptr<int64_t>();
Rex Ying's avatar
Rex Ying committed
175
    }
rusty1s's avatar
rusty1s committed
176
177
178

    auto &samples = samples_dict.at(node_type);
    auto &to_local_node = to_local_node_dict.at(node_type);
Rex Ying's avatar
Rex Ying committed
179
    auto &root_time = root_time_dict.at(node_type);
rusty1s's avatar
rusty1s committed
180
181
182
183
    for (int64_t i = 0; i < input_node.numel(); i++) {
      const auto &v = input_node_data[i];
      samples.push_back(v);
      to_local_node.insert({v, i});
184
      if (temporal)
Rex Ying's avatar
Rex Ying committed
185
        root_time.push_back(node_time_data[v]);
rusty1s's avatar
rusty1s committed
186
187
188
    }
  }

189
  phmap::flat_hash_map<node_t, pair<int64_t, int64_t>> slice_dict;
rusty1s's avatar
rusty1s committed
190
191
192
  for (const auto &kv : samples_dict)
    slice_dict[kv.first] = {0, kv.second.size()};

193
194
195
196
197
198
  vector<rel_t> all_rel_types;
  for (const auto &kv : num_neighbors_dict) {
    all_rel_types.push_back(kv.key());
  }
  std::sort(all_rel_types.begin(), all_rel_types.end());

rusty1s's avatar
rusty1s committed
199
  for (int64_t ell = 0; ell < num_hops; ell++) {
200
    for (const auto &rel_type : all_rel_types) {
rusty1s's avatar
rusty1s committed
201
202
203
      const auto &edge_type = to_edge_type[rel_type];
      const auto &src_node_type = get<0>(edge_type);
      const auto &dst_node_type = get<2>(edge_type);
204
      const auto num_samples = num_neighbors_dict.at(rel_type)[ell];
rusty1s's avatar
rusty1s committed
205
206
207
208
      const auto &dst_samples = samples_dict.at(dst_node_type);
      auto &src_samples = samples_dict.at(src_node_type);
      auto &to_local_src_node = to_local_node_dict.at(src_node_type);

209
210
211
212
      const torch::Tensor &colptr = colptr_dict.at(rel_type);
      const auto *colptr_data = colptr.data_ptr<int64_t>();
      const torch::Tensor &row = row_dict.at(rel_type);
      const auto *row_data = row.data_ptr<int64_t>();
rusty1s's avatar
rusty1s committed
213
214
215
216
217

      auto &rows = rows_dict.at(rel_type);
      auto &cols = cols_dict.at(rel_type);
      auto &edges = edges_dict.at(rel_type);

218
      // For temporal sampling, sampled nodes cannot have a timestamp greater
219
      // than the timestamp of the root nodes:
Rex Ying's avatar
Rex Ying committed
220
221
222
      const auto &dst_root_time = root_time_dict.at(dst_node_type);
      auto &src_root_time = root_time_dict.at(src_node_type);

223
224
      const auto &begin = slice_dict.at(dst_node_type).first;
      const auto &end = slice_dict.at(dst_node_type).second;
rusty1s's avatar
rusty1s committed
225
226
      for (int64_t i = begin; i < end; i++) {
        const auto &w = dst_samples[i];
227
228
229
        int64_t dst_time = 0;
        if (temporal)
          dst_time = dst_root_time[i];
rusty1s's avatar
rusty1s committed
230
231
232
233
234
235
236
        const auto &col_start = colptr_data[w];
        const auto &col_end = colptr_data[w + 1];
        const auto col_count = col_end - col_start;

        if (col_count == 0)
          continue;

rusty1s's avatar
bugfix  
rusty1s committed
237
        if ((num_samples < 0) || (!replace && (num_samples >= col_count))) {
238
          // Select all neighbors:
rusty1s's avatar
bugfix  
rusty1s committed
239
          for (int64_t offset = col_start; offset < col_end; offset++) {
rusty1s's avatar
rusty1s committed
240
            const int64_t &v = row_data[offset];
Rex Ying's avatar
Rex Ying committed
241
            if (temporal) {
242
243
              if (!satisfy_time(node_time_dict, src_node_type, dst_time, v))
                continue;
244
245
246
247
              // force disjoint of computation tree
              // note that the sampling always needs to have directed=True
              // for temporal case
              // to_local_src_node is not used for temporal / directed case
248
              const int64_t sample_idx = src_samples.size();
rusty1s's avatar
rusty1s committed
249
              src_samples.push_back(v);
250
              src_root_time.push_back(dst_time);
rusty1s's avatar
rusty1s committed
251
              cols.push_back(i);
252
              rows.push_back(sample_idx);
rusty1s's avatar
rusty1s committed
253
              edges.push_back(offset);
254
255
256
257
258
259
260
261
262
            } else {
              const auto res = to_local_src_node.insert({v, src_samples.size()});
              if (res.second)
                src_samples.push_back(v);
              if (directed) {
                cols.push_back(i);
                rows.push_back(res.first->second);
                edges.push_back(offset);
              }
rusty1s's avatar
rusty1s committed
263
264
            }
          }
rusty1s's avatar
bugfix  
rusty1s committed
265
        } else if (replace) {
266
          // Sample with replacement:
Rex Ying's avatar
Rex Ying committed
267
268
          int64_t num_neighbors = 0;
          while (num_neighbors < num_samples) {
269
            const int64_t offset = col_start + uniform_randint(col_count);
rusty1s's avatar
rusty1s committed
270
            const int64_t &v = row_data[offset];
Rex Ying's avatar
Rex Ying committed
271
            if (temporal) {
272
273
274
              // TODO Infinity loop if no neighbor satisfies time constraint:
              if (!satisfy_time(node_time_dict, src_node_type, dst_time, v))
                continue;
275
276
277
              // force disjoint of computation tree
              // note that the sampling always needs to have directed=True
              // for temporal case
278
              const int64_t sample_idx = src_samples.size();
rusty1s's avatar
rusty1s committed
279
              src_samples.push_back(v);
280
              src_root_time.push_back(dst_time);
rusty1s's avatar
rusty1s committed
281
              cols.push_back(i);
282
              rows.push_back(sample_idx);
rusty1s's avatar
rusty1s committed
283
              edges.push_back(offset);
284
285
286
287
288
289
290
291
292
            } else {
              const auto res = to_local_src_node.insert({v, src_samples.size()});
              if (res.second)
                src_samples.push_back(v);
              if (directed) {
                cols.push_back(i);
                rows.push_back(res.first->second);
                edges.push_back(offset);
              }
rusty1s's avatar
rusty1s committed
293
            }
Rex Ying's avatar
Rex Ying committed
294
            num_neighbors += 1;
rusty1s's avatar
rusty1s committed
295
296
          }
        } else {
297
          // Sample without replacement:
rusty1s's avatar
rusty1s committed
298
299
          unordered_set<int64_t> rnd_indices;
          for (int64_t j = col_count - num_samples; j < col_count; j++) {
300
            int64_t rnd = uniform_randint(j);
rusty1s's avatar
rusty1s committed
301
302
303
304
305
306
            if (!rnd_indices.insert(rnd).second) {
              rnd = j;
              rnd_indices.insert(j);
            }
            const int64_t offset = col_start + rnd;
            const int64_t &v = row_data[offset];
Rex Ying's avatar
Rex Ying committed
307
            if (temporal) {
308
309
              if (!satisfy_time(node_time_dict, src_node_type, dst_time, v))
                continue;
310
311
312
              // force disjoint of computation tree
              // note that the sampling always needs to have directed=True
              // for temporal case
313
              const int64_t sample_idx = src_samples.size();
rusty1s's avatar
rusty1s committed
314
              src_samples.push_back(v);
315
              src_root_time.push_back(dst_time);
rusty1s's avatar
rusty1s committed
316
              cols.push_back(i);
317
              rows.push_back(sample_idx);
rusty1s's avatar
rusty1s committed
318
              edges.push_back(offset);
319
320
321
322
323
324
325
326
327
            } else {
              const auto res = to_local_src_node.insert({v, src_samples.size()});
              if (res.second)
                src_samples.push_back(v);
              if (directed) {
                cols.push_back(i);
                rows.push_back(res.first->second);
                edges.push_back(offset);
              }
rusty1s's avatar
rusty1s committed
328
329
330
331
332
333
334
335
336
337
338
339
            }
          }
        }
      }
    }

    for (const auto &kv : samples_dict) {
      slice_dict[kv.first] = {slice_dict.at(kv.first).second, kv.second.size()};
    }
  }

  if (!directed) { // Construct the subgraph among the sampled nodes:
340
    phmap::flat_hash_map<int64_t, int64_t>::iterator iter;
rusty1s's avatar
rusty1s committed
341
342
343
344
345
346
347
348
    for (const auto &kv : colptr_dict) {
      const auto &rel_type = kv.key();
      const auto &edge_type = to_edge_type[rel_type];
      const auto &src_node_type = get<0>(edge_type);
      const auto &dst_node_type = get<2>(edge_type);
      const auto &dst_samples = samples_dict.at(dst_node_type);
      auto &to_local_src_node = to_local_node_dict.at(src_node_type);

Michał Marcinkiewicz's avatar
Michał Marcinkiewicz committed
349
      const auto *colptr_data = ((torch::Tensor)kv.value()).data_ptr<int64_t>();
350
351
      const auto *row_data =
          ((torch::Tensor)row_dict.at(rel_type)).data_ptr<int64_t>();
rusty1s's avatar
rusty1s committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

      auto &rows = rows_dict.at(rel_type);
      auto &cols = cols_dict.at(rel_type);
      auto &edges = edges_dict.at(rel_type);

      for (int64_t i = 0; i < (int64_t)dst_samples.size(); i++) {
        const auto &w = dst_samples[i];
        const auto &col_start = colptr_data[w];
        const auto &col_end = colptr_data[w + 1];
        for (int64_t offset = col_start; offset < col_end; offset++) {
          const auto &v = row_data[offset];
          iter = to_local_src_node.find(v);
          if (iter != to_local_src_node.end()) {
            rows.push_back(iter->second);
            cols.push_back(i);
            edges.push_back(offset);
          }
        }
      }
    }
  }

  return make_tuple(from_vector<node_t, int64_t>(samples_dict),
                    from_vector<rel_t, int64_t>(rows_dict),
                    from_vector<rel_t, int64_t>(cols_dict),
                    from_vector<rel_t, int64_t>(edges_dict));
}

} // namespace

tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
neighbor_sample_cpu(const torch::Tensor &colptr, const torch::Tensor &row,
                    const torch::Tensor &input_node,
                    const vector<int64_t> num_neighbors, const bool replace,
                    const bool directed) {

  if (replace && directed) {
    return sample<true, true>(colptr, row, input_node, num_neighbors);
  } else if (replace && !directed) {
    return sample<true, false>(colptr, row, input_node, num_neighbors);
  } else if (!replace && directed) {
    return sample<false, true>(colptr, row, input_node, num_neighbors);
  } else {
    return sample<false, false>(colptr, row, input_node, num_neighbors);
  }
}

rusty1s's avatar
bugfix  
rusty1s committed
399
400
tuple<c10::Dict<node_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>,
      c10::Dict<rel_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>>
rusty1s's avatar
rusty1s committed
401
hetero_neighbor_sample_cpu(
rusty1s's avatar
bugfix  
rusty1s committed
402
    const vector<node_t> &node_types, const vector<edge_t> &edge_types,
rusty1s's avatar
rusty1s committed
403
404
405
    const c10::Dict<rel_t, torch::Tensor> &colptr_dict,
    const c10::Dict<rel_t, torch::Tensor> &row_dict,
    const c10::Dict<node_t, torch::Tensor> &input_node_dict,
rusty1s's avatar
bugfix  
rusty1s committed
406
    const c10::Dict<rel_t, vector<int64_t>> &num_neighbors_dict,
rusty1s's avatar
rusty1s committed
407
408
    const int64_t num_hops, const bool replace, const bool directed) {

409
410
  c10::Dict<node_t, torch::Tensor> node_time_dict; // Empty dictionary.

rusty1s's avatar
rusty1s committed
411
  if (replace && directed) {
412
413
414
    return hetero_sample<true, true, false>(
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
        num_neighbors_dict, node_time_dict, num_hops);
Rex Ying's avatar
Rex Ying committed
415
  } else if (replace && !directed) {
416
    return hetero_sample<true, false, false>(
Matthias Fey's avatar
Matthias Fey committed
417
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
418
        num_neighbors_dict, node_time_dict, num_hops);
Rex Ying's avatar
Rex Ying committed
419
  } else if (!replace && directed) {
420
    return hetero_sample<false, true, false>(
Matthias Fey's avatar
Matthias Fey committed
421
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
422
        num_neighbors_dict, node_time_dict, num_hops);
Rex Ying's avatar
Rex Ying committed
423
  } else {
424
    return hetero_sample<false, false, false>(
Matthias Fey's avatar
Matthias Fey committed
425
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
426
        num_neighbors_dict, node_time_dict, num_hops);
Rex Ying's avatar
Rex Ying committed
427
428
429
430
431
  }
}

tuple<c10::Dict<node_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>,
      c10::Dict<rel_t, torch::Tensor>, c10::Dict<rel_t, torch::Tensor>>
432
hetero_temporal_neighbor_sample_cpu(
Rex Ying's avatar
Rex Ying committed
433
434
435
436
437
438
439
    const vector<node_t> &node_types, const vector<edge_t> &edge_types,
    const c10::Dict<rel_t, torch::Tensor> &colptr_dict,
    const c10::Dict<rel_t, torch::Tensor> &row_dict,
    const c10::Dict<node_t, torch::Tensor> &input_node_dict,
    const c10::Dict<rel_t, vector<int64_t>> &num_neighbors_dict,
    const c10::Dict<node_t, torch::Tensor> &node_time_dict,
    const int64_t num_hops, const bool replace, const bool directed) {
440
  AT_ASSERTM(directed, "Temporal sampling requires 'directed' sampling");
441
442
443
444
445
446
447
  if (replace) {
    // We assume that directed = True for temporal sampling
    // The current implementation uses disjoint computation trees
    // to tackle the case of the same node sampled having different
    // root time constraint.
    // In future, we could extend to directed = False case,
    // allowing additional edges within each computation tree.
Rex Ying's avatar
Rex Ying committed
448
    return hetero_sample<true, true, true>(
Matthias Fey's avatar
Matthias Fey committed
449
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
450
        num_neighbors_dict, node_time_dict, num_hops);
rusty1s's avatar
rusty1s committed
451
  } else {
452
    return hetero_sample<false, true, true>(
Matthias Fey's avatar
Matthias Fey committed
453
        node_types, edge_types, colptr_dict, row_dict, input_node_dict,
454
        num_neighbors_dict, node_time_dict, num_hops);
rusty1s's avatar
rusty1s committed
455
  }
456
}