fused_csc_sampling_graph.cc 82.8 KB
Newer Older
sangwzh's avatar
sangwzh committed
1
// !!! This is a file automatically generated by hipify!!!
2
3
/**
 *  Copyright (c) 2023 by Contributors
4
 * @file fused_csc_sampling_graph.cc
5
6
7
 * @brief Source file of sampling graph.
 */

8
#include <graphbolt/cuda_sampling_ops.h>
9
#include <graphbolt/fused_csc_sampling_graph.h>
10
#include <graphbolt/serialize.h>
11
12
#include <torch/torch.h>

13
14
#include <algorithm>
#include <array>
15
16
#include <cmath>
#include <limits>
17
#include <numeric>
18
#include <tuple>
19
#include <type_traits>
20
#include <vector>
21

22
#include "./expand_indptr.h"
23
#include "./macro.h"
24
#include "./random.h"
25
#include "./shared_memory_helper.h"
26
#include "./utils.h"
27
28


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace {
torch::optional<torch::Dict<std::string, torch::Tensor>> TensorizeDict(
    const torch::optional<torch::Dict<std::string, int64_t>>& dict) {
  if (!dict.has_value()) {
    return torch::nullopt;
  }
  torch::Dict<std::string, torch::Tensor> result;
  for (const auto& pair : dict.value()) {
    result.insert(pair.key(), torch::tensor(pair.value(), torch::kInt64));
  }
  return result;
}

torch::optional<torch::Dict<std::string, int64_t>> DetensorizeDict(
    const torch::optional<torch::Dict<std::string, torch::Tensor>>& dict) {
  if (!dict.has_value()) {
    return torch::nullopt;
  }
  torch::Dict<std::string, int64_t> result;
  for (const auto& pair : dict.value()) {
    result.insert(pair.key(), pair.value().item<int64_t>());
  }
  return result;
}
}  // namespace

55
56
57
namespace graphbolt {
namespace sampling {

58
59
static const int kPickleVersion = 6199;

60
FusedCSCSamplingGraph::FusedCSCSamplingGraph(
61
    const torch::Tensor& indptr, const torch::Tensor& indices,
62
    const torch::optional<torch::Tensor>& node_type_offset,
63
    const torch::optional<torch::Tensor>& type_per_edge,
64
65
    const torch::optional<NodeTypeToIDMap>& node_type_to_id,
    const torch::optional<EdgeTypeToIDMap>& edge_type_to_id,
66
    const torch::optional<NodeAttrMap>& node_attributes,
67
    const torch::optional<EdgeAttrMap>& edge_attributes)
68
    : indptr_(indptr),
69
      indices_(indices),
70
      node_type_offset_(node_type_offset),
71
      type_per_edge_(type_per_edge),
72
73
      node_type_to_id_(node_type_to_id),
      edge_type_to_id_(edge_type_to_id),
74
      node_attributes_(node_attributes),
75
      edge_attributes_(edge_attributes) {
76
77
78
79
80
  TORCH_CHECK(indptr.dim() == 1);
  TORCH_CHECK(indices.dim() == 1);
  TORCH_CHECK(indptr.device() == indices.device());
}

81
c10::intrusive_ptr<FusedCSCSamplingGraph> FusedCSCSamplingGraph::Create(
82
    const torch::Tensor& indptr, const torch::Tensor& indices,
83
    const torch::optional<torch::Tensor>& node_type_offset,
84
    const torch::optional<torch::Tensor>& type_per_edge,
85
86
    const torch::optional<NodeTypeToIDMap>& node_type_to_id,
    const torch::optional<EdgeTypeToIDMap>& edge_type_to_id,
87
    const torch::optional<NodeAttrMap>& node_attributes,
88
    const torch::optional<EdgeAttrMap>& edge_attributes) {
89
90
91
  if (node_type_offset.has_value()) {
    auto& offset = node_type_offset.value();
    TORCH_CHECK(offset.dim() == 1);
92
93
94
95
    TORCH_CHECK(node_type_to_id.has_value());
    TORCH_CHECK(
        offset.size(0) ==
        static_cast<int64_t>(node_type_to_id.value().size() + 1));
96
97
98
99
  }
  if (type_per_edge.has_value()) {
    TORCH_CHECK(type_per_edge.value().dim() == 1);
    TORCH_CHECK(type_per_edge.value().size(0) == indices.size(0));
100
    TORCH_CHECK(edge_type_to_id.has_value());
101
  }
102
103
  if (node_attributes.has_value()) {
    for (const auto& pair : node_attributes.value()) {
104
105
106
107
108
109
      TORCH_CHECK(
          pair.value().size(0) == indptr.size(0) - 1,
          "Expected node_attribute.size(0) and num_nodes to be equal, "
          "but node_attribute.size(0) was ",
          pair.value().size(0), ", and num_nodes was ", indptr.size(0) - 1,
          ".");
110
111
    }
  }
112
113
  if (edge_attributes.has_value()) {
    for (const auto& pair : edge_attributes.value()) {
114
115
116
117
118
      TORCH_CHECK(
          pair.value().size(0) == indices.size(0),
          "Expected edge_attribute.size(0) and num_edges to be equal, "
          "but edge_attribute.size(0) was ",
          pair.value().size(0), ", and num_edges was ", indices.size(0), ".");
119
120
    }
  }
121
  return c10::make_intrusive<FusedCSCSamplingGraph>(
122
      indptr, indices, node_type_offset, type_per_edge, node_type_to_id,
123
      edge_type_to_id, node_attributes, edge_attributes);
124
125
}

126
void FusedCSCSamplingGraph::Load(torch::serialize::InputArchive& archive) {
127
  const int64_t magic_num =
128
      read_from_archive<int64_t>(archive, "FusedCSCSamplingGraph/magic_num");
129
130
  TORCH_CHECK(
      magic_num == kCSCSamplingGraphSerializeMagic,
131
132
      "Magic numbers mismatch when loading FusedCSCSamplingGraph.");
  indptr_ =
133
134
135
136
137
138
139
      read_from_archive<torch::Tensor>(archive, "FusedCSCSamplingGraph/indptr");
  indices_ = read_from_archive<torch::Tensor>(
      archive, "FusedCSCSamplingGraph/indices");
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_node_type_offset")) {
    node_type_offset_ = read_from_archive<torch::Tensor>(
        archive, "FusedCSCSamplingGraph/node_type_offset");
140
  }
141
142
143
144
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_type_per_edge")) {
    type_per_edge_ = read_from_archive<torch::Tensor>(
        archive, "FusedCSCSamplingGraph/type_per_edge");
145
  }
146

147
148
149
150
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_node_type_to_id")) {
    node_type_to_id_ = read_from_archive<NodeTypeToIDMap>(
        archive, "FusedCSCSamplingGraph/node_type_to_id");
151
152
  }

153
154
155
156
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_edge_type_to_id")) {
    edge_type_to_id_ = read_from_archive<EdgeTypeToIDMap>(
        archive, "FusedCSCSamplingGraph/edge_type_to_id");
157
158
  }

159
160
161
162
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_node_attributes")) {
    node_attributes_ = read_from_archive<NodeAttrMap>(
        archive, "FusedCSCSamplingGraph/node_attributes");
163
  }
164
165
166
167
  if (read_from_archive<bool>(
          archive, "FusedCSCSamplingGraph/has_edge_attributes")) {
    edge_attributes_ = read_from_archive<EdgeAttrMap>(
        archive, "FusedCSCSamplingGraph/edge_attributes");
168
  }
169
170
}

171
172
173
174
175
176
void FusedCSCSamplingGraph::Save(
    torch::serialize::OutputArchive& archive) const {
  archive.write(
      "FusedCSCSamplingGraph/magic_num", kCSCSamplingGraphSerializeMagic);
  archive.write("FusedCSCSamplingGraph/indptr", indptr_);
  archive.write("FusedCSCSamplingGraph/indices", indices_);
177
  archive.write(
178
179
      "FusedCSCSamplingGraph/has_node_type_offset",
      node_type_offset_.has_value());
180
181
  if (node_type_offset_) {
    archive.write(
182
        "FusedCSCSamplingGraph/node_type_offset", node_type_offset_.value());
183
184
  }
  archive.write(
185
      "FusedCSCSamplingGraph/has_type_per_edge", type_per_edge_.has_value());
186
  if (type_per_edge_) {
187
188
    archive.write(
        "FusedCSCSamplingGraph/type_per_edge", type_per_edge_.value());
189
  }
190
191
192
193
194
195
196
197
198
199
200
201
202
203
  archive.write(
      "FusedCSCSamplingGraph/has_node_type_to_id",
      node_type_to_id_.has_value());
  if (node_type_to_id_) {
    archive.write(
        "FusedCSCSamplingGraph/node_type_to_id", node_type_to_id_.value());
  }
  archive.write(
      "FusedCSCSamplingGraph/has_edge_type_to_id",
      edge_type_to_id_.has_value());
  if (edge_type_to_id_) {
    archive.write(
        "FusedCSCSamplingGraph/edge_type_to_id", edge_type_to_id_.value());
  }
204
205
206
207
208
209
210
  archive.write(
      "FusedCSCSamplingGraph/has_node_attributes",
      node_attributes_.has_value());
  if (node_attributes_) {
    archive.write(
        "FusedCSCSamplingGraph/node_attributes", node_attributes_.value());
  }
211
  archive.write(
212
213
      "FusedCSCSamplingGraph/has_edge_attributes",
      edge_attributes_.has_value());
214
  if (edge_attributes_) {
215
216
    archive.write(
        "FusedCSCSamplingGraph/edge_attributes", edge_attributes_.value());
217
  }
218
219
}

220
void FusedCSCSamplingGraph::SetState(
221
222
223
224
225
226
227
228
229
    const torch::Dict<std::string, torch::Dict<std::string, torch::Tensor>>&
        state) {
  // State is a dict of dicts. The tensor-type attributes are stored in the dict
  // with key "independent_tensors". The dict-type attributes (edge_attributes)
  // are stored directly with the their name as the key.
  const auto& independent_tensors = state.at("independent_tensors");
  TORCH_CHECK(
      independent_tensors.at("version_number")
          .equal(torch::tensor({kPickleVersion})),
230
      "Version number mismatches when loading pickled FusedCSCSamplingGraph.")
231
232
233
234
235
236
237
238
239
  indptr_ = independent_tensors.at("indptr");
  indices_ = independent_tensors.at("indices");
  if (independent_tensors.find("node_type_offset") !=
      independent_tensors.end()) {
    node_type_offset_ = independent_tensors.at("node_type_offset");
  }
  if (independent_tensors.find("type_per_edge") != independent_tensors.end()) {
    type_per_edge_ = independent_tensors.at("type_per_edge");
  }
240
241
242
243
244
245
  if (state.find("node_type_to_id") != state.end()) {
    node_type_to_id_ = DetensorizeDict(state.at("node_type_to_id"));
  }
  if (state.find("edge_type_to_id") != state.end()) {
    edge_type_to_id_ = DetensorizeDict(state.at("edge_type_to_id"));
  }
246
247
248
  if (state.find("node_attributes") != state.end()) {
    node_attributes_ = state.at("node_attributes");
  }
249
250
251
252
253
254
  if (state.find("edge_attributes") != state.end()) {
    edge_attributes_ = state.at("edge_attributes");
  }
}

torch::Dict<std::string, torch::Dict<std::string, torch::Tensor>>
255
FusedCSCSamplingGraph::GetState() const {
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
  // State is a dict of dicts. The tensor-type attributes are stored in the dict
  // with key "independent_tensors". The dict-type attributes (edge_attributes)
  // are stored directly with the their name as the key.
  torch::Dict<std::string, torch::Dict<std::string, torch::Tensor>> state;
  torch::Dict<std::string, torch::Tensor> independent_tensors;
  // Serialization version number. It indicates the serialization method of the
  // whole state.
  independent_tensors.insert("version_number", torch::tensor({kPickleVersion}));
  independent_tensors.insert("indptr", indptr_);
  independent_tensors.insert("indices", indices_);
  if (node_type_offset_.has_value()) {
    independent_tensors.insert("node_type_offset", node_type_offset_.value());
  }
  if (type_per_edge_.has_value()) {
    independent_tensors.insert("type_per_edge", type_per_edge_.value());
  }
  state.insert("independent_tensors", independent_tensors);
273
274
275
276
277
278
  if (node_type_to_id_.has_value()) {
    state.insert("node_type_to_id", TensorizeDict(node_type_to_id_).value());
  }
  if (edge_type_to_id_.has_value()) {
    state.insert("edge_type_to_id", TensorizeDict(edge_type_to_id_).value());
  }
279
280
281
  if (node_attributes_.has_value()) {
    state.insert("node_attributes", node_attributes_.value());
  }
282
283
284
285
286
287
  if (edge_attributes_.has_value()) {
    state.insert("edge_attributes", edge_attributes_.value());
  }
  return state;
}

288
c10::intrusive_ptr<FusedSampledSubgraph> FusedCSCSamplingGraph::InSubgraph(
289
    const torch::Tensor& nodes) const {
290
  if (utils::is_on_gpu(nodes) && utils::is_accessible_from_gpu(indptr_) &&
291
292
293
294
295
296
297
      utils::is_accessible_from_gpu(indices_) &&
      (!type_per_edge_.has_value() ||
       utils::is_accessible_from_gpu(type_per_edge_.value()))) {
    GRAPHBOLT_DISPATCH_CUDA_ONLY_DEVICE(c10::DeviceType::CUDA, "InSubgraph", {
      return ops::InSubgraph(indptr_, indices_, nodes, type_per_edge_);
    });
  }
298
299
  using namespace torch::indexing;
  const int32_t kDefaultGrainSize = 100;
300
301
  const auto num_seeds = nodes.size(0);
  torch::Tensor indptr = torch::zeros({num_seeds + 1}, indptr_.dtype());
302
  std::vector<torch::Tensor> indices_arr(num_seeds);
303
304
  torch::Tensor original_column_node_ids =
      torch::zeros({num_seeds}, indptr_.dtype());
305
306
  std::vector<torch::Tensor> edge_ids_arr(num_seeds);
  std::vector<torch::Tensor> type_per_edge_arr(num_seeds);
307

308
  AT_DISPATCH_INDEX_TYPES(
309
310
311
312
      indptr_.scalar_type(), "InSubgraph", ([&] {
        torch::parallel_for(
            0, num_seeds, kDefaultGrainSize, [&](size_t start, size_t end) {
              for (size_t i = start; i < end; ++i) {
313
314
315
                const auto node_id = nodes[i].item<index_t>();
                const auto start_idx = indptr_[node_id].item<index_t>();
                const auto end_idx = indptr_[node_id + 1].item<index_t>();
316
317
318
319
320
321
322
323
324
325
326
327
                indptr[i + 1] = end_idx - start_idx;
                original_column_node_ids[i] = node_id;
                indices_arr[i] = indices_.slice(0, start_idx, end_idx);
                edge_ids_arr[i] = torch::arange(start_idx, end_idx);
                if (type_per_edge_) {
                  type_per_edge_arr[i] =
                      type_per_edge_.value().slice(0, start_idx, end_idx);
                }
              }
            });
      }));

328
  return c10::make_intrusive<FusedSampledSubgraph>(
329
      indptr.cumsum(0), torch::cat(indices_arr), original_column_node_ids,
330
331
332
333
334
335
      torch::arange(0, NumNodes()), torch::cat(edge_ids_arr),
      type_per_edge_
          ? torch::optional<torch::Tensor>{torch::cat(type_per_edge_arr)}
          : torch::nullopt);
}

336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
 * @brief Get a lambda function which counts the number of the neighbors to be
 * sampled.
 *
 * @param fanouts The number of edges to be sampled for each node with or
 * without considering edge types.
 * @param replace Boolean indicating whether the sample is performed with or
 * without replacement. If True, a value can be selected multiple times.
 * Otherwise, each value can be selected only once.
 * @param type_per_edge A tensor representing the type of each edge, if
 * present.
 * @param probs_or_mask Optional tensor containing the (unnormalized)
 * probabilities associated with each neighboring edge of a node in the original
 * graph. It must be a 1D floating-point tensor with the number of elements
 * equal to the number of edges in the graph.
 *
352
353
354
355
356
 * @return A lambda function (int64_t seed_offset, int64_t offset, int64_t
 * num_neighbors) -> torch::Tensor, which takes seed offset (the offset of the
 * seed to sample), offset (the starting edge ID of the given node) and
 * num_neighbors (number of neighbors) as params and returns the pick number of
 * the given node.
357
358
359
360
 */
auto GetNumPickFn(
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::optional<torch::Tensor>& type_per_edge,
361
362
    const torch::optional<torch::Tensor>& probs_or_mask,
    bool with_seed_offsets) {
363
364
  // If fanouts.size() > 1, returns the total number of all edge types of the
  // given node.
365
366
367
368
  return [&fanouts, replace, &probs_or_mask, &type_per_edge, with_seed_offsets](
             int64_t offset, int64_t num_neighbors, auto num_picked_ptr,
             int64_t seed_index,
             const std::vector<int64_t>& etype_id_to_num_picked_offset) {
369
    if (fanouts.size() > 1) {
370
371
372
373
      NumPickByEtype(
          with_seed_offsets, fanouts, replace, type_per_edge.value(),
          probs_or_mask, offset, num_neighbors, num_picked_ptr, seed_index,
          etype_id_to_num_picked_offset);
374
    } else {
375
376
377
      NumPick(
          fanouts[0], replace, probs_or_mask, offset, num_neighbors,
          num_picked_ptr + seed_index);
378
379
380
381
    }
  };
}

382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
auto GetTemporalNumPickFn(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices,
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::optional<torch::Tensor>& type_per_edge,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
    const torch::optional<torch::Tensor>& edge_timestamp) {
  // If fanouts.size() > 1, returns the total number of all edge types of the
  // given node.
  return [&seed_timestamp, &csc_indices, &fanouts, replace, &probs_or_mask,
          &type_per_edge, &node_timestamp, &edge_timestamp](
             int64_t seed_offset, int64_t offset, int64_t num_neighbors) {
    if (fanouts.size() > 1) {
      return TemporalNumPickByEtype(
          seed_timestamp, csc_indices, fanouts, replace, type_per_edge.value(),
          probs_or_mask, node_timestamp, edge_timestamp, seed_offset, offset,
          num_neighbors);
    } else {
      return TemporalNumPick(
          seed_timestamp, csc_indices, fanouts[0], replace, probs_or_mask,
          node_timestamp, edge_timestamp, seed_offset, offset, num_neighbors);
    }
  };
}

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/**
 * @brief Get a lambda function which contains the sampling process.
 *
 * @param fanouts The number of edges to be sampled for each node with or
 * without considering edge types.
 * @param replace Boolean indicating whether the sample is performed with or
 * without replacement. If True, a value can be selected multiple times.
 * Otherwise, each value can be selected only once.
 * @param options Tensor options specifying the desired data type of the result.
 * @param type_per_edge A tensor representing the type of each edge, if
 * present.
 * @param probs_or_mask Optional tensor containing the (unnormalized)
 * probabilities associated with each neighboring edge of a node in the original
 * graph. It must be a 1D floating-point tensor with the number of elements
 * equal to the number of edges in the graph.
 * @param args Contains sampling algorithm specific arguments.
 *
424
425
426
427
428
 * @return A lambda function: (int64_t seed_offset, int64_t offset, int64_t
 * num_neighbors, PickedType* picked_data_ptr) -> torch::Tensor, which takes
 * seed_offset (the offset of the seed to sample), offset (the starting edge ID
 * of the given node) and num_neighbors (number of neighbors) as params and puts
 * the picked neighbors at the address specified by picked_data_ptr.
429
 */
430
template <SamplerType S>
431
432
433
434
auto GetPickFn(
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::TensorOptions& options,
    const torch::optional<torch::Tensor>& type_per_edge,
435
436
437
438
439
440
441
    const torch::optional<torch::Tensor>& probs_or_mask, bool with_seed_offsets,
    SamplerArgs<S> args) {
  return [&fanouts, replace, &options, &type_per_edge, &probs_or_mask, args,
          with_seed_offsets](
             int64_t offset, int64_t num_neighbors, auto picked_data_ptr,
             int64_t seed_offset, auto subgraph_indptr_ptr,
             const std::vector<int64_t>& etype_id_to_num_picked_offset) {
442
443
444
    // If fanouts.size() > 1, perform sampling for each edge type of each
    // node; otherwise just sample once for each node with no regard of edge
    // types.
445
446
    if (fanouts.size() > 1) {
      return PickByEtype(
447
448
449
          with_seed_offsets, offset, num_neighbors, fanouts, replace, options,
          type_per_edge.value(), probs_or_mask, args, picked_data_ptr,
          seed_offset, subgraph_indptr_ptr, etype_id_to_num_picked_offset);
450
    } else {
451
      int64_t num_sampled = Pick(
452
          offset, num_neighbors, fanouts[0], replace, options, probs_or_mask,
453
          args, picked_data_ptr + subgraph_indptr_ptr[seed_offset]);
454
455
456
457
      if (type_per_edge) {
        std::sort(picked_data_ptr, picked_data_ptr + num_sampled);
      }
      return num_sampled;
458
459
460
461
    }
  };
}

462
template <SamplerType S>
463
464
465
466
467
468
469
auto GetTemporalPickFn(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices,
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::TensorOptions& options,
    const torch::optional<torch::Tensor>& type_per_edge,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    const torch::optional<torch::Tensor>& edge_timestamp, SamplerArgs<S> args) {
  return
      [&seed_timestamp, &csc_indices, &fanouts, replace, &options,
       &type_per_edge, &probs_or_mask, &node_timestamp, &edge_timestamp, args](
          int64_t seed_offset, int64_t offset, int64_t num_neighbors,
          auto picked_data_ptr) {
        // If fanouts.size() > 1, perform sampling for each edge type of each
        // node; otherwise just sample once for each node with no regard of edge
        // types.
        if (fanouts.size() > 1) {
          return TemporalPickByEtype(
              seed_timestamp, csc_indices, seed_offset, offset, num_neighbors,
              fanouts, replace, options, type_per_edge.value(), probs_or_mask,
              node_timestamp, edge_timestamp, args, picked_data_ptr);
        } else {
          int64_t num_sampled = TemporalPick(
              seed_timestamp, csc_indices, seed_offset, offset, num_neighbors,
              fanouts[0], replace, options, probs_or_mask, node_timestamp,
              edge_timestamp, args, picked_data_ptr);
          if (type_per_edge.has_value()) {
            std::sort(picked_data_ptr, picked_data_ptr + num_sampled);
          }
          return num_sampled;
        }
      };
495
496
}

497
template <TemporalOption Temporal, typename NumPickFn, typename PickFn>
498
499
c10::intrusive_ptr<FusedSampledSubgraph>
FusedCSCSamplingGraph::SampleNeighborsImpl(
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    const torch::Tensor& seeds,
    torch::optional<std::vector<int64_t>>& seed_offsets,
    const std::vector<int64_t>& fanouts, bool return_eids,
    NumPickFn num_pick_fn, PickFn pick_fn) const {
  const int64_t num_seeds = seeds.size(0);
  const auto indptr_options = indptr_.options();

  // Calculate GrainSize for parallel_for.
  // Set the default grain size to 64.
  const int64_t grain_size = 64;
  torch::Tensor picked_eids;
  torch::Tensor subgraph_indptr;
  torch::Tensor subgraph_indices;
  torch::optional<torch::Tensor> subgraph_type_per_edge = torch::nullopt;
  torch::optional<torch::Tensor> edge_offsets = torch::nullopt;

  bool with_seed_offsets = seed_offsets.has_value();
517
518
  bool hetero_with_seed_offsets = with_seed_offsets && fanouts.size() > 1 &&
                                  Temporal == TemporalOption::NOT_TEMPORAL;
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

  // Get the number of edge types. If it's homo or if the size of fanouts is 1
  // (hetero graph but sampled as a homo graph), set num_etypes as 1.
  // In temporal sampling, this will not be used for now since the logic hasn't
  // been adopted for temporal sampling.
  const int64_t num_etypes =
      (edge_type_to_id_.has_value() && hetero_with_seed_offsets)
          ? edge_type_to_id_->size()
          : 1;
  std::vector<int64_t> etype_id_to_src_ntype_id(num_etypes);
  std::vector<int64_t> etype_id_to_dst_ntype_id(num_etypes);
  torch::optional<torch::Tensor> subgraph_indptr_substract = torch::nullopt;
  // The pick numbers are stored in a single tensor by the order of etype. Each
  // etype corresponds to a group of seeds whose ntype are the same as the
  // dst_type. `etype_id_to_num_picked_offset` indicates the beginning offset
  // where each etype's corresponding seeds' pick numbers are stored in the pick
  // number tensor.
  std::vector<int64_t> etype_id_to_num_picked_offset(num_etypes + 1);
  if (hetero_with_seed_offsets) {
    for (auto& etype_and_id : edge_type_to_id_.value()) {
      auto etype = etype_and_id.key();
      auto id = etype_and_id.value();
      auto [src_type, dst_type] = utils::parse_src_dst_ntype_from_etype(etype);
      auto dst_ntype_id = node_type_to_id_->at(dst_type);
      etype_id_to_src_ntype_id[id] = node_type_to_id_->at(src_type);
      etype_id_to_dst_ntype_id[id] = dst_ntype_id;
      etype_id_to_num_picked_offset[id + 1] =
          seed_offsets->at(dst_ntype_id + 1) - seed_offsets->at(dst_ntype_id) +
          1;
    }
    std::partial_sum(
        etype_id_to_num_picked_offset.begin(),
        etype_id_to_num_picked_offset.end(),
        etype_id_to_num_picked_offset.begin());
  } else {
    etype_id_to_dst_ntype_id[0] = 0;
    etype_id_to_num_picked_offset[1] = num_seeds + 1;
  }
  // `num_rows` indicates the length of `num_picked_neighbors_per_node`, which
  // is used for storing pick numbers. In non-temporal hetero sampling, it
  // equals to sum_{etype} #seeds with ntype=dst_type(etype). In homo sampling,
  // it equals to `num_seeds`.
  const int64_t num_rows = etype_id_to_num_picked_offset[num_etypes];
  torch::Tensor num_picked_neighbors_per_node =
563
564
      // Need to use zeros because all nodes don't have all etypes.
      torch::zeros({num_rows}, indptr_options);
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589

  AT_DISPATCH_INDEX_TYPES(
      indptr_.scalar_type(), "SampleNeighborsImplWrappedWithIndptr", ([&] {
        using indptr_t = index_t;
        AT_DISPATCH_INDEX_TYPES(
            seeds.scalar_type(), "SampleNeighborsImplWrappedWithSeeds", ([&] {
              using seeds_t = index_t;
              const auto indptr_data = indptr_.data_ptr<indptr_t>();
              const auto num_picked_neighbors_data_ptr =
                  num_picked_neighbors_per_node.data_ptr<indptr_t>();
              num_picked_neighbors_data_ptr[0] = 0;
              const auto seeds_data_ptr = seeds.data_ptr<seeds_t>();

              // Step 1. Calculate pick number of each node.
              torch::parallel_for(
                  0, num_seeds, grain_size, [&](int64_t begin, int64_t end) {
                    for (int64_t i = begin; i < end; ++i) {
                      const auto nid = seeds_data_ptr[i];
                      TORCH_CHECK(
                          nid >= 0 && nid < NumNodes(),
                          "The seed nodes' IDs should fall within the range of "
                          "the graph's node IDs.");
                      const auto offset = indptr_data[nid];
                      const auto num_neighbors = indptr_data[nid + 1] - offset;

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
                      if constexpr (Temporal == TemporalOption::TEMPORAL) {
                        num_picked_neighbors_data_ptr[i + 1] =
                            num_neighbors == 0
                                ? 0
                                : num_pick_fn(i, offset, num_neighbors);
                      } else {
                        const auto seed_type_id =
                            (hetero_with_seed_offsets)
                                ? std::upper_bound(
                                      seed_offsets->begin(),
                                      seed_offsets->end(), i) -
                                      seed_offsets->begin() - 1
                                : 0;
                        // `seed_index` indicates the index of the current
                        // seed within the group of seeds which have the same
                        // node type.
                        const auto seed_index =
                            (hetero_with_seed_offsets)
                                ? i - seed_offsets->at(seed_type_id)
                                : i;
                        num_pick_fn(
                            offset, num_neighbors,
                            num_picked_neighbors_data_ptr + 1, seed_index,
                            etype_id_to_num_picked_offset);
                      }
615
616
617
                    }
                  });

618
619
620
621
622
623
624
              // Step 2. Calculate prefix sum to get total length and offsets of
              // each node. It's also the indptr of the generated subgraph.
              subgraph_indptr = num_picked_neighbors_per_node.cumsum(
                  0, indptr_.scalar_type());
              auto subgraph_indptr_data_ptr =
                  subgraph_indptr.data_ptr<indptr_t>();

625
626
              if (hetero_with_seed_offsets) {
                torch::Tensor num_picked_offset_tensor =
627
628
629
630
631
632
633
                    torch::empty({num_etypes + 1}, indptr_options);
                const auto num_picked_offset_data_ptr =
                    num_picked_offset_tensor.data_ptr<indptr_t>();
                std::copy(
                    etype_id_to_num_picked_offset.begin(),
                    etype_id_to_num_picked_offset.end(),
                    num_picked_offset_data_ptr);
634
                torch::Tensor substract_offset =
635
                    torch::empty({num_etypes}, indptr_options);
636
637
638
                const auto substract_offset_data_ptr =
                    substract_offset.data_ptr<indptr_t>();
                for (auto i = 0; i < num_etypes; ++i) {
639
640
641
                  // Collect the total pick number subtract offsets.
                  substract_offset_data_ptr[i] = subgraph_indptr_data_ptr
                      [etype_id_to_num_picked_offset[i]];
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
                }
                subgraph_indptr_substract = ops::ExpandIndptr(
                    num_picked_offset_tensor, indptr_.scalar_type(),
                    substract_offset);
              }

              // When doing non-temporal hetero sampling, we generate an
              // edge_offsets tensor.
              if (hetero_with_seed_offsets) {
                edge_offsets = torch::empty({num_etypes + 1}, indptr_options);
                AT_DISPATCH_INTEGRAL_TYPES(
                    edge_offsets.value().scalar_type(), "CalculateEdgeOffsets",
                    ([&] {
                      auto edge_offsets_data_ptr =
                          edge_offsets.value().data_ptr<scalar_t>();
                      edge_offsets_data_ptr[0] = 0;
                      for (auto i = 0; i < num_etypes; ++i) {
                        edge_offsets_data_ptr[i + 1] = subgraph_indptr_data_ptr
                            [etype_id_to_num_picked_offset[i + 1] - 1];
                      }
                    }));
              }

              // Step 3. Allocate the tensor for picked neighbors.
              const auto total_length =
                  subgraph_indptr.data_ptr<indptr_t>()[num_rows - 1];
              picked_eids = torch::empty({total_length}, indptr_options);
              subgraph_indices =
                  torch::empty({total_length}, indices_.options());
              if (!hetero_with_seed_offsets && type_per_edge_.has_value()) {
                subgraph_type_per_edge = torch::empty(
                    {total_length}, type_per_edge_.value().options());
              }

              auto picked_eids_data_ptr = picked_eids.data_ptr<indptr_t>();
              torch::parallel_for(
                  0, num_seeds, grain_size, [&](int64_t begin, int64_t end) {
                    for (int64_t i = begin; i < end; ++i) {
                      const auto nid = seeds_data_ptr[i];
                      const auto offset = indptr_data[nid];
                      const auto num_neighbors = indptr_data[nid + 1] - offset;
                      auto picked_number = 0;
                      const auto seed_type_id =
                          (hetero_with_seed_offsets)
                              ? std::upper_bound(
                                    seed_offsets->begin(), seed_offsets->end(),
                                    i) -
                                    seed_offsets->begin() - 1
                              : 0;
                      const auto seed_index =
                          (hetero_with_seed_offsets)
                              ? i - seed_offsets->at(seed_type_id)
                              : i;

                      // Step 4. Pick neighbors for each node.
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
                      if constexpr (Temporal == TemporalOption::TEMPORAL) {
                        picked_number = num_picked_neighbors_data_ptr[i + 1];
                        auto picked_offset = subgraph_indptr_data_ptr[i];
                        if (picked_number > 0) {
                          auto actual_picked_count = pick_fn(
                              i, offset, num_neighbors,
                              picked_eids_data_ptr + picked_offset);
                          TORCH_CHECK(
                              actual_picked_count == picked_number,
                              "Actual picked count doesn't match the calculated"
                              " pick number.");
                        }
                      } else {
                        picked_number = pick_fn(
                            offset, num_neighbors, picked_eids_data_ptr,
                            seed_index, subgraph_indptr_data_ptr,
                            etype_id_to_num_picked_offset);
                        if (!hetero_with_seed_offsets) {
                          TORCH_CHECK(
                              num_picked_neighbors_data_ptr[i + 1] ==
                                  picked_number,
                              "Actual picked count doesn't match the calculated"
                              " pick number.");
                        }
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
                      }

                      // Step 5. Calculate other attributes and return the
                      // subgraph.
                      if (picked_number > 0) {
                        AT_DISPATCH_INDEX_TYPES(
                            subgraph_indices.scalar_type(),
                            "IndexSelectSubgraphIndices", ([&] {
                              auto subgraph_indices_data_ptr =
                                  subgraph_indices.data_ptr<index_t>();
                              auto indices_data_ptr =
                                  indices_.data_ptr<index_t>();
                              for (auto i = 0; i < num_etypes; ++i) {
                                if (etype_id_to_dst_ntype_id[i] != seed_type_id)
                                  continue;
                                const auto indptr_offset =
                                    with_seed_offsets
                                        ? etype_id_to_num_picked_offset[i] +
                                              seed_index
                                        : seed_index;
                                const auto picked_begin =
                                    subgraph_indptr_data_ptr[indptr_offset];
                                const auto picked_end =
                                    subgraph_indptr_data_ptr[indptr_offset + 1];
                                for (auto j = picked_begin; j < picked_end;
                                     ++j) {
                                  subgraph_indices_data_ptr[j] =
                                      indices_data_ptr[picked_eids_data_ptr[j]];
                                  if (hetero_with_seed_offsets &&
                                      node_type_offset_.has_value()) {
                                    // Substract the node type offset from
                                    // subgraph indices. Assuming
                                    // node_type_offset has the same dtype as
                                    // indices.
                                    auto node_type_offset_data =
                                        node_type_offset_.value()
                                            .data_ptr<index_t>();
                                    subgraph_indices_data_ptr[j] -=
                                        node_type_offset_data
                                            [etype_id_to_src_ntype_id[i]];
                                  }
                                }
                              }
                            }));

                        if (!hetero_with_seed_offsets &&
                            type_per_edge_.has_value()) {
                          // When hetero graph is sampled as a homo graph, we
                          // still generate type_per_edge tensor for this
                          // situation.
                          AT_DISPATCH_INTEGRAL_TYPES(
                              subgraph_type_per_edge.value().scalar_type(),
                              "IndexSelectTypePerEdge", ([&] {
                                auto subgraph_type_per_edge_data_ptr =
                                    subgraph_type_per_edge.value()
                                        .data_ptr<scalar_t>();
                                auto type_per_edge_data_ptr =
                                    type_per_edge_.value().data_ptr<scalar_t>();
                                const auto picked_offset =
                                    subgraph_indptr_data_ptr[seed_index];
                                for (auto j = picked_offset;
                                     j < picked_offset + picked_number; ++j)
                                  subgraph_type_per_edge_data_ptr[j] =
                                      type_per_edge_data_ptr
                                          [picked_eids_data_ptr[j]];
                              }));
                        }
                      }
                    }
                  });
            }));
      }));

  torch::optional<torch::Tensor> subgraph_reverse_edge_ids = torch::nullopt;
  if (return_eids) subgraph_reverse_edge_ids = std::move(picked_eids);

  if (subgraph_indptr_substract.has_value()) {
    subgraph_indptr -= subgraph_indptr_substract.value();
  }

  return c10::make_intrusive<FusedSampledSubgraph>(
      subgraph_indptr, subgraph_indices, seeds, torch::nullopt,
      subgraph_reverse_edge_ids, subgraph_type_per_edge, edge_offsets);
}

806
c10::intrusive_ptr<FusedSampledSubgraph> FusedCSCSamplingGraph::SampleNeighbors(
807
808
809
810
    torch::optional<torch::Tensor> seeds,
    torch::optional<std::vector<int64_t>> seed_offsets,
    const std::vector<int64_t>& fanouts, bool replace, bool layer,
    bool return_eids, torch::optional<std::string> probs_name,
811
812
    torch::optional<torch::Tensor> random_seed,
    double seed2_contribution) const {
813
814
  auto probs_or_mask = this->EdgeAttribute(probs_name);

815
816
  // If seeds does not have a value, then we expect all arguments to be resident
  // on the GPU. If seeds has a value, then we expect them to be accessible from
817
  // GPU. This is required for the dispatch to work when CUDA is not available.
818
  if (((!seeds.has_value() && utils::is_on_gpu(indptr_) &&
819
820
821
822
823
        utils::is_on_gpu(indices_) &&
        (!probs_or_mask.has_value() ||
         utils::is_on_gpu(probs_or_mask.value())) &&
        (!type_per_edge_.has_value() ||
         utils::is_on_gpu(type_per_edge_.value()))) ||
824
       (seeds.has_value() && utils::is_on_gpu(seeds.value()) &&
825
826
827
828
829
830
831
        utils::is_accessible_from_gpu(indptr_) &&
        utils::is_accessible_from_gpu(indices_) &&
        (!probs_or_mask.has_value() ||
         utils::is_accessible_from_gpu(probs_or_mask.value())) &&
        (!type_per_edge_.has_value() ||
         utils::is_accessible_from_gpu(type_per_edge_.value())))) &&
      !replace) {
832
833
834
    GRAPHBOLT_DISPATCH_CUDA_ONLY_DEVICE(
        c10::DeviceType::CUDA, "SampleNeighbors", {
          return ops::SampleNeighbors(
835
              indptr_, indices_, seeds, seed_offsets, fanouts, replace, layer,
836
837
838
              return_eids, type_per_edge_, probs_or_mask, node_type_offset_,
              node_type_to_id_, edge_type_to_id_, random_seed,
              seed2_contribution);
839
840
        });
  }
841
  TORCH_CHECK(seeds.has_value(), "Nodes can not be None on the CPU.");
842
843

  if (probs_or_mask.has_value()) {
844
845
846
847
848
849
850
851
    // Note probs will be passed as input for 'torch.multinomial' in deeper
    // stack, which doesn't support 'torch.half' and 'torch.bool' data types. To
    // avoid crashes, convert 'probs_or_mask' to 'float32' data type.
    if (probs_or_mask.value().dtype() == torch::kBool ||
        probs_or_mask.value().dtype() == torch::kFloat16) {
      probs_or_mask = probs_or_mask.value().to(torch::kFloat32);
    }
  }
852

853
854
  bool with_seed_offsets = seed_offsets.has_value();

855
  if (layer) {
856
857
858
859
860
    if (random_seed.has_value() && random_seed->numel() >= 2) {
      SamplerArgs<SamplerType::LABOR_DEPENDENT> args{
          indices_,
          {random_seed.value(), static_cast<float>(seed2_contribution)},
          NumNodes()};
861
      return SampleNeighborsImpl<TemporalOption::NOT_TEMPORAL>(
862
863
864
865
          seeds.value(), seed_offsets, fanouts, return_eids,
          GetNumPickFn(
              fanouts, replace, type_per_edge_, probs_or_mask,
              with_seed_offsets),
866
867
          GetPickFn(
              fanouts, replace, indptr_.options(), type_per_edge_,
868
              probs_or_mask, with_seed_offsets, args));
869
870
871
872
873
874
875
876
877
878
879
880
881
    } else {
      auto args = [&] {
        if (random_seed.has_value() && random_seed->numel() == 1) {
          return SamplerArgs<SamplerType::LABOR>{
              indices_, random_seed.value(), NumNodes()};
        } else {
          return SamplerArgs<SamplerType::LABOR>{
              indices_,
              RandomEngine::ThreadLocal()->RandInt(
                  static_cast<int64_t>(0), std::numeric_limits<int64_t>::max()),
              NumNodes()};
        }
      }();
882
      return SampleNeighborsImpl<TemporalOption::NOT_TEMPORAL>(
883
884
885
886
          seeds.value(), seed_offsets, fanouts, return_eids,
          GetNumPickFn(
              fanouts, replace, type_per_edge_, probs_or_mask,
              with_seed_offsets),
887
888
          GetPickFn(
              fanouts, replace, indptr_.options(), type_per_edge_,
889
              probs_or_mask, with_seed_offsets, args));
890
    }
891
892
  } else {
    SamplerArgs<SamplerType::NEIGHBOR> args;
893
    return SampleNeighborsImpl<TemporalOption::NOT_TEMPORAL>(
894
895
896
        seeds.value(), seed_offsets, fanouts, return_eids,
        GetNumPickFn(
            fanouts, replace, type_per_edge_, probs_or_mask, with_seed_offsets),
897
898
        GetPickFn(
            fanouts, replace, indptr_.options(), type_per_edge_, probs_or_mask,
899
            with_seed_offsets, args));
900
901
902
  }
}

903
904
905
906
c10::intrusive_ptr<FusedSampledSubgraph>
FusedCSCSamplingGraph::TemporalSampleNeighbors(
    const torch::Tensor& input_nodes,
    const torch::Tensor& input_nodes_timestamp,
907
908
    const std::vector<int64_t>& fanouts, bool replace, bool layer,
    bool return_eids, torch::optional<std::string> probs_name,
909
910
    torch::optional<std::string> node_timestamp_attr_name,
    torch::optional<std::string> edge_timestamp_attr_name) const {
911
  torch::optional<std::vector<int64_t>> seed_offsets = torch::nullopt;
912
  // 1. Get probs_or_mask.
913
914
915
916
917
918
919
920
921
922
  auto probs_or_mask = this->EdgeAttribute(probs_name);
  if (probs_name.has_value()) {
    // Note probs will be passed as input for 'torch.multinomial' in deeper
    // stack, which doesn't support 'torch.half' and 'torch.bool' data types. To
    // avoid crashes, convert 'probs_or_mask' to 'float32' data type.
    if (probs_or_mask.value().dtype() == torch::kBool ||
        probs_or_mask.value().dtype() == torch::kFloat16) {
      probs_or_mask = probs_or_mask.value().to(torch::kFloat32);
    }
  }
923
  // 2. Get the timestamp attribute for nodes of the graph
924
  auto node_timestamp = this->NodeAttribute(node_timestamp_attr_name);
925
  // 3. Get the timestamp attribute for edges of the graph
926
927
  auto edge_timestamp = this->EdgeAttribute(edge_timestamp_attr_name);
  // 4. Call SampleNeighborsImpl
928
929
930
931
  if (layer) {
    const int64_t random_seed = RandomEngine::ThreadLocal()->RandInt(
        static_cast<int64_t>(0), std::numeric_limits<int64_t>::max());
    SamplerArgs<SamplerType::LABOR> args{indices_, random_seed, NumNodes()};
932
933
    return SampleNeighborsImpl<TemporalOption::TEMPORAL>(
        input_nodes, seed_offsets, fanouts, return_eids,
934
935
936
937
938
939
940
941
942
        GetTemporalNumPickFn(
            input_nodes_timestamp, this->indices_, fanouts, replace,
            type_per_edge_, probs_or_mask, node_timestamp, edge_timestamp),
        GetTemporalPickFn(
            input_nodes_timestamp, this->indices_, fanouts, replace,
            indptr_.options(), type_per_edge_, probs_or_mask, node_timestamp,
            edge_timestamp, args));
  } else {
    SamplerArgs<SamplerType::NEIGHBOR> args;
943
944
    return SampleNeighborsImpl<TemporalOption::TEMPORAL>(
        input_nodes, seed_offsets, fanouts, return_eids,
945
946
947
948
949
950
951
952
        GetTemporalNumPickFn(
            input_nodes_timestamp, this->indices_, fanouts, replace,
            type_per_edge_, probs_or_mask, node_timestamp, edge_timestamp),
        GetTemporalPickFn(
            input_nodes_timestamp, this->indices_, fanouts, replace,
            indptr_.options(), type_per_edge_, probs_or_mask, node_timestamp,
            edge_timestamp, args));
  }
953
954
}

955
956
static c10::intrusive_ptr<FusedCSCSamplingGraph>
BuildGraphFromSharedMemoryHelper(SharedMemoryHelper&& helper) {
957
958
959
960
961
  helper.InitializeRead();
  auto indptr = helper.ReadTorchTensor();
  auto indices = helper.ReadTorchTensor();
  auto node_type_offset = helper.ReadTorchTensor();
  auto type_per_edge = helper.ReadTorchTensor();
962
963
  auto node_type_to_id = DetensorizeDict(helper.ReadTorchTensorDict());
  auto edge_type_to_id = DetensorizeDict(helper.ReadTorchTensorDict());
964
  auto node_attributes = helper.ReadTorchTensorDict();
965
  auto edge_attributes = helper.ReadTorchTensorDict();
966
  auto graph = c10::make_intrusive<FusedCSCSamplingGraph>(
967
      indptr.value(), indices.value(), node_type_offset, type_per_edge,
968
      node_type_to_id, edge_type_to_id, node_attributes, edge_attributes);
969
970
971
  auto shared_memory = helper.ReleaseSharedMemory();
  graph->HoldSharedMemoryObject(
      std::move(shared_memory.first), std::move(shared_memory.second));
972
973
974
  return graph;
}

975
976
c10::intrusive_ptr<FusedCSCSamplingGraph>
FusedCSCSamplingGraph::CopyToSharedMemory(
977
    const std::string& shared_memory_name) {
978
  SharedMemoryHelper helper(shared_memory_name);
979
980
981
982
  helper.WriteTorchTensor(indptr_);
  helper.WriteTorchTensor(indices_);
  helper.WriteTorchTensor(node_type_offset_);
  helper.WriteTorchTensor(type_per_edge_);
983
984
  helper.WriteTorchTensorDict(TensorizeDict(node_type_to_id_));
  helper.WriteTorchTensorDict(TensorizeDict(edge_type_to_id_));
985
  helper.WriteTorchTensorDict(node_attributes_);
986
987
988
  helper.WriteTorchTensorDict(edge_attributes_);
  helper.Flush();
  return BuildGraphFromSharedMemoryHelper(std::move(helper));
989
990
}

991
992
c10::intrusive_ptr<FusedCSCSamplingGraph>
FusedCSCSamplingGraph::LoadFromSharedMemory(
993
    const std::string& shared_memory_name) {
994
  SharedMemoryHelper helper(shared_memory_name);
995
  return BuildGraphFromSharedMemoryHelper(std::move(helper));
996
997
}

998
void FusedCSCSamplingGraph::HoldSharedMemoryObject(
999
1000
1001
1002
1003
    SharedMemoryPtr tensor_metadata_shm, SharedMemoryPtr tensor_data_shm) {
  tensor_metadata_shm_ = std::move(tensor_metadata_shm);
  tensor_data_shm_ = std::move(tensor_data_shm);
}

1004
1005
template <typename PickedNumType>
void NumPick(
1006
1007
    int64_t fanout, bool replace,
    const torch::optional<torch::Tensor>& probs_or_mask, int64_t offset,
1008
    int64_t num_neighbors, PickedNumType* picked_num_ptr) {
1009
  int64_t num_valid_neighbors = num_neighbors;
1010
  if (probs_or_mask.has_value() && num_neighbors > 0) {
1011
1012
1013
1014
1015
1016
1017
1018
1019
    // Subtract the count of zeros in probs_or_mask.
    AT_DISPATCH_ALL_TYPES(
        probs_or_mask.value().scalar_type(), "CountZero", ([&] {
          scalar_t* probs_data_ptr = probs_or_mask.value().data_ptr<scalar_t>();
          num_valid_neighbors -= std::count(
              probs_data_ptr + offset, probs_data_ptr + offset + num_neighbors,
              0);
        }));
  }
1020
1021
1022
1023
1024
  if (num_valid_neighbors == 0 || fanout == -1) {
    *picked_num_ptr = num_valid_neighbors;
  } else {
    *picked_num_ptr = replace ? fanout : std::min(fanout, num_valid_neighbors);
  }
1025
1026
}

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
torch::Tensor TemporalMask(
    int64_t seed_timestamp, torch::Tensor csc_indices,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
    const torch::optional<torch::Tensor>& edge_timestamp,
    std::pair<int64_t, int64_t> edge_range) {
  auto [l, r] = edge_range;
  torch::Tensor mask = torch::ones({r - l}, torch::kBool);
  if (node_timestamp.has_value()) {
    auto neighbor_timestamp =
        node_timestamp.value().index_select(0, csc_indices.slice(0, l, r));
1038
    mask &= neighbor_timestamp < seed_timestamp;
1039
1040
  }
  if (edge_timestamp.has_value()) {
1041
    mask &= edge_timestamp.value().slice(0, l, r) < seed_timestamp;
1042
1043
1044
1045
1046
1047
1048
  }
  if (probs_or_mask.has_value()) {
    mask &= probs_or_mask.value().slice(0, l, r) != 0;
  }
  return mask;
}

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
/**
 * @brief Fast path for temporal sampling without probability. It is used when
 * the number of neighbors is large. It randomly samples neighbors and checks
 * the timestamp of the neighbors. It is successful if the number of sampled
 * neighbors in kTriedThreshold trials is equal to the fanout.
 */
std::pair<bool, std::vector<int64_t>> FastTemporalPick(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices, int64_t fanout,
    bool replace, const torch::optional<torch::Tensor>& node_timestamp,
    const torch::optional<torch::Tensor>& edge_timestamp, int64_t seed_offset,
    int64_t offset, int64_t num_neighbors) {
  constexpr int64_t kTriedThreshold = 1000;
  auto timestamp = utils::GetValueByIndex<int64_t>(seed_timestamp, seed_offset);
  std::vector<int64_t> sampled_edges;
  sampled_edges.reserve(fanout);
  std::set<int64_t> sampled_edge_set;
  int64_t sample_count = 0;
  int64_t tried = 0;
  while (sample_count < fanout && tried < kTriedThreshold) {
    int64_t edge_id =
        RandomEngine::ThreadLocal()->RandInt(offset, offset + num_neighbors);
    ++tried;
    if (!replace && sampled_edge_set.count(edge_id) > 0) {
      continue;
    }
    if (node_timestamp.has_value()) {
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
      bool flag = true;
      AT_DISPATCH_INDEX_TYPES(
          csc_indices.scalar_type(), "CheckNodeTimeStamp", ([&] {
            int64_t neighbor_id =
                utils::GetValueByIndex<index_t>(csc_indices, edge_id);
            if (utils::GetValueByIndex<int64_t>(
                    node_timestamp.value(), neighbor_id) >= timestamp)
              flag = false;
          }));
      if (!flag) continue;
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
    }
    if (edge_timestamp.has_value() &&
        utils::GetValueByIndex<int64_t>(edge_timestamp.value(), edge_id) >=
            timestamp) {
      continue;
    }
    if (!replace) {
      sampled_edge_set.insert(edge_id);
    }
    sampled_edges.push_back(edge_id);
    sample_count++;
  }
  if (sample_count < fanout) {
    return {false, {}};
  }
  return {true, sampled_edges};
}

1103
1104
1105
1106
1107
1108
int64_t TemporalNumPick(
    torch::Tensor seed_timestamp, torch::Tensor csc_indics, int64_t fanout,
    bool replace, const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
    const torch::optional<torch::Tensor>& edge_timestamp, int64_t seed_offset,
    int64_t offset, int64_t num_neighbors) {
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
  constexpr int64_t kFastPathThreshold = 1000;
  if (num_neighbors > kFastPathThreshold && !probs_or_mask.has_value()) {
    // TODO: Currently we use the fast path both in TemporalNumPick and
    // TemporalPick. We may only sample once in TemporalNumPick and use the
    // sampled edges in TemporalPick to avoid sampling twice.
    auto [success, sampled_edges] = FastTemporalPick(
        seed_timestamp, csc_indics, fanout, replace, node_timestamp,
        edge_timestamp, seed_offset, offset, num_neighbors);
    if (success) return sampled_edges.size();
  }
1119
1120
1121
1122
1123
1124
1125
1126
1127
  auto mask = TemporalMask(
      utils::GetValueByIndex<int64_t>(seed_timestamp, seed_offset), csc_indics,
      probs_or_mask, node_timestamp, edge_timestamp,
      {offset, offset + num_neighbors});
  int64_t num_valid_neighbors = utils::GetValueByIndex<int64_t>(mask.sum(), 0);
  if (num_valid_neighbors == 0 || fanout == -1) return num_valid_neighbors;
  return replace ? fanout : std::min(fanout, num_valid_neighbors);
}

1128
1129
1130
template <typename PickedNumType>
void NumPickByEtype(
    bool with_seed_offsets, const std::vector<int64_t>& fanouts, bool replace,
1131
1132
    const torch::Tensor& type_per_edge,
    const torch::optional<torch::Tensor>& probs_or_mask, int64_t offset,
1133
1134
    int64_t num_neighbors, PickedNumType* num_picked_ptr, int64_t seed_index,
    const std::vector<int64_t>& etype_id_to_num_picked_offset) {
1135
1136
  int64_t etype_begin = offset;
  const int64_t end = offset + num_neighbors;
1137
  PickedNumType total_count = 0;
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
  AT_DISPATCH_INTEGRAL_TYPES(
      type_per_edge.scalar_type(), "NumPickFnByEtype", ([&] {
        const scalar_t* type_per_edge_data = type_per_edge.data_ptr<scalar_t>();
        while (etype_begin < end) {
          scalar_t etype = type_per_edge_data[etype_begin];
          TORCH_CHECK(
              etype >= 0 && etype < (int64_t)fanouts.size(),
              "Etype values exceed the number of fanouts.");
          auto etype_end_it = std::upper_bound(
              type_per_edge_data + etype_begin, type_per_edge_data + end,
              etype);
          int64_t etype_end = etype_end_it - type_per_edge_data;
          // Do sampling for one etype.
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
          if (with_seed_offsets) {
            // The pick numbers aren't stored continuously, but separately for
            // each different etype.
            const auto offset =
                etype_id_to_num_picked_offset[etype] + seed_index;
            NumPick(
                fanouts[etype], replace, probs_or_mask, etype_begin,
                etype_end - etype_begin, num_picked_ptr + offset);
          } else {
            PickedNumType picked_count = 0;
            NumPick(
                fanouts[etype], replace, probs_or_mask, etype_begin,
                etype_end - etype_begin, &picked_count);
            total_count += picked_count;
          }
1166
1167
1168
          etype_begin = etype_end;
        }
      }));
1169
1170
1171
  if (!with_seed_offsets) {
    num_picked_ptr[seed_index] = total_count;
  }
1172
1173
}

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
int64_t TemporalNumPickByEtype(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices,
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::Tensor& type_per_edge,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
    const torch::optional<torch::Tensor>& edge_timestamp, int64_t seed_offset,
    int64_t offset, int64_t num_neighbors) {
  int64_t etype_begin = offset;
  const int64_t end = offset + num_neighbors;
  int64_t total_count = 0;
  AT_DISPATCH_INTEGRAL_TYPES(
      type_per_edge.scalar_type(), "TemporalNumPickFnByEtype", ([&] {
        const scalar_t* type_per_edge_data = type_per_edge.data_ptr<scalar_t>();
        while (etype_begin < end) {
          scalar_t etype = type_per_edge_data[etype_begin];
          TORCH_CHECK(
              etype >= 0 && etype < (int64_t)fanouts.size(),
              "Etype values exceed the number of fanouts.");
          auto etype_end_it = std::upper_bound(
              type_per_edge_data + etype_begin, type_per_edge_data + end,
              etype);
          int64_t etype_end = etype_end_it - type_per_edge_data;
          // Do sampling for one etype.
          total_count += TemporalNumPick(
              seed_timestamp, csc_indices, fanouts[etype], replace,
              probs_or_mask, node_timestamp, edge_timestamp, seed_offset,
              etype_begin, etype_end - etype_begin);
          etype_begin = etype_end;
        }
      }));
  return total_count;
}

1208
1209
1210
1211
1212
1213
1214
1215
/**
 * @brief Perform uniform sampling of elements and return the sampled indices.
 *
 * @param offset The starting edge ID for the connected neighbors of the sampled
 * node.
 * @param num_neighbors The number of neighbors to pick.
 * @param fanout The number of edges to be sampled for each node. It should be
 * >= 0 or -1.
1216
1217
1218
 *  - When the value is -1, all neighbors will be sampled once regardless of
 * replacement. It is equivalent to selecting all neighbors when the fanout is
 * >= the number of neighbors (and replacement is set to false).
1219
1220
 *  - When the value is a non-negative integer, it serves as a minimum
 * threshold for selecting neighbors.
1221
 * @param replace Boolean indicating whether the sample is performed with or
1222
1223
1224
 * without replacement. If True, a value can be selected multiple times.
 * Otherwise, each value can be selected only once.
 * @param options Tensor options specifying the desired data type of the result.
1225
1226
 * @param picked_data_ptr The destination address where the picked neighbors
 * should be put. Enough memory space should be allocated in advance.
1227
 */
1228
template <typename PickedType>
1229
inline int64_t UniformPick(
1230
    int64_t offset, int64_t num_neighbors, int64_t fanout, bool replace,
1231
    const torch::TensorOptions& options, PickedType* picked_data_ptr) {
1232
  if ((fanout == -1) || (num_neighbors <= fanout && !replace)) {
1233
    std::iota(picked_data_ptr, picked_data_ptr + num_neighbors, offset);
1234
    return num_neighbors;
1235
  } else if (replace) {
1236
1237
1238
1239
1240
    std::memcpy(
        picked_data_ptr,
        torch::randint(offset, offset + num_neighbors, {fanout}, options)
            .data_ptr<PickedType>(),
        fanout * sizeof(PickedType));
1241
    return fanout;
1242
  } else {
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
    // We use different sampling strategies for different sampling case.
    if (fanout >= num_neighbors / 10) {
      // [Algorithm]
      // This algorithm is conceptually related to the Fisher-Yates
      // shuffle.
      //
      // [Complexity Analysis]
      // This algorithm's memory complexity is O(num_neighbors), but
      // it generates fewer random numbers (O(fanout)).
      //
      // (Compare) Reservoir algorithm is one of the most classical
      // sampling algorithms. Both the reservoir algorithm and our
      // algorithm offer distinct advantages, we need to compare to
      // illustrate our trade-offs.
      // The reservoir algorithm is memory-efficient (O(fanout)) but
      // creates many random numbers (O(num_neighbors)), which is
      // costly.
      //
      // [Practical Consideration]
      // Use this algorithm when `fanout >= num_neighbors / 10` to
      // reduce computation.
      // In this scenarios above, memory complexity is not a concern due
      // to the small size of both `fanout` and `num_neighbors`. And it
      // is efficient to allocate a small amount of memory. So the
      // algorithm performence is great in this case.
      std::vector<PickedType> seq(num_neighbors);
      // Assign the seq with [offset, offset + num_neighbors].
      std::iota(seq.begin(), seq.end(), offset);
      for (int64_t i = 0; i < fanout; ++i) {
        auto j = RandomEngine::ThreadLocal()->RandInt(i, num_neighbors);
        std::swap(seq[i], seq[j]);
      }
      // Save the randomly sampled fanout elements to the output tensor.
      std::copy(seq.begin(), seq.begin() + fanout, picked_data_ptr);
1277
      return fanout;
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
    } else if (fanout < 64) {
      // [Algorithm]
      // Use linear search to verify uniqueness.
      //
      // [Complexity Analysis]
      // Since the set of numbers is small (up to 64), so it is more
      // cost-effective for the CPU to use this algorithm.
      auto begin = picked_data_ptr;
      auto end = picked_data_ptr + fanout;

      while (begin != end) {
        // Put the new random number in the last position.
        *begin = RandomEngine::ThreadLocal()->RandInt(
            offset, offset + num_neighbors);
        // Check if a new value doesn't exist in current
        // range(picked_data_ptr, begin). Otherwise get a new
        // value until we haven't unique range of elements.
        auto it = std::find(picked_data_ptr, begin, *begin);
        if (it == begin) ++begin;
      }
1298
      return fanout;
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
    } else {
      // [Algorithm]
      // Use hash-set to verify uniqueness. In the best scenario, the
      // time complexity is O(fanout), assuming no conflicts occur.
      //
      // [Complexity Analysis]
      // Let K = (fanout / num_neighbors), the expected number of extra
      // sampling steps is roughly K^2 / (1-K) * num_neighbors, which
      // means in the worst case scenario, the time complexity is
      // O(num_neighbors^2).
      //
      // [Practical Consideration]
      // In practice, we set the threshold K to 1/10. This trade-off is
      // due to the slower performance of std::unordered_set, which
      // would otherwise increase the sampling cost. By doing so, we
      // achieve a balance between theoretical efficiency and practical
      // performance.
      std::unordered_set<PickedType> picked_set;
      while (static_cast<int64_t>(picked_set.size()) < fanout) {
        picked_set.insert(RandomEngine::ThreadLocal()->RandInt(
            offset, offset + num_neighbors));
      }
      std::copy(picked_set.begin(), picked_set.end(), picked_data_ptr);
1322
      return picked_set.size();
1323
    }
1324
1325
1326
  }
}

1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
/** @brief An operator to perform non-uniform sampling. */
static torch::Tensor NonUniformPickOp(
    torch::Tensor probs, int64_t fanout, bool replace) {
  auto positive_probs_indices = probs.nonzero().squeeze(1);
  auto num_positive_probs = positive_probs_indices.size(0);
  if (num_positive_probs == 0) return torch::empty({0}, torch::kLong);
  if ((fanout == -1) || (num_positive_probs <= fanout && !replace)) {
    return positive_probs_indices;
  }
  if (!replace) fanout = std::min(fanout, num_positive_probs);
  if (fanout == 0) return torch::empty({0}, torch::kLong);
  auto ret_tensor = torch::empty({fanout}, torch::kLong);
  auto ret_ptr = ret_tensor.data_ptr<int64_t>();
  AT_DISPATCH_FLOATING_TYPES(
      probs.scalar_type(), "MultinomialSampling", ([&] {
        auto probs_data_ptr = probs.data_ptr<scalar_t>();
        auto positive_probs_indices_ptr =
            positive_probs_indices.data_ptr<int64_t>();

        if (!replace) {
          // The algorithm is from gumbel softmax.
          // s = argmax( logp - log(-log(eps)) ) where eps ~ U(0, 1).
          // Here we can apply exp to the formula which will not affect result
          // of argmax or topk. Then we have
          // s = argmax( p / (-log(eps)) ) where eps ~ U(0, 1).
          // We can also simplify the formula above by
          // s = argmax( p / q ) where q ~ Exp(1).
          if (fanout == 1) {
            // Return argmax(p / q).
            scalar_t max_prob = 0;
            int64_t max_prob_index = -1;
            // We only care about the neighbors with non-zero probability.
            for (auto i = 0; i < num_positive_probs; ++i) {
              // Calculate (p / q) for the current neighbor.
              scalar_t current_prob =
                  probs_data_ptr[positive_probs_indices_ptr[i]] /
                  RandomEngine::ThreadLocal()->Exponential(1.);
              if (current_prob > max_prob) {
                max_prob = current_prob;
                max_prob_index = positive_probs_indices_ptr[i];
              }
            }
            ret_ptr[0] = max_prob_index;
          } else {
            // Return topk(p / q).
            std::vector<std::pair<scalar_t, int64_t>> q(num_positive_probs);
            for (auto i = 0; i < num_positive_probs; ++i) {
              q[i].first = probs_data_ptr[positive_probs_indices_ptr[i]] /
                           RandomEngine::ThreadLocal()->Exponential(1.);
              q[i].second = positive_probs_indices_ptr[i];
            }
            if (fanout < num_positive_probs / 64) {
              // Use partial_sort.
              std::partial_sort(
                  q.begin(), q.begin() + fanout, q.end(), std::greater{});
              for (auto i = 0; i < fanout; ++i) {
                ret_ptr[i] = q[i].second;
              }
            } else {
              // Use nth_element.
              std::nth_element(
                  q.begin(), q.begin() + fanout - 1, q.end(), std::greater{});
              for (auto i = 0; i < fanout; ++i) {
                ret_ptr[i] = q[i].second;
              }
            }
          }
        } else {
          // Calculate cumulative sum of probabilities.
          std::vector<scalar_t> prefix_sum_probs(num_positive_probs);
          scalar_t sum_probs = 0;
          for (auto i = 0; i < num_positive_probs; ++i) {
            sum_probs += probs_data_ptr[positive_probs_indices_ptr[i]];
            prefix_sum_probs[i] = sum_probs;
          }
          // Normalize.
          if ((sum_probs > 1.00001) || (sum_probs < 0.99999)) {
            for (auto i = 0; i < num_positive_probs; ++i) {
              prefix_sum_probs[i] /= sum_probs;
            }
          }
          for (auto i = 0; i < fanout; ++i) {
            // Sample a probability mass from a uniform distribution.
            double uniform_sample =
                RandomEngine::ThreadLocal()->Uniform(0., 1.);
            // Use a binary search to find the index.
            int sampled_index = std::lower_bound(
                                    prefix_sum_probs.begin(),
                                    prefix_sum_probs.end(), uniform_sample) -
                                prefix_sum_probs.begin();
            ret_ptr[i] = positive_probs_indices_ptr[sampled_index];
          }
        }
      }));
  return ret_tensor;
}

1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
/**
 * @brief Perform non-uniform sampling of elements based on probabilities and
 * return the sampled indices.
 *
 * If 'probs_or_mask' is provided, it indicates that the sampling is
 * non-uniform. In such cases:
 * - When the number of neighbors with non-zero probability is less than or
 * equal to fanout, all neighbors with non-zero probability will be selected.
 * - When the number of neighbors with non-zero probability exceeds fanout, the
 * sampling process will select 'fanout' elements based on their respective
 * probabilities. Higher probabilities will increase the chances of being chosen
 * during the sampling process.
 *
 * @param offset The starting edge ID for the connected neighbors of the sampled
 * node.
 * @param num_neighbors The number of neighbors to pick.
 * @param fanout The number of edges to be sampled for each node. It should be
 * >= 0 or -1.
1442
1443
1444
1445
 *  - When the value is -1, all neighbors with non-zero probability will be
 * sampled once regardless of replacement. It is equivalent to selecting all
 * neighbors with non-zero probability when the fanout is >= the number of
 * neighbors (and replacement is set to false).
1446
1447
 *  - When the value is a non-negative integer, it serves as a minimum
 * threshold for selecting neighbors.
1448
 * @param replace Boolean indicating whether the sample is performed with or
1449
1450
1451
1452
1453
1454
1455
 * without replacement. If True, a value can be selected multiple times.
 * Otherwise, each value can be selected only once.
 * @param options Tensor options specifying the desired data type of the result.
 * @param probs_or_mask Optional tensor containing the (unnormalized)
 * probabilities associated with each neighboring edge of a node in the original
 * graph. It must be a 1D floating-point tensor with the number of elements
 * equal to the number of edges in the graph.
1456
1457
 * @param picked_data_ptr The destination address where the picked neighbors
 * should be put. Enough memory space should be allocated in advance.
1458
 */
1459
template <typename PickedType>
1460
inline int64_t NonUniformPick(
1461
    int64_t offset, int64_t num_neighbors, int64_t fanout, bool replace,
1462
    const torch::TensorOptions& options, const torch::Tensor& probs_or_mask,
1463
    PickedType* picked_data_ptr) {
1464
  auto local_probs =
1465
1466
1467
      probs_or_mask.size(0) > num_neighbors
          ? probs_or_mask.slice(0, offset, offset + num_neighbors)
          : probs_or_mask;
1468
1469
1470
1471
1472
  auto picked_indices = NonUniformPickOp(local_probs, fanout, replace);
  auto picked_indices_ptr = picked_indices.data_ptr<int64_t>();
  for (int i = 0; i < picked_indices.numel(); ++i) {
    picked_data_ptr[i] =
        static_cast<PickedType>(picked_indices_ptr[i]) + offset;
1473
  }
1474
  return picked_indices.numel();
1475
1476
}

1477
template <typename PickedType>
1478
int64_t Pick(
1479
1480
    int64_t offset, int64_t num_neighbors, int64_t fanout, bool replace,
    const torch::TensorOptions& options,
1481
    const torch::optional<torch::Tensor>& probs_or_mask,
1482
    SamplerArgs<SamplerType::NEIGHBOR> args, PickedType* picked_data_ptr) {
1483
  if (fanout == 0 || num_neighbors == 0) return 0;
1484
  if (probs_or_mask.has_value()) {
1485
    return NonUniformPick(
1486
        offset, num_neighbors, fanout, replace, options, probs_or_mask.value(),
1487
        picked_data_ptr);
1488
  } else {
1489
    return UniformPick(
1490
        offset, num_neighbors, fanout, replace, options, picked_data_ptr);
1491
1492
1493
  }
}

1494
template <SamplerType S, typename PickedType>
1495
1496
1497
1498
1499
1500
int64_t TemporalPick(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices,
    int64_t seed_offset, int64_t offset, int64_t num_neighbors, int64_t fanout,
    bool replace, const torch::TensorOptions& options,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
1501
    const torch::optional<torch::Tensor>& edge_timestamp, SamplerArgs<S> args,
1502
    PickedType* picked_data_ptr) {
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
  constexpr int64_t kFastPathThreshold = 1000;
  if (S == SamplerType::NEIGHBOR && num_neighbors > kFastPathThreshold &&
      !probs_or_mask.has_value()) {
    auto [success, sampled_edges] = FastTemporalPick(
        seed_timestamp, csc_indices, fanout, replace, node_timestamp,
        edge_timestamp, seed_offset, offset, num_neighbors);
    if (success) {
      for (size_t i = 0; i < sampled_edges.size(); ++i) {
        picked_data_ptr[i] = static_cast<PickedType>(sampled_edges[i]);
      }
      return sampled_edges.size();
    }
  }
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
  auto mask = TemporalMask(
      utils::GetValueByIndex<int64_t>(seed_timestamp, seed_offset), csc_indices,
      probs_or_mask, node_timestamp, edge_timestamp,
      {offset, offset + num_neighbors});
  torch::Tensor masked_prob;
  if (probs_or_mask.has_value()) {
    masked_prob =
        probs_or_mask.value().slice(0, offset, offset + num_neighbors) * mask;
  } else {
    masked_prob = mask.to(torch::kFloat32);
  }
1527
1528
1529
1530
1531
1532
1533
1534
1535
  if constexpr (S == SamplerType::NEIGHBOR) {
    auto picked_indices = NonUniformPickOp(masked_prob, fanout, replace);
    auto picked_indices_ptr = picked_indices.data_ptr<int64_t>();
    for (int i = 0; i < picked_indices.numel(); ++i) {
      picked_data_ptr[i] =
          static_cast<PickedType>(picked_indices_ptr[i]) + offset;
    }
    return picked_indices.numel();
  }
1536
  if constexpr (is_labor(S)) {
1537
1538
1539
    return Pick(
        offset, num_neighbors, fanout, replace, options, masked_prob, args,
        picked_data_ptr);
1540
1541
1542
  }
}

1543
template <SamplerType S, typename PickedType>
1544
int64_t PickByEtype(
1545
1546
1547
    bool with_seed_offsets, int64_t offset, int64_t num_neighbors,
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::TensorOptions& options, const torch::Tensor& type_per_edge,
1548
    const torch::optional<torch::Tensor>& probs_or_mask, SamplerArgs<S> args,
1549
1550
1551
    PickedType* picked_data_ptr, int64_t seed_index,
    PickedType* subgraph_indptr_ptr,
    const std::vector<int64_t>& etype_id_to_num_picked_offset) {
1552
1553
  int64_t etype_begin = offset;
  int64_t etype_end = offset;
1554
  int64_t picked_total_count = 0;
1555
1556
1557
  AT_DISPATCH_INTEGRAL_TYPES(
      type_per_edge.scalar_type(), "PickByEtype", ([&] {
        const scalar_t* type_per_edge_data = type_per_edge.data_ptr<scalar_t>();
1558
1559
1560
        const auto end = offset + num_neighbors;
        while (etype_begin < end) {
          scalar_t etype = type_per_edge_data[etype_begin];
1561
          TORCH_CHECK(
1562
              etype >= 0 && etype < (int64_t)fanouts.size(),
1563
              "Etype values exceed the number of fanouts.");
1564
          int64_t fanout = fanouts[etype];
1565
1566
1567
1568
          auto etype_end_it = std::upper_bound(
              type_per_edge_data + etype_begin, type_per_edge_data + end,
              etype);
          etype_end = etype_end_it - type_per_edge_data;
1569
1570
          // Do sampling for one etype. The picked nodes aren't stored
          // continuously, but separately for each different etype.
1571
          if (fanout != 0) {
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
            auto picked_count = 0;
            if (with_seed_offsets) {
              const auto indptr_offset =
                  etype_id_to_num_picked_offset[etype] + seed_index;
              picked_count = Pick(
                  etype_begin, etype_end - etype_begin, fanout, replace,
                  options, probs_or_mask, args,
                  picked_data_ptr + subgraph_indptr_ptr[indptr_offset]);
              TORCH_CHECK(
                  subgraph_indptr_ptr[indptr_offset + 1] -
                          subgraph_indptr_ptr[indptr_offset] ==
                      picked_count,
                  "Actual picked count doesn't match the calculated "
                  "pick number.");
            } else {
              picked_count = Pick(
                  etype_begin, etype_end - etype_begin, fanout, replace,
                  options, probs_or_mask, args,
                  picked_data_ptr + subgraph_indptr_ptr[seed_index] +
                      picked_total_count);
            }
            picked_total_count += picked_count;
1594
1595
1596
1597
          }
          etype_begin = etype_end;
        }
      }));
1598
  return picked_total_count;
1599
1600
}

1601
template <SamplerType S, typename PickedType>
1602
1603
1604
1605
1606
1607
1608
int64_t TemporalPickByEtype(
    torch::Tensor seed_timestamp, torch::Tensor csc_indices,
    int64_t seed_offset, int64_t offset, int64_t num_neighbors,
    const std::vector<int64_t>& fanouts, bool replace,
    const torch::TensorOptions& options, const torch::Tensor& type_per_edge,
    const torch::optional<torch::Tensor>& probs_or_mask,
    const torch::optional<torch::Tensor>& node_timestamp,
1609
    const torch::optional<torch::Tensor>& edge_timestamp, SamplerArgs<S> args,
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
    PickedType* picked_data_ptr) {
  int64_t etype_begin = offset;
  int64_t etype_end = offset;
  int64_t pick_offset = 0;
  AT_DISPATCH_INTEGRAL_TYPES(
      type_per_edge.scalar_type(), "TemporalPickByEtype", ([&] {
        const scalar_t* type_per_edge_data = type_per_edge.data_ptr<scalar_t>();
        const auto end = offset + num_neighbors;
        while (etype_begin < end) {
          scalar_t etype = type_per_edge_data[etype_begin];
          TORCH_CHECK(
              etype >= 0 && etype < (int64_t)fanouts.size(),
              "Etype values exceed the number of fanouts.");
          int64_t fanout = fanouts[etype];
          auto etype_end_it = std::upper_bound(
              type_per_edge_data + etype_begin, type_per_edge_data + end,
              etype);
          etype_end = etype_end_it - type_per_edge_data;
          // Do sampling for one etype.
          if (fanout != 0) {
            int64_t picked_count = TemporalPick(
                seed_timestamp, csc_indices, seed_offset, etype_begin,
                etype_end - etype_begin, fanout, replace, options,
1633
                probs_or_mask, node_timestamp, edge_timestamp, args,
1634
1635
1636
1637
1638
1639
1640
1641
1642
                picked_data_ptr + pick_offset);
            pick_offset += picked_count;
          }
          etype_begin = etype_end;
        }
      }));
  return pick_offset;
}

1643
1644
template <SamplerType S, typename PickedType>
std::enable_if_t<is_labor(S), int64_t> Pick(
1645
1646
    int64_t offset, int64_t num_neighbors, int64_t fanout, bool replace,
    const torch::TensorOptions& options,
1647
1648
    const torch::optional<torch::Tensor>& probs_or_mask, SamplerArgs<S> args,
    PickedType* picked_data_ptr) {
1649
  if (fanout == 0 || num_neighbors == 0) return 0;
1650
  if (probs_or_mask.has_value()) {
1651
    if (fanout < 0) {
1652
      return NonUniformPick(
1653
1654
          offset, num_neighbors, fanout, replace, options,
          probs_or_mask.value(), picked_data_ptr);
1655
    } else {
1656
      int64_t picked_count;
1657
1658
1659
      AT_DISPATCH_FLOATING_TYPES(
          probs_or_mask.value().scalar_type(), "LaborPickFloatType", ([&] {
            if (replace) {
1660
              picked_count = LaborPick<true, true, scalar_t>(
1661
1662
1663
                  offset, num_neighbors, fanout, options, probs_or_mask, args,
                  picked_data_ptr);
            } else {
1664
              picked_count = LaborPick<true, false, scalar_t>(
1665
1666
1667
1668
                  offset, num_neighbors, fanout, options, probs_or_mask, args,
                  picked_data_ptr);
            }
          }));
1669
      return picked_count;
1670
1671
    }
  } else if (fanout < 0) {
1672
    return UniformPick(
1673
        offset, num_neighbors, fanout, replace, options, picked_data_ptr);
1674
  } else if (replace) {
1675
    return LaborPick<false, true, float>(
1676
        offset, num_neighbors, fanout, options,
1677
        /* probs_or_mask= */ torch::nullopt, args, picked_data_ptr);
1678
  } else {  // replace = false
1679
    return LaborPick<false, false, float>(
1680
        offset, num_neighbors, fanout, options,
1681
        /* probs_or_mask= */ torch::nullopt, args, picked_data_ptr);
1682
1683
1684
1685
1686
1687
1688
1689
  }
}

template <typename T, typename U>
inline void safe_divide(T& a, U b) {
  a = b > 0 ? (T)(a / b) : std::numeric_limits<T>::infinity();
}

1690
1691
1692
1693
1694
1695
1696
1697
namespace labor {

template <typename T>
inline T invcdf(T u, int64_t n, T rem) {
  constexpr T one = 1;
  return rem * (one - std::pow(one - u, one / n));
}

1698
template <typename T, typename seed_t>
1699
inline T jth_sorted_uniform_random(
1700
    seed_t seed, int64_t t, int64_t c, int64_t j, T& rem, int64_t n) {
1701
1702
1703
1704
1705
1706
1707
1708
  const T u = seed.uniform(t + j * c);
  // https://mathematica.stackexchange.com/a/256707
  rem -= invcdf(u, n, rem);
  return 1 - rem;
}

};  // namespace labor

1709
1710
1711
1712
1713
1714
1715
1716
1717
/**
 * @brief Perform uniform-nonuniform sampling of elements depending on the
 * template parameter NonUniform and return the sampled indices.
 *
 * @param offset The starting edge ID for the connected neighbors of the sampled
 * node.
 * @param num_neighbors The number of neighbors to pick.
 * @param fanout The number of edges to be sampled for each node. It should be
 * >= 0 or -1.
1718
1719
1720
1721
 *  - When the value is -1, all neighbors (with non-zero probability, if
 * weighted) will be sampled once regardless of replacement. It is equivalent to
 * selecting all neighbors with non-zero probability when the fanout is >= the
 * number of neighbors (and replacement is set to false).
1722
1723
1724
1725
1726
1727
1728
1729
 *  - When the value is a non-negative integer, it serves as a minimum
 * threshold for selecting neighbors.
 * @param options Tensor options specifying the desired data type of the result.
 * @param probs_or_mask Optional tensor containing the (unnormalized)
 * probabilities associated with each neighboring edge of a node in the original
 * graph. It must be a 1D floating-point tensor with the number of elements
 * equal to the number of edges in the graph.
 * @param args Contains labor specific arguments.
1730
1731
 * @param picked_data_ptr The destination address where the picked neighbors
 * should be put. Enough memory space should be allocated in advance.
1732
 */
1733
template <
1734
1735
1736
    bool NonUniform, bool Replace, typename ProbsType, SamplerType S,
    typename PickedType, int StackSize>
inline std::enable_if_t<is_labor(S), int64_t> LaborPick(
1737
1738
    int64_t offset, int64_t num_neighbors, int64_t fanout,
    const torch::TensorOptions& options,
1739
1740
    const torch::optional<torch::Tensor>& probs_or_mask, SamplerArgs<S> args,
    PickedType* picked_data_ptr) {
1741
  fanout = Replace ? fanout : std::min(fanout, num_neighbors);
1742
  if (!NonUniform && !Replace && fanout >= num_neighbors) {
1743
    std::iota(picked_data_ptr, picked_data_ptr + num_neighbors, offset);
1744
    return num_neighbors;
1745
1746
  }
  // Assuming max_degree of a vertex is <= 4 billion.
1747
1748
1749
1750
1751
1752
1753
1754
1755
  std::array<std::pair<float, uint32_t>, StackSize> heap;
  auto heap_data = heap.data();
  torch::Tensor heap_tensor;
  if (fanout > StackSize) {
    constexpr int factor = sizeof(heap_data[0]) / sizeof(int32_t);
    heap_tensor = torch::empty({fanout * factor}, torch::kInt32);
    heap_data = reinterpret_cast<std::pair<float, uint32_t>*>(
        heap_tensor.data_ptr<int32_t>());
  }
1756
1757
1758
  const ProbsType* local_probs_data =
      NonUniform ? probs_or_mask.value().data_ptr<ProbsType>() + offset
                 : nullptr;
1759
1760
1761
  if (NonUniform && probs_or_mask.value().size(0) <= num_neighbors) {
    local_probs_data -= offset;
  }
1762
  AT_DISPATCH_INDEX_TYPES(
1763
      args.indices.scalar_type(), "LaborPickMain", ([&] {
1764
1765
        const auto local_indices_data =
            reinterpret_cast<index_t*>(args.indices.data_ptr()) + offset;
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
        if constexpr (Replace) {
          // [Algorithm] @mfbalin
          // Use a max-heap to get rid of the big random numbers and filter the
          // smallest fanout of them. Implements arXiv:2210.13339 Section A.3.
          // Unlike sampling without replacement below, the same item can be
          // included fanout times in our sample. Thus, we sort and pick the
          // smallest fanout random numbers out of num_neighbors * fanout of
          // them. Each item has fanout many random numbers in the race and the
          // smallest fanout of them get picked. Instead of generating
          // fanout * num_neighbors random numbers and increase the complexity,
          // I devised an algorithm to generate the fanout numbers for an item
          // in a sorted manner on demand, meaning we continue generating random
          // numbers for an item only if it has been sampled that many times
          // already.
          // https://gist.github.com/mfbalin/096dcad5e3b1f6a59ff7ff2f9f541618
          //
          // [Complexity Analysis]
          // Will modify the heap at most linear in O(num_neighbors + fanout)
          // and each modification takes O(log(fanout)). So the total complexity
          // is O((fanout + num_neighbors) log(fanout)). It is possible to
          // decrease the logarithmic factor down to
          // O(log(min(fanout, num_neighbors))).
1788
1789
1790
1791
1792
1793
1794
1795
          std::array<float, StackSize> remaining;
          auto remaining_data = remaining.data();
          torch::Tensor remaining_tensor;
          if (num_neighbors > StackSize) {
            remaining_tensor = torch::empty({num_neighbors}, torch::kFloat32);
            remaining_data = remaining_tensor.data_ptr<float>();
          }
          std::fill_n(remaining_data, num_neighbors, 1.f);
1796
1797
1798
          auto heap_end = heap_data;
          const auto init_count = (num_neighbors + fanout - 1) / num_neighbors;
          auto sample_neighbor_i_with_index_t_jth_time =
1799
              [&](index_t t, int64_t j, uint32_t i) {
1800
                auto rnd = labor::jth_sorted_uniform_random(
1801
                    args.random_seed, t, args.num_nodes, j, remaining_data[i],
1802
1803
1804
1805
1806
1807
                    fanout - j);  // r_t
                if constexpr (NonUniform) {
                  safe_divide(rnd, local_probs_data[i]);
                }  // r_t / \pi_t
                if (heap_end < heap_data + fanout) {
                  heap_end[0] = std::make_pair(rnd, i);
1808
1809
1810
                  if (++heap_end >= heap_data + fanout) {
                    std::make_heap(heap_data, heap_data + fanout);
                  }
1811
1812
1813
1814
1815
1816
1817
                  return false;
                } else if (rnd < heap_data[0].first) {
                  std::pop_heap(heap_data, heap_data + fanout);
                  heap_data[fanout - 1] = std::make_pair(rnd, i);
                  std::push_heap(heap_data, heap_data + fanout);
                  return false;
                } else {
1818
                  remaining_data[i] = -1;
1819
1820
1821
1822
                  return true;
                }
              };
          for (uint32_t i = 0; i < num_neighbors; ++i) {
1823
            const auto t = local_indices_data[i];
1824
1825
1826
1827
1828
            for (int64_t j = 0; j < init_count; j++) {
              sample_neighbor_i_with_index_t_jth_time(t, j, i);
            }
          }
          for (uint32_t i = 0; i < num_neighbors; ++i) {
1829
            if (remaining_data[i] == -1) continue;
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
            const auto t = local_indices_data[i];
            for (int64_t j = init_count; j < fanout; ++j) {
              if (sample_neighbor_i_with_index_t_jth_time(t, j, i)) break;
            }
          }
        } else {
          // [Algorithm]
          // Use a max-heap to get rid of the big random numbers and filter the
          // smallest fanout of them. Implements arXiv:2210.13339 Section A.3.
          //
          // [Complexity Analysis]
          // the first for loop and std::make_heap runs in time O(fanouts).
          // The next for loop compares each random number to the current
          // minimum fanout numbers. For any given i, the probability that the
          // current random number will replace any number in the heap is fanout
          // / i. Summing from i=fanout to num_neighbors, we get f * (H_n -
          // H_f), where n is num_neighbors and f is fanout, H_f is \sum_j=1^f
          // 1/j. In the end H_n - H_f = O(log n/f), there are n - f iterations,
          // each heap operation takes time log f, so the total complexity is
          // O(f + (n - f)
          // + f log(n/f) log f) = O(n + f log(f) log(n/f)). If f << n (f is a
          // constant in almost all cases), then the average complexity is
          // O(num_neighbors).
          for (uint32_t i = 0; i < fanout; ++i) {
            const auto t = local_indices_data[i];
1855
            auto rnd = args.random_seed.uniform(t);  // r_t
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
            if constexpr (NonUniform) {
              safe_divide(rnd, local_probs_data[i]);
            }  // r_t / \pi_t
            heap_data[i] = std::make_pair(rnd, i);
          }
          if (!NonUniform || fanout < num_neighbors) {
            std::make_heap(heap_data, heap_data + fanout);
          }
          for (uint32_t i = fanout; i < num_neighbors; ++i) {
            const auto t = local_indices_data[i];
1866
            auto rnd = args.random_seed.uniform(t);  // r_t
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
            if constexpr (NonUniform) {
              safe_divide(rnd, local_probs_data[i]);
            }  // r_t / \pi_t
            if (rnd < heap_data[0].first) {
              std::pop_heap(heap_data, heap_data + fanout);
              heap_data[fanout - 1] = std::make_pair(rnd, i);
              std::push_heap(heap_data, heap_data + fanout);
            }
          }
        }
      }));
  int64_t num_sampled = 0;
1879
1880
1881
1882
1883
1884
  for (int64_t i = 0; i < fanout; ++i) {
    const auto [rnd, j] = heap_data[i];
    if (!NonUniform || rnd < std::numeric_limits<float>::infinity()) {
      picked_data_ptr[num_sampled++] = offset + j;
    }
  }
1885
  return num_sampled;
1886
1887
}

1888
1889
}  // namespace sampling
}  // namespace graphbolt