knn.hip 35.9 KB
Newer Older
sangwzh's avatar
sangwzh committed
1
2
// !!! This is a file automatically generated by hipify!!!
#include "hip/hip_runtime.h"
3
/**
4
 *  Copyright (c) 2020 by Contributors
5
6
 * @file graph/transform/cuda/knn.cu
 * @brief k-nearest-neighbor (KNN) implementation (cuda)
7
8
 */

sangwzh's avatar
sangwzh committed
9
#include <hiprand/hiprand_kernel.h>
10
#include <dgl/array.h>
11
#include <dgl/random.h>
12
#include <dgl/runtime/device_api.h>
13

14
#include <algorithm>
sangwzh's avatar
sangwzh committed
15
#include <hipcub/hipcub.hpp>  // NOLINT
16
#include <limits>
17
#include <string>
18
#include <type_traits>
19
#include <vector>
20

21
#include "../../../array/cuda/utils.h"
22
#include "../../../runtime/cuda/cuda_common.h"
23
24
25
26
27
#include "../knn.h"

namespace dgl {
namespace transform {
namespace impl {
28
29
30
31
32
33
34
35
36
37
38
39
40
41

/**
 * @brief Given input `size`, find the smallest value
 * greater or equal to `size` that is a multiple of `align`.
 *
 * e.g. Pow2Align(17, 4) = 20, Pow2Align(17, 8) = 24
 */
template <typename Type>
static __host__ __device__ std::enable_if_t<std::is_unsigned<Type>::value, Type>
Pow2Align(Type size, Type align) {
  if (align <= 1 || size <= 0) return size;
  return ((size - 1) | (align - 1)) + 1;
}

42
/**
43
 * @brief Utility class used to avoid linker errors with extern
44
45
46
47
 *  unsized shared memory arrays with templated type
 */
template <typename Type>
struct SharedMemory {
48
  __device__ inline operator Type*() {
49
50
51
52
    extern __shared__ int __smem[];
    return reinterpret_cast<Type*>(__smem);
  }

53
  __device__ inline operator const Type*() const {
54
55
56
57
58
59
60
61
62
    extern __shared__ int __smem[];
    return reinterpret_cast<Type*>(__smem);
  }
};

// specialize for double to avoid unaligned memory
// access compile errors
template <>
struct SharedMemory<double> {
63
  __device__ inline operator double*() {
64
65
66
67
    extern __shared__ double __smem_d[];
    return reinterpret_cast<double*>(__smem_d);
  }

68
  __device__ inline operator const double*() const {
69
70
71
72
73
    extern __shared__ double __smem_d[];
    return reinterpret_cast<double*>(__smem_d);
  }
};

74
/** @brief Compute Euclidean distance between two vectors in a cuda kernel */
75
template <typename FloatType, typename IdType>
76
77
__device__ FloatType
EuclideanDist(const FloatType* vec1, const FloatType* vec2, const int64_t dim) {
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  FloatType dist = 0;
  IdType idx = 0;
  for (; idx < dim - 3; idx += 4) {
    FloatType diff0 = vec1[idx] - vec2[idx];
    FloatType diff1 = vec1[idx + 1] - vec2[idx + 1];
    FloatType diff2 = vec1[idx + 2] - vec2[idx + 2];
    FloatType diff3 = vec1[idx + 3] - vec2[idx + 3];

    dist += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
  }

  for (; idx < dim; ++idx) {
    FloatType diff = vec1[idx] - vec2[idx];
    dist += diff * diff;
  }

  return dist;
}

97
/**
98
 * @brief Compute Euclidean distance between two vectors in a cuda kernel,
99
100
101
102
 *  return positive infinite value if the intermediate distance is greater
 *  than the worst distance.
 */
template <typename FloatType, typename IdType>
103
104
105
__device__ FloatType EuclideanDistWithCheck(
    const FloatType* vec1, const FloatType* vec2, const int64_t dim,
    const FloatType worst_dist) {
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  FloatType dist = 0;
  IdType idx = 0;
  bool early_stop = false;

  for (; idx < dim - 3; idx += 4) {
    FloatType diff0 = vec1[idx] - vec2[idx];
    FloatType diff1 = vec1[idx + 1] - vec2[idx + 1];
    FloatType diff2 = vec1[idx + 2] - vec2[idx + 2];
    FloatType diff3 = vec1[idx + 3] - vec2[idx + 3];

    dist += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
    if (dist > worst_dist) {
      early_stop = true;
      idx = dim;
      break;
    }
  }

  for (; idx < dim; ++idx) {
    FloatType diff = vec1[idx] - vec2[idx];
    dist += diff * diff;
    if (dist > worst_dist) {
      early_stop = true;
      break;
    }
  }

  if (early_stop) {
    return std::numeric_limits<FloatType>::max();
  } else {
    return dist;
  }
}

template <typename FloatType, typename IdType>
__device__ void BuildHeap(IdType* indices, FloatType* dists, int size) {
  for (int i = size / 2 - 1; i >= 0; --i) {
    IdType idx = i;
    while (true) {
      IdType largest = idx;
      IdType left = idx * 2 + 1;
      IdType right = left + 1;
      if (left < size && dists[left] > dists[largest]) {
        largest = left;
      }
      if (right < size && dists[right] > dists[largest]) {
        largest = right;
      }
      if (largest != idx) {
        IdType tmp_idx = indices[largest];
        indices[largest] = indices[idx];
        indices[idx] = tmp_idx;

        FloatType tmp_dist = dists[largest];
        dists[largest] = dists[idx];
        dists[idx] = tmp_dist;
        idx = largest;
      } else {
        break;
      }
    }
  }
}

template <typename FloatType, typename IdType>
171
172
173
__device__ void HeapInsert(
    IdType* indices, FloatType* dist, IdType new_idx, FloatType new_dist,
    int size, bool check_repeat = false) {
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
  if (new_dist > dist[0]) return;

  // check if we have it
  if (check_repeat) {
    for (IdType i = 0; i < size; ++i) {
      if (indices[i] == new_idx) return;
    }
  }

  IdType left = 0, right = 0, idx = 0, largest = 0;
  dist[0] = new_dist;
  indices[0] = new_idx;
  while (true) {
    left = idx * 2 + 1;
    right = left + 1;
    if (left < size && dist[left] > dist[largest]) {
      largest = left;
    }
    if (right < size && dist[right] > dist[largest]) {
      largest = right;
    }
    if (largest != idx) {
      IdType tmp_idx = indices[idx];
      indices[idx] = indices[largest];
      indices[largest] = tmp_idx;

      FloatType tmp_dist = dist[idx];
      dist[idx] = dist[largest];
      dist[largest] = tmp_dist;

      idx = largest;
    } else {
      break;
    }
  }
}

template <typename FloatType, typename IdType>
212
213
214
__device__ bool FlaggedHeapInsert(
    IdType* indices, FloatType* dist, bool* flags, IdType new_idx,
    FloatType new_dist, bool new_flag, int size, bool check_repeat = false) {
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
  if (new_dist > dist[0]) return false;

  // check if we have it
  if (check_repeat) {
    for (IdType i = 0; i < size; ++i) {
      if (indices[i] == new_idx) return false;
    }
  }

  IdType left = 0, right = 0, idx = 0, largest = 0;
  dist[0] = new_dist;
  indices[0] = new_idx;
  flags[0] = new_flag;
  while (true) {
    left = idx * 2 + 1;
    right = left + 1;
    if (left < size && dist[left] > dist[largest]) {
      largest = left;
    }
    if (right < size && dist[right] > dist[largest]) {
      largest = right;
    }
    if (largest != idx) {
      IdType tmp_idx = indices[idx];
      indices[idx] = indices[largest];
      indices[largest] = tmp_idx;

      FloatType tmp_dist = dist[idx];
      dist[idx] = dist[largest];
      dist[largest] = tmp_dist;

      bool tmp_flag = flags[idx];
      flags[idx] = flags[largest];
      flags[largest] = tmp_flag;

      idx = largest;
    } else {
      break;
    }
  }
  return true;
}

258
/**
259
 * @brief Brute force kNN kernel. Compute distance for each pair of input points
260
 * and get the result directly (without a distance matrix).
261
262
 */
template <typename FloatType, typename IdType>
263
264
265
266
267
__global__ void BruteforceKnnKernel(
    const FloatType* data_points, const IdType* data_offsets,
    const FloatType* query_points, const IdType* query_offsets, const int k,
    FloatType* dists, IdType* query_out, IdType* data_out,
    const int64_t num_batches, const int64_t feature_size) {
268
  const IdType q_idx = blockIdx.x * blockDim.x + threadIdx.x;
269
  if (q_idx >= query_offsets[num_batches]) return;
270
271
  IdType batch_idx = 0;
  for (IdType b = 0; b < num_batches + 1; ++b) {
272
273
274
275
    if (query_offsets[b] > q_idx) {
      batch_idx = b - 1;
      break;
    }
276
  }
277
278
  const IdType data_start = data_offsets[batch_idx],
               data_end = data_offsets[batch_idx + 1];
279
280
281
282
283
284
285
286

  for (IdType k_idx = 0; k_idx < k; ++k_idx) {
    query_out[q_idx * k + k_idx] = q_idx;
    dists[q_idx * k + k_idx] = std::numeric_limits<FloatType>::max();
  }
  FloatType worst_dist = std::numeric_limits<FloatType>::max();

  for (IdType d_idx = data_start; d_idx < data_end; ++d_idx) {
287
    FloatType tmp_dist = EuclideanDistWithCheck<FloatType, IdType>(
288
289
        query_points + q_idx * feature_size, data_points + d_idx * feature_size,
        feature_size, worst_dist);
290
291

    IdType out_offset = q_idx * k;
292
293
    HeapInsert<FloatType, IdType>(
        data_out + out_offset, dists + out_offset, d_idx, tmp_dist, k);
294
    worst_dist = dists[q_idx * k];
295
296
297
  }
}

298
/**
299
 * @brief Same as BruteforceKnnKernel, but use shared memory as buffer.
300
301
302
303
304
 *  This kernel divides query points and data points into blocks. For each
 *  query block, it will make a loop over all data blocks and compute distances.
 *  This kernel is faster when the dimension of input points is not large.
 */
template <typename FloatType, typename IdType>
305
306
307
308
309
310
__global__ void BruteforceKnnShareKernel(
    const FloatType* data_points, const IdType* data_offsets,
    const FloatType* query_points, const IdType* query_offsets,
    const IdType* block_batch_id, const IdType* local_block_id, const int k,
    FloatType* dists, IdType* query_out, IdType* data_out,
    const int64_t num_batches, const int64_t feature_size) {
311
312
313
314
315
  const IdType block_idx = static_cast<IdType>(blockIdx.x);
  const IdType block_size = static_cast<IdType>(blockDim.x);
  const IdType batch_idx = block_batch_id[block_idx];
  const IdType local_bid = local_block_id[block_idx];
  const IdType query_start = query_offsets[batch_idx] + block_size * local_bid;
316
317
  const IdType query_end =
      min(query_start + block_size, query_offsets[batch_idx + 1]);
318
  if (query_start >= query_end) return;
319
320
321
322
323
324
325
326
  const IdType query_idx = query_start + threadIdx.x;
  const IdType data_start = data_offsets[batch_idx];
  const IdType data_end = data_offsets[batch_idx + 1];

  // shared memory: points in block + distance buffer + result buffer
  FloatType* data_buff = SharedMemory<FloatType>();
  FloatType* query_buff = data_buff + block_size * feature_size;
  FloatType* dist_buff = query_buff + block_size * feature_size;
327
328
  IdType* res_buff = reinterpret_cast<IdType*>(Pow2Align<uint64_t>(
      reinterpret_cast<uint64_t>(dist_buff + block_size * k), sizeof(IdType)));
329
330
331
332
  FloatType worst_dist = std::numeric_limits<FloatType>::max();

  // initialize dist buff with inf value
  for (auto i = 0; i < k; ++i) {
333
334
    dist_buff[threadIdx.x + i * block_size] =
        std::numeric_limits<FloatType>::max();
335
336
337
  }

  // load query data to shared memory
338
339
  // TODO(tianqi): could be better here to exploit coalesce global memory
  // access.
340
341
342
  if (query_idx < query_end) {
    for (auto i = 0; i < feature_size; ++i) {
      // to avoid bank conflict, we use transpose here
343
344
      query_buff[threadIdx.x + i * block_size] =
          query_points[query_idx * feature_size + i];
345
346
347
348
    }
  }

  // perform computation on each tile
349
350
  for (auto tile_start = data_start; tile_start < data_end;
       tile_start += block_size) {
351
352
353
354
    // each thread load one data point into the shared memory
    IdType load_idx = tile_start + threadIdx.x;
    if (load_idx < data_end) {
      for (auto i = 0; i < feature_size; ++i) {
355
356
        data_buff[threadIdx.x * feature_size + i] =
            data_points[load_idx * feature_size + i];
357
358
359
360
361
362
363
364
365
366
367
368
369
      }
    }
    __syncthreads();

    // compute distance for one tile
    IdType true_block_size = min(data_end - tile_start, block_size);
    if (query_idx < query_end) {
      for (IdType d_idx = 0; d_idx < true_block_size; ++d_idx) {
        FloatType tmp_dist = 0;
        bool early_stop = false;
        IdType dim_idx = 0;

        for (; dim_idx < feature_size - 3; dim_idx += 4) {
370
371
372
373
374
375
376
377
378
379
380
381
382
383
          FloatType diff0 = query_buff[threadIdx.x + block_size * (dim_idx)] -
                            data_buff[d_idx * feature_size + dim_idx];
          FloatType diff1 =
              query_buff[threadIdx.x + block_size * (dim_idx + 1)] -
              data_buff[d_idx * feature_size + dim_idx + 1];
          FloatType diff2 =
              query_buff[threadIdx.x + block_size * (dim_idx + 2)] -
              data_buff[d_idx * feature_size + dim_idx + 2];
          FloatType diff3 =
              query_buff[threadIdx.x + block_size * (dim_idx + 3)] -
              data_buff[d_idx * feature_size + dim_idx + 3];

          tmp_dist +=
              diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
384
385
386
387
388
389
390
391
392

          if (tmp_dist > worst_dist) {
            early_stop = true;
            dim_idx = feature_size;
            break;
          }
        }

        for (; dim_idx < feature_size; ++dim_idx) {
393
394
395
          const FloatType diff =
              query_buff[threadIdx.x + dim_idx * block_size] -
              data_buff[d_idx * feature_size + dim_idx];
396
397
398
399
400
401
402
403
404
405
          tmp_dist += diff * diff;

          if (tmp_dist > worst_dist) {
            early_stop = true;
            break;
          }
        }

        if (early_stop) continue;

406
        HeapInsert<FloatType, IdType>(
407
408
            res_buff + threadIdx.x * k, dist_buff + threadIdx.x * k,
            d_idx + tile_start, tmp_dist, k);
409
        worst_dist = dist_buff[threadIdx.x * k];
410
411
      }
    }
412
    __syncthreads();
413
414
415
416
417
418
419
420
421
422
423
424
  }

  // copy result to global memory
  if (query_idx < query_end) {
    for (auto i = 0; i < k; ++i) {
      dists[query_idx * k + i] = dist_buff[threadIdx.x * k + i];
      data_out[query_idx * k + i] = res_buff[threadIdx.x * k + i];
      query_out[query_idx * k + i] = query_idx;
    }
  }
}

425
/** @brief determine the number of blocks for each segment */
426
template <typename IdType>
427
428
429
__global__ void GetNumBlockPerSegment(
    const IdType* offsets, IdType* out, const int64_t batch_size,
    const int64_t block_size) {
430
431
432
433
434
435
  const IdType idx = blockIdx.x * blockDim.x + threadIdx.x;
  if (idx < batch_size) {
    out[idx] = (offsets[idx + 1] - offsets[idx] - 1) / block_size + 1;
  }
}

436
/** @brief Get the batch index and local index in segment for each block */
437
template <typename IdType>
438
439
440
__global__ void GetBlockInfo(
    const IdType* num_block_prefixsum, IdType* block_batch_id,
    IdType* local_block_id, size_t batch_size, size_t num_blocks) {
441
442
443
444
445
446
447
448
449
450
451
452
453
  const IdType idx = blockIdx.x * blockDim.x + threadIdx.x;
  IdType i = 0;

  if (idx < num_blocks) {
    for (; i < batch_size; ++i) {
      if (num_block_prefixsum[i] > idx) break;
    }
    i--;
    block_batch_id[idx] = i;
    local_block_id[idx] = idx - num_block_prefixsum[i];
  }
}

454
/**
455
 * @brief Brute force kNN. Compute distance for each pair of input points and
456
 * get the result directly (without a distance matrix).
457
 *
458
459
460
461
462
463
464
465
 * @tparam FloatType The type of input points.
 * @tparam IdType The type of id.
 * @param data_points NDArray of dataset points.
 * @param data_offsets offsets of point index in data points.
 * @param query_points NDArray of query points
 * @param query_offsets offsets of point index in query points.
 * @param k the number of nearest points
 * @param result output array
466
467
 */
template <typename FloatType, typename IdType>
468
469
470
471
void BruteForceKNNCuda(
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result) {
sangwzh's avatar
sangwzh committed
472
  hipStream_t stream = runtime::getCurrentHIPStreamMasqueradingAsCUDA();
473
474
475
476
477
478
479
480
481
482
483
484
  const auto& ctx = data_points->ctx;
  auto device = runtime::DeviceAPI::Get(ctx);
  const int64_t batch_size = data_offsets->shape[0] - 1;
  const int64_t feature_size = data_points->shape[1];
  const IdType* data_offsets_data = data_offsets.Ptr<IdType>();
  const IdType* query_offsets_data = query_offsets.Ptr<IdType>();
  const FloatType* data_points_data = data_points.Ptr<FloatType>();
  const FloatType* query_points_data = query_points.Ptr<FloatType>();
  IdType* query_out = result.Ptr<IdType>();
  IdType* data_out = query_out + k * query_points->shape[0];

  FloatType* dists = static_cast<FloatType*>(device->AllocWorkspace(
485
      ctx, k * query_points->shape[0] * sizeof(FloatType)));
486
487
488

  const int64_t block_size = cuda::FindNumThreads(query_points->shape[0]);
  const int64_t num_blocks = (query_points->shape[0] - 1) / block_size + 1;
489
490
491
492
  CUDA_KERNEL_CALL(
      BruteforceKnnKernel, num_blocks, block_size, 0, stream, data_points_data,
      data_offsets_data, query_points_data, query_offsets_data, k, dists,
      query_out, data_out, batch_size, feature_size);
493
494
495
496

  device->FreeWorkspace(ctx, dists);
}

497
/**
498
 * @brief Brute force kNN with shared memory.
499
500
501
502
 *  This function divides query points and data points into blocks. For each
 *  query block, it will make a loop over all data blocks and compute distances.
 *  It will be faster when the dimension of input points is not large.
 *
503
504
505
506
507
508
509
510
 * @tparam FloatType The type of input points.
 * @tparam IdType The type of id.
 * @param data_points NDArray of dataset points.
 * @param data_offsets offsets of point index in data points.
 * @param query_points NDArray of query points
 * @param query_offsets offsets of point index in query points.
 * @param k the number of nearest points
 * @param result output array
511
512
 */
template <typename FloatType, typename IdType>
513
514
515
516
void BruteForceKNNSharedCuda(
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result) {
sangwzh's avatar
sangwzh committed
517
  hipStream_t stream = runtime::getCurrentHIPStreamMasqueradingAsCUDA();
518
519
520
521
522
523
524
525
526
527
  const auto& ctx = data_points->ctx;
  auto device = runtime::DeviceAPI::Get(ctx);
  const int64_t batch_size = data_offsets->shape[0] - 1;
  const int64_t feature_size = data_points->shape[1];
  const IdType* data_offsets_data = data_offsets.Ptr<IdType>();
  const IdType* query_offsets_data = query_offsets.Ptr<IdType>();
  const FloatType* data_points_data = data_points.Ptr<FloatType>();
  const FloatType* query_points_data = query_points.Ptr<FloatType>();
  IdType* query_out = result.Ptr<IdType>();
  IdType* data_out = query_out + k * query_points->shape[0];
528
  constexpr size_t smem_align = std::max(sizeof(IdType), sizeof(FloatType));
529
530
531
532

  // get max shared memory per block in bytes
  // determine block size according to this value
  int max_sharedmem_per_block = 0;
sangwzh's avatar
sangwzh committed
533
534
  CUDA_CALL(hipDeviceGetAttribute(
      &max_sharedmem_per_block, hipDeviceAttributeMaxSharedMemoryPerBlock,
535
      ctx.device_id));
536
537
538
539
  const int64_t single_shared_mem = static_cast<int64_t>(Pow2Align<size_t>(
      (k + 2 * feature_size) * sizeof(FloatType) + k * sizeof(IdType),
      smem_align));

540
541
  const int64_t block_size =
      cuda::FindNumThreads(max_sharedmem_per_block / single_shared_mem);
542
543
544
545

  // Determine the number of blocks. We first get the number of blocks for each
  // segment. Then we get the block id offset via prefix sum.
  IdType* num_block_per_segment = static_cast<IdType*>(
546
      device->AllocWorkspace(ctx, batch_size * sizeof(IdType)));
547
  IdType* num_block_prefixsum = static_cast<IdType*>(
548
      device->AllocWorkspace(ctx, batch_size * sizeof(IdType)));
549

550
  // block size for GetNumBlockPerSegment computation
551
552
  int64_t temp_block_size = cuda::FindNumThreads(batch_size);
  int64_t temp_num_blocks = (batch_size - 1) / temp_block_size + 1;
553
554
555
  CUDA_KERNEL_CALL(
      GetNumBlockPerSegment, temp_num_blocks, temp_block_size, 0, stream,
      query_offsets_data, num_block_per_segment, batch_size, block_size);
556
  size_t prefix_temp_size = 0;
sangwzh's avatar
sangwzh committed
557
  CUDA_CALL(hipcub::DeviceScan::ExclusiveSum(
558
559
      nullptr, prefix_temp_size, num_block_per_segment, num_block_prefixsum,
      batch_size, stream));
560
  void* prefix_temp = device->AllocWorkspace(ctx, prefix_temp_size);
sangwzh's avatar
sangwzh committed
561
  CUDA_CALL(hipcub::DeviceScan::ExclusiveSum(
562
563
      prefix_temp, prefix_temp_size, num_block_per_segment, num_block_prefixsum,
      batch_size, stream));
564
565
  device->FreeWorkspace(ctx, prefix_temp);

566
  // wait for results
sangwzh's avatar
sangwzh committed
567
  CUDA_CALL(hipStreamSynchronize(stream));
568

569
570
  int64_t num_blocks = 0, final_elem = 0,
          copyoffset = (batch_size - 1) * sizeof(IdType);
571
  device->CopyDataFromTo(
572
573
      num_block_prefixsum, copyoffset, &num_blocks, 0, sizeof(IdType), ctx,
      DGLContext{kDGLCPU, 0}, query_offsets->dtype);
574
  device->CopyDataFromTo(
575
576
      num_block_per_segment, copyoffset, &final_elem, 0, sizeof(IdType), ctx,
      DGLContext{kDGLCPU, 0}, query_offsets->dtype);
577
578
579
580
581
582
  num_blocks += final_elem;
  device->FreeWorkspace(ctx, num_block_per_segment);

  // get batch id and local id in segment
  temp_block_size = cuda::FindNumThreads(num_blocks);
  temp_num_blocks = (num_blocks - 1) / temp_block_size + 1;
583
584
585
586
  IdType* block_batch_id = static_cast<IdType*>(
      device->AllocWorkspace(ctx, num_blocks * sizeof(IdType)));
  IdType* local_block_id = static_cast<IdType*>(
      device->AllocWorkspace(ctx, num_blocks * sizeof(IdType)));
587
  CUDA_KERNEL_CALL(
588
589
590
      GetBlockInfo, temp_num_blocks, temp_block_size, 0, stream,
      num_block_prefixsum, block_batch_id, local_block_id, batch_size,
      num_blocks);
591
592

  FloatType* dists = static_cast<FloatType*>(device->AllocWorkspace(
593
594
595
596
597
598
      ctx, k * query_points->shape[0] * sizeof(FloatType)));
  CUDA_KERNEL_CALL(
      BruteforceKnnShareKernel, num_blocks, block_size,
      single_shared_mem * block_size, stream, data_points_data,
      data_offsets_data, query_points_data, query_offsets_data, block_batch_id,
      local_block_id, k, dists, query_out, data_out, batch_size, feature_size);
599

600
  device->FreeWorkspace(ctx, num_block_prefixsum);
601
602
603
604
  device->FreeWorkspace(ctx, dists);
  device->FreeWorkspace(ctx, local_block_id);
  device->FreeWorkspace(ctx, block_batch_id);
}
605

606
/** @brief Setup rng state for nn-descent */
607
__global__ void SetupRngKernel(
sangwzh's avatar
sangwzh committed
608
    hiprandState_t* states, const uint64_t seed, const size_t n) {
609
610
  size_t id = blockIdx.x * blockDim.x + threadIdx.x;
  if (id < n) {
sangwzh's avatar
sangwzh committed
611
    hiprand_init(seed, id, 0, states + id);
612
613
614
  }
}

615
/**
616
 * @brief Randomly initialize neighbors (sampling without replacement)
617
618
619
 * for each nodes
 */
template <typename FloatType, typename IdType>
620
621
622
623
__global__ void RandomInitNeighborsKernel(
    const FloatType* points, const IdType* offsets, IdType* central_nodes,
    IdType* neighbors, FloatType* dists, bool* flags, const int k,
    const int64_t feature_size, const int64_t batch_size, const uint64_t seed) {
624
625
626
  const IdType point_idx = blockIdx.x * blockDim.x + threadIdx.x;
  IdType batch_idx = 0;
  if (point_idx >= offsets[batch_size]) return;
sangwzh's avatar
sangwzh committed
627
628
  hiprandState_t state;
  hiprand_init(seed, point_idx, 0, &state);
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

  // find the segment location in the input batch
  for (IdType b = 0; b < batch_size + 1; ++b) {
    if (offsets[b] > point_idx) {
      batch_idx = b - 1;
      break;
    }
  }

  const IdType segment_size = offsets[batch_idx + 1] - offsets[batch_idx];
  IdType* current_neighbors = neighbors + point_idx * k;
  IdType* current_central_nodes = central_nodes + point_idx * k;
  bool* current_flags = flags + point_idx * k;
  FloatType* current_dists = dists + point_idx * k;
  IdType segment_start = offsets[batch_idx];

  // reservoir sampling
  for (IdType i = 0; i < k; ++i) {
    current_neighbors[i] = i + segment_start;
    current_central_nodes[i] = point_idx;
  }
  for (IdType i = k; i < segment_size; ++i) {
sangwzh's avatar
sangwzh committed
651
    const IdType j = static_cast<IdType>(hiprand(&state) % (i + 1));
652
653
654
655
656
657
658
    if (j < k) current_neighbors[j] = i + segment_start;
  }

  // compute distances and set flags
  for (IdType i = 0; i < k; ++i) {
    current_flags[i] = true;
    current_dists[i] = EuclideanDist<FloatType, IdType>(
659
660
        points + point_idx * feature_size,
        points + current_neighbors[i] * feature_size, feature_size);
661
662
663
664
665
666
  }

  // build heap
  BuildHeap<FloatType, IdType>(neighbors + point_idx * k, current_dists, k);
}

667
/**
668
 * @brief Randomly select candidates from current knn and reverse-knn graph for
669
670
 *        nn-descent.
 */
671
template <typename IdType>
672
673
674
675
__global__ void FindCandidatesKernel(
    const IdType* offsets, IdType* new_candidates, IdType* old_candidates,
    IdType* neighbors, bool* flags, const uint64_t seed,
    const int64_t batch_size, const int num_candidates, const int k) {
676
677
678
  const IdType point_idx = blockIdx.x * blockDim.x + threadIdx.x;
  IdType batch_idx = 0;
  if (point_idx >= offsets[batch_size]) return;
sangwzh's avatar
sangwzh committed
679
680
  hiprandState_t state;
  hiprand_init(seed, point_idx, 0, &state);
681
682
683
684
685
686
687
688
689

  // find the segment location in the input batch
  for (IdType b = 0; b < batch_size + 1; ++b) {
    if (offsets[b] > point_idx) {
      batch_idx = b - 1;
      break;
    }
  }

690
691
  IdType segment_start = offsets[batch_idx],
         segment_end = offsets[batch_idx + 1];
692
693
694
695
  IdType* current_neighbors = neighbors + point_idx * k;
  bool* current_flags = flags + point_idx * k;

  // reset candidates
696
697
698
699
  IdType* new_candidates_ptr =
      new_candidates + point_idx * (num_candidates + 1);
  IdType* old_candidates_ptr =
      old_candidates + point_idx * (num_candidates + 1);
700
701
702
703
704
705
706
  new_candidates_ptr[0] = 0;
  old_candidates_ptr[0] = 0;

  // select candidates from current knn graph
  // here we use candidate[0] for reservoir sampling temporarily
  for (IdType i = 0; i < k; ++i) {
    IdType candidate = current_neighbors[i];
707
708
    IdType* candidate_array =
        current_flags[i] ? new_candidates_ptr : old_candidates_ptr;
709
710
711
712
713
714
715
    IdType curr_num = candidate_array[0];
    IdType* candidate_data = candidate_array + 1;

    // reservoir sampling
    if (curr_num < num_candidates) {
      candidate_data[curr_num] = candidate;
    } else {
sangwzh's avatar
sangwzh committed
716
      IdType pos = static_cast<IdType>(hiprand(&state) % (curr_num + 1));
717
718
719
720
721
722
723
724
725
726
727
      if (pos < num_candidates) candidate_data[pos] = candidate;
    }
    ++candidate_array[0];
  }

  // select candidates from current reverse knn graph
  // here we use candidate[0] for reservoir sampling temporarily
  IdType index_start = segment_start * k, index_end = segment_end * k;
  for (IdType i = index_start; i < index_end; ++i) {
    if (neighbors[i] == point_idx) {
      IdType reverse_candidate = (i - index_start) / k + segment_start;
728
729
      IdType* candidate_array =
          flags[i] ? new_candidates_ptr : old_candidates_ptr;
730
731
732
733
734
735
736
      IdType curr_num = candidate_array[0];
      IdType* candidate_data = candidate_array + 1;

      // reservoir sampling
      if (curr_num < num_candidates) {
        candidate_data[curr_num] = reverse_candidate;
      } else {
sangwzh's avatar
sangwzh committed
737
        IdType pos = static_cast<IdType>(hiprand(&state) % (curr_num + 1));
738
739
740
741
742
743
744
        if (pos < num_candidates) candidate_data[pos] = reverse_candidate;
      }
      ++candidate_array[0];
    }
  }

  // set candidate[0] back to length
745
746
747
748
  if (new_candidates_ptr[0] > num_candidates)
    new_candidates_ptr[0] = num_candidates;
  if (old_candidates_ptr[0] > num_candidates)
    old_candidates_ptr[0] = num_candidates;
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765

  // mark new_candidates as old
  IdType num_new_candidates = new_candidates_ptr[0];
  for (IdType i = 0; i < k; ++i) {
    IdType neighbor_idx = current_neighbors[i];

    if (current_flags[i]) {
      for (IdType j = 1; j < num_new_candidates + 1; ++j) {
        if (new_candidates_ptr[j] == neighbor_idx) {
          current_flags[i] = false;
          break;
        }
      }
    }
  }
}

766
/** @brief Update knn graph according to selected candidates for nn-descent */
767
template <typename FloatType, typename IdType>
768
769
770
771
772
__global__ void UpdateNeighborsKernel(
    const FloatType* points, const IdType* offsets, IdType* neighbors,
    IdType* new_candidates, IdType* old_candidates, FloatType* distances,
    bool* flags, IdType* num_updates, const int64_t batch_size,
    const int num_candidates, const int k, const int64_t feature_size) {
773
774
775
776
777
  const IdType point_idx = blockIdx.x * blockDim.x + threadIdx.x;
  if (point_idx >= offsets[batch_size]) return;
  IdType* current_neighbors = neighbors + point_idx * k;
  bool* current_flags = flags + point_idx * k;
  FloatType* current_dists = distances + point_idx * k;
778
779
780
781
  IdType* new_candidates_ptr =
      new_candidates + point_idx * (num_candidates + 1);
  IdType* old_candidates_ptr =
      old_candidates + point_idx * (num_candidates + 1);
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
  IdType num_new_candidates = new_candidates_ptr[0];
  IdType num_old_candidates = old_candidates_ptr[0];
  IdType current_num_updates = 0;

  // process new candidates
  for (IdType i = 1; i <= num_new_candidates; ++i) {
    IdType new_c = new_candidates_ptr[i];

    // new/old candidates of the current new candidate
    IdType* twohop_new_ptr = new_candidates + new_c * (num_candidates + 1);
    IdType* twohop_old_ptr = old_candidates + new_c * (num_candidates + 1);
    IdType num_twohop_new = twohop_new_ptr[0];
    IdType num_twohop_old = twohop_old_ptr[0];
    FloatType worst_dist = current_dists[0];

    // new - new
    for (IdType j = 1; j <= num_twohop_new; ++j) {
      IdType twohop_new_c = twohop_new_ptr[j];
      FloatType new_dist = EuclideanDistWithCheck<FloatType, IdType>(
801
802
          points + point_idx * feature_size,
          points + twohop_new_c * feature_size, feature_size, worst_dist);
803
804

      if (FlaggedHeapInsert<FloatType, IdType>(
805
806
807
808
              current_neighbors, current_dists, current_flags, twohop_new_c,
              new_dist, true, k, true)) {
        ++current_num_updates;
        worst_dist = current_dists[0];
809
810
811
812
813
814
815
      }
    }

    // new - old
    for (IdType j = 1; j <= num_twohop_old; ++j) {
      IdType twohop_old_c = twohop_old_ptr[j];
      FloatType new_dist = EuclideanDistWithCheck<FloatType, IdType>(
816
817
          points + point_idx * feature_size,
          points + twohop_old_c * feature_size, feature_size, worst_dist);
818
819

      if (FlaggedHeapInsert<FloatType, IdType>(
820
821
822
823
              current_neighbors, current_dists, current_flags, twohop_old_c,
              new_dist, true, k, true)) {
        ++current_num_updates;
        worst_dist = current_dists[0];
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
      }
    }
  }

  // process old candidates
  for (IdType i = 1; i <= num_old_candidates; ++i) {
    IdType old_c = old_candidates_ptr[i];

    // new candidates of the current old candidate
    IdType* twohop_new_ptr = new_candidates + old_c * (num_candidates + 1);
    IdType num_twohop_new = twohop_new_ptr[0];
    FloatType worst_dist = current_dists[0];

    // old - new
    for (IdType j = 1; j <= num_twohop_new; ++j) {
      IdType twohop_new_c = twohop_new_ptr[j];
      FloatType new_dist = EuclideanDistWithCheck<FloatType, IdType>(
841
842
          points + point_idx * feature_size,
          points + twohop_new_c * feature_size, feature_size, worst_dist);
843
844

      if (FlaggedHeapInsert<FloatType, IdType>(
845
846
847
848
              current_neighbors, current_dists, current_flags, twohop_new_c,
              new_dist, true, k, true)) {
        ++current_num_updates;
        worst_dist = current_dists[0];
849
850
851
852
853
854
855
      }
    }
  }

  num_updates[point_idx] = current_num_updates;
}

856
857
}  // namespace impl

858
template <DGLDeviceType XPU, typename FloatType, typename IdType>
859
860
861
862
void KNN(
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result, const std::string& algorithm) {
863
864
  if (algorithm == std::string("bruteforce")) {
    impl::BruteForceKNNCuda<FloatType, IdType>(
865
        data_points, data_offsets, query_points, query_offsets, k, result);
866
867
  } else if (algorithm == std::string("bruteforce-sharemem")) {
    impl::BruteForceKNNSharedCuda<FloatType, IdType>(
868
        data_points, data_offsets, query_points, query_offsets, k, result);
869
870
871
872
873
  } else {
    LOG(FATAL) << "Algorithm " << algorithm << " is not supported on CUDA.";
  }
}

874
template <DGLDeviceType XPU, typename FloatType, typename IdType>
875
876
877
void NNDescent(
    const NDArray& points, const IdArray& offsets, IdArray result, const int k,
    const int num_iters, const int num_candidates, const double delta) {
sangwzh's avatar
sangwzh committed
878
  hipStream_t stream = runtime::getCurrentHIPStreamMasqueradingAsCUDA();
879
880
881
882
883
884
885
886
887
888
889
890
  const auto& ctx = points->ctx;
  auto device = runtime::DeviceAPI::Get(ctx);
  const int64_t num_nodes = points->shape[0];
  const int64_t feature_size = points->shape[1];
  const int64_t batch_size = offsets->shape[0] - 1;
  const IdType* offsets_data = offsets.Ptr<IdType>();
  const FloatType* points_data = points.Ptr<FloatType>();

  IdType* central_nodes = result.Ptr<IdType>();
  IdType* neighbors = central_nodes + k * num_nodes;
  uint64_t seed;
  int warp_size = 0;
891
  CUDA_CALL(
sangwzh's avatar
sangwzh committed
892
      hipDeviceGetAttribute(&warp_size, hipDeviceAttributeWarpSize, ctx.device_id));
893
894
  // We don't need large block sizes, since there's not much inter-thread
  // communication
895
896
897
898
899
  int64_t block_size = warp_size;
  int64_t num_blocks = (num_nodes - 1) / block_size + 1;

  // allocate space for candidates, distances and flags
  // we use the first element in candidate array to represent length
900
901
902
903
  IdType* new_candidates = static_cast<IdType*>(device->AllocWorkspace(
      ctx, num_nodes * (num_candidates + 1) * sizeof(IdType)));
  IdType* old_candidates = static_cast<IdType*>(device->AllocWorkspace(
      ctx, num_nodes * (num_candidates + 1) * sizeof(IdType)));
904
  IdType* num_updates = static_cast<IdType*>(
905
      device->AllocWorkspace(ctx, num_nodes * sizeof(IdType)));
906
  FloatType* distances = static_cast<FloatType*>(
907
      device->AllocWorkspace(ctx, num_nodes * k * sizeof(IdType)));
908
  bool* flags = static_cast<bool*>(
909
      device->AllocWorkspace(ctx, num_nodes * k * sizeof(IdType)));
910
911
912

  size_t sum_temp_size = 0;
  IdType total_num_updates = 0;
913
914
  IdType* total_num_updates_d =
      static_cast<IdType*>(device->AllocWorkspace(ctx, sizeof(IdType)));
915

sangwzh's avatar
sangwzh committed
916
  CUDA_CALL(hipcub::DeviceReduce::Sum(
917
918
919
920
      nullptr, sum_temp_size, num_updates, total_num_updates_d, num_nodes,
      stream));
  IdType* sum_temp_storage =
      static_cast<IdType*>(device->AllocWorkspace(ctx, sum_temp_size));
921
922
923

  // random initialize neighbors
  seed = RandomEngine::ThreadLocal()->RandInt<uint64_t>(
924
      std::numeric_limits<uint64_t>::max());
925
  CUDA_KERNEL_CALL(
926
927
928
      impl::RandomInitNeighborsKernel, num_blocks, block_size, 0, stream,
      points_data, offsets_data, central_nodes, neighbors, distances, flags, k,
      feature_size, batch_size, seed);
929
930
931
932

  for (int i = 0; i < num_iters; ++i) {
    // select candidates
    seed = RandomEngine::ThreadLocal()->RandInt<uint64_t>(
933
        std::numeric_limits<uint64_t>::max());
934
    CUDA_KERNEL_CALL(
935
936
937
        impl::FindCandidatesKernel, num_blocks, block_size, 0, stream,
        offsets_data, new_candidates, old_candidates, neighbors, flags, seed,
        batch_size, num_candidates, k);
938
939
940

    // update
    CUDA_KERNEL_CALL(
941
942
943
944
        impl::UpdateNeighborsKernel, num_blocks, block_size, 0, stream,
        points_data, offsets_data, neighbors, new_candidates, old_candidates,
        distances, flags, num_updates, batch_size, num_candidates, k,
        feature_size);
945
946

    total_num_updates = 0;
sangwzh's avatar
sangwzh committed
947
    CUDA_CALL(hipcub::DeviceReduce::Sum(
948
949
        sum_temp_storage, sum_temp_size, num_updates, total_num_updates_d,
        num_nodes, stream));
950
    device->CopyDataFromTo(
951
952
        total_num_updates_d, 0, &total_num_updates, 0, sizeof(IdType), ctx,
        DGLContext{kDGLCPU, 0}, offsets->dtype);
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967

    if (total_num_updates <= static_cast<IdType>(delta * k * num_nodes)) {
      break;
    }
  }

  device->FreeWorkspace(ctx, new_candidates);
  device->FreeWorkspace(ctx, old_candidates);
  device->FreeWorkspace(ctx, num_updates);
  device->FreeWorkspace(ctx, distances);
  device->FreeWorkspace(ctx, flags);
  device->FreeWorkspace(ctx, total_num_updates_d);
  device->FreeWorkspace(ctx, sum_temp_storage);
}

968
template void KNN<kDGLCUDA, float, int32_t>(
969
970
971
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result, const std::string& algorithm);
972
template void KNN<kDGLCUDA, float, int64_t>(
973
974
975
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result, const std::string& algorithm);
976
template void KNN<kDGLCUDA, double, int32_t>(
977
978
979
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result, const std::string& algorithm);
980
template void KNN<kDGLCUDA, double, int64_t>(
981
982
983
    const NDArray& data_points, const IdArray& data_offsets,
    const NDArray& query_points, const IdArray& query_offsets, const int k,
    IdArray result, const std::string& algorithm);
984

985
template void NNDescent<kDGLCUDA, float, int32_t>(
986
987
    const NDArray& points, const IdArray& offsets, IdArray result, const int k,
    const int num_iters, const int num_candidates, const double delta);
988
template void NNDescent<kDGLCUDA, float, int64_t>(
989
990
    const NDArray& points, const IdArray& offsets, IdArray result, const int k,
    const int num_iters, const int num_candidates, const double delta);
991
template void NNDescent<kDGLCUDA, double, int32_t>(
992
993
    const NDArray& points, const IdArray& offsets, IdArray result, const int k,
    const int num_iters, const int num_candidates, const double delta);
994
template void NNDescent<kDGLCUDA, double, int64_t>(
995
996
    const NDArray& points, const IdArray& offsets, IdArray result, const int k,
    const int num_iters, const int num_candidates, const double delta);
997

998
999
}  // namespace transform
}  // namespace dgl