forked from rapidsai/cuvs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnn_descent.cuh
1554 lines (1387 loc) · 58.3 KB
/
nn_descent.cuh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
171
172
173
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
212
213
214
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
563
564
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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2023-2025, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "ann_utils.cuh"
#include "cagra/device_common.hpp"
#include <cuvs/distance/distance.hpp>
#include <cuvs/neighbors/nn_descent.hpp>
#include <raft/core/device_mdarray.hpp>
#include <raft/core/device_mdspan.hpp>
#include <raft/core/error.hpp>
#include <raft/core/host_mdarray.hpp>
#include <raft/core/mdspan.hpp>
#include <raft/core/operators.hpp>
#include <raft/core/pinned_mdarray.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/core/resources.hpp>
#include <raft/matrix/init.cuh>
#include <raft/matrix/slice.cuh>
#include <raft/util/arch.cuh> // raft::util::arch::SM_*
#include <raft/util/cuda_dev_essentials.cuh>
#include <raft/util/cuda_rt_essentials.hpp>
#include <raft/util/cudart_utils.hpp>
#include <raft/util/pow2_utils.cuh>
#include <rmm/device_uvector.hpp>
#include <cuda_runtime.h>
#include <mma.h>
#include <omp.h>
#include <limits>
#include <optional>
#include <queue>
#include <random>
namespace cuvs::neighbors::nn_descent::detail {
using DistData_t = float;
constexpr int DEGREE_ON_DEVICE{32};
constexpr int SEGMENT_SIZE{32};
constexpr int counter_interval{100};
template <typename Index_t>
struct InternalID_t;
// InternalID_t uses 1 bit for marking (new or old).
template <>
class InternalID_t<int> {
private:
using Index_t = int;
Index_t id_{std::numeric_limits<Index_t>::max()};
public:
__host__ __device__ bool is_new() const { return id_ >= 0; }
__host__ __device__ Index_t& id_with_flag() { return id_; }
__host__ __device__ Index_t id() const
{
if (is_new()) return id_;
return -id_ - 1;
}
__host__ __device__ void mark_old()
{
if (id_ >= 0) id_ = -id_ - 1;
}
__host__ __device__ bool operator==(const InternalID_t<int>& other) const
{
return id() == other.id();
}
};
template <typename Index_t>
struct ResultItem;
template <>
class ResultItem<int> {
private:
using Index_t = int;
Index_t id_;
DistData_t dist_;
public:
__host__ __device__ ResultItem()
: id_(std::numeric_limits<Index_t>::max()), dist_(std::numeric_limits<DistData_t>::max()){};
__host__ __device__ ResultItem(const Index_t id_with_flag, const DistData_t dist)
: id_(id_with_flag), dist_(dist){};
__host__ __device__ bool is_new() const { return id_ >= 0; }
__host__ __device__ Index_t& id_with_flag() { return id_; }
__host__ __device__ Index_t id() const
{
if (is_new()) return id_;
return -id_ - 1;
}
__host__ __device__ DistData_t& dist() { return dist_; }
__host__ __device__ void mark_old()
{
if (id_ >= 0) id_ = -id_ - 1;
}
__host__ __device__ bool operator<(const ResultItem<Index_t>& other) const
{
if (dist_ == other.dist_) return id() < other.id();
return dist_ < other.dist_;
}
__host__ __device__ bool operator==(const ResultItem<Index_t>& other) const
{
return id() == other.id();
}
__host__ __device__ bool operator>=(const ResultItem<Index_t>& other) const
{
return !(*this < other);
}
__host__ __device__ bool operator<=(const ResultItem<Index_t>& other) const
{
return (*this == other) || (*this < other);
}
__host__ __device__ bool operator>(const ResultItem<Index_t>& other) const
{
return !(*this <= other);
}
__host__ __device__ bool operator!=(const ResultItem<Index_t>& other) const
{
return !(*this == other);
}
};
using align32 = raft::Pow2<32>;
template <typename T>
int get_batch_size(const int it_now, const T nrow, const int batch_size)
{
int it_total = raft::ceildiv(nrow, batch_size);
return (it_now == it_total - 1) ? nrow - it_now * batch_size : batch_size;
}
// for avoiding bank conflict
template <typename T>
constexpr __host__ __device__ __forceinline__ int skew_dim(int ndim)
{
// all "4"s are for alignment
if constexpr (std::is_same<T, float>::value) {
ndim = raft::ceildiv(ndim, 4) * 4;
return ndim + (ndim % 32 == 0) * 4;
}
}
template <typename T>
__device__ __forceinline__ ResultItem<T> xor_swap(ResultItem<T> x, int mask, int dir)
{
ResultItem<T> y;
y.dist() = __shfl_xor_sync(raft::warp_full_mask(), x.dist(), mask, raft::warp_size());
y.id_with_flag() =
__shfl_xor_sync(raft::warp_full_mask(), x.id_with_flag(), mask, raft::warp_size());
return x < y == dir ? y : x;
}
__device__ __forceinline__ int xor_swap(int x, int mask, int dir)
{
int y = __shfl_xor_sync(raft::warp_full_mask(), x, mask, raft::warp_size());
return x < y == dir ? y : x;
}
// TODO: Move to RAFT utils https://github.com/rapidsai/raft/issues/1827
__device__ __forceinline__ uint bfe(uint lane_id, uint pos)
{
uint res;
asm("bfe.u32 %0,%1,%2,%3;" : "=r"(res) : "r"(lane_id), "r"(pos), "r"(1));
return res;
}
template <typename T>
__device__ __forceinline__ void warp_bitonic_sort(T* element_ptr, const int lane_id)
{
static_assert(raft::warp_size() == 32);
auto& element = *element_ptr;
element = xor_swap(element, 0x01, bfe(lane_id, 1) ^ bfe(lane_id, 0));
element = xor_swap(element, 0x02, bfe(lane_id, 2) ^ bfe(lane_id, 1));
element = xor_swap(element, 0x01, bfe(lane_id, 2) ^ bfe(lane_id, 0));
element = xor_swap(element, 0x04, bfe(lane_id, 3) ^ bfe(lane_id, 2));
element = xor_swap(element, 0x02, bfe(lane_id, 3) ^ bfe(lane_id, 1));
element = xor_swap(element, 0x01, bfe(lane_id, 3) ^ bfe(lane_id, 0));
element = xor_swap(element, 0x08, bfe(lane_id, 4) ^ bfe(lane_id, 3));
element = xor_swap(element, 0x04, bfe(lane_id, 4) ^ bfe(lane_id, 2));
element = xor_swap(element, 0x02, bfe(lane_id, 4) ^ bfe(lane_id, 1));
element = xor_swap(element, 0x01, bfe(lane_id, 4) ^ bfe(lane_id, 0));
element = xor_swap(element, 0x10, bfe(lane_id, 4));
element = xor_swap(element, 0x08, bfe(lane_id, 3));
element = xor_swap(element, 0x04, bfe(lane_id, 2));
element = xor_swap(element, 0x02, bfe(lane_id, 1));
element = xor_swap(element, 0x01, bfe(lane_id, 0));
return;
}
struct BuildConfig {
size_t max_dataset_size;
size_t dataset_dim;
size_t node_degree{64};
size_t internal_node_degree{0};
// If internal_node_degree == 0, the value of node_degree will be assigned to it
size_t max_iterations{50};
float termination_threshold{0.0001};
size_t output_graph_degree{32};
cuvs::distance::DistanceType metric{cuvs::distance::DistanceType::L2Expanded};
};
template <typename Index_t>
class BloomFilter {
public:
BloomFilter(size_t nrow, size_t num_sets_per_list, size_t num_hashs)
: nrow_(nrow),
num_sets_per_list_(num_sets_per_list),
num_hashs_(num_hashs),
bitsets_(nrow * num_bits_per_set_ * num_sets_per_list)
{
}
void add(size_t list_id, Index_t key)
{
if (is_cleared) { is_cleared = false; }
uint32_t hash = hash_0(key);
size_t global_set_idx = list_id * num_bits_per_set_ * num_sets_per_list_ +
key % num_sets_per_list_ * num_bits_per_set_;
bitsets_[global_set_idx + hash % num_bits_per_set_] = 1;
for (size_t i = 1; i < num_hashs_; i++) {
hash = hash + hash_1(key);
bitsets_[global_set_idx + hash % num_bits_per_set_] = 1;
}
}
bool check(size_t list_id, Index_t key)
{
bool is_present = true;
uint32_t hash = hash_0(key);
size_t global_set_idx = list_id * num_bits_per_set_ * num_sets_per_list_ +
key % num_sets_per_list_ * num_bits_per_set_;
is_present &= bitsets_[global_set_idx + hash % num_bits_per_set_];
if (!is_present) return false;
for (size_t i = 1; i < num_hashs_; i++) {
hash = hash + hash_1(key);
is_present &= bitsets_[global_set_idx + hash % num_bits_per_set_];
if (!is_present) return false;
}
return true;
}
void clear()
{
if (is_cleared) return;
#pragma omp parallel for
for (size_t i = 0; i < nrow_ * num_bits_per_set_ * num_sets_per_list_; i++) {
bitsets_[i] = 0;
}
is_cleared = true;
}
private:
uint32_t hash_0(uint32_t value)
{
value *= 1103515245;
value += 12345;
value ^= value << 13;
value ^= value >> 17;
value ^= value << 5;
return value;
}
uint32_t hash_1(uint32_t value)
{
value *= 1664525;
value += 1013904223;
value ^= value << 13;
value ^= value >> 17;
value ^= value << 5;
return value;
}
static constexpr int num_bits_per_set_ = 512;
bool is_cleared{true};
std::vector<bool> bitsets_;
size_t nrow_;
size_t num_sets_per_list_;
size_t num_hashs_;
};
template <typename Index_t>
struct GnndGraph {
raft::resources const& res;
static constexpr int segment_size = 32;
InternalID_t<Index_t>* h_graph;
size_t nrow;
size_t node_degree;
int num_samples;
int num_segments;
raft::host_matrix<DistData_t, size_t, raft::row_major> h_dists;
raft::pinned_matrix<Index_t, size_t> h_graph_new;
raft::pinned_vector<int2, size_t> h_list_sizes_new;
raft::pinned_matrix<Index_t, size_t> h_graph_old;
raft::pinned_vector<int2, size_t> h_list_sizes_old;
BloomFilter<Index_t> bloom_filter;
GnndGraph(const GnndGraph&) = delete;
GnndGraph& operator=(const GnndGraph&) = delete;
GnndGraph(raft::resources const& res,
const size_t nrow,
const size_t node_degree,
const size_t internal_node_degree,
const size_t num_samples);
void init_random_graph();
// TODO: Create a generic bloom filter utility https://github.com/rapidsai/raft/issues/1827
// Use Bloom filter to sample "new" neighbors for local joining
void sample_graph_new(InternalID_t<Index_t>* new_neighbors, const size_t width);
void sample_graph(bool sample_new);
void update_graph(const InternalID_t<Index_t>* new_neighbors,
const DistData_t* new_dists,
const size_t width,
std::atomic<int64_t>& update_counter);
void sort_lists();
void clear();
~GnndGraph();
};
template <typename Data_t = float, typename Index_t = int>
class GNND {
public:
GNND(raft::resources const& res, const BuildConfig& build_config);
GNND(const GNND&) = delete;
GNND& operator=(const GNND&) = delete;
void build(Data_t* data,
const Index_t nrow,
Index_t* output_graph,
bool return_distances,
DistData_t* output_distances);
~GNND() = default;
using ID_t = InternalID_t<Index_t>;
void reset(raft::resources const& res);
private:
void add_reverse_edges(Index_t* graph_ptr,
Index_t* h_rev_graph_ptr,
Index_t* d_rev_graph_ptr,
int2* list_sizes,
cudaStream_t stream = 0);
void local_join(cudaStream_t stream = 0);
raft::resources const& res;
BuildConfig build_config_;
GnndGraph<Index_t> graph_;
std::atomic<int64_t> update_counter_;
size_t nrow_;
size_t ndim_;
raft::device_matrix<__half, size_t, raft::row_major> d_data_;
raft::device_vector<DistData_t, size_t> l2_norms_;
raft::device_matrix<ID_t, size_t, raft::row_major> graph_buffer_;
raft::device_matrix<DistData_t, size_t, raft::row_major> dists_buffer_;
raft::pinned_matrix<ID_t, size_t> graph_host_buffer_;
raft::pinned_matrix<DistData_t, size_t> dists_host_buffer_;
raft::device_vector<int, size_t> d_locks_;
raft::pinned_matrix<Index_t, size_t> h_rev_graph_new_;
raft::pinned_matrix<Index_t, size_t> h_graph_old_;
raft::pinned_matrix<Index_t, size_t> h_rev_graph_old_;
// int2.x is the number of forward edges, int2.y is the number of reverse edges
raft::device_vector<int2, size_t> d_list_sizes_new_;
raft::device_vector<int2, size_t> d_list_sizes_old_;
};
constexpr int TILE_ROW_WIDTH = 64;
constexpr int TILE_COL_WIDTH = 128;
constexpr int NUM_SAMPLES = 32;
// For now, the max. number of samples is 32, so the sample cache size is fixed
// to 64 (32 * 2).
constexpr int MAX_NUM_BI_SAMPLES = 64;
constexpr int SKEWED_MAX_NUM_BI_SAMPLES = skew_dim<float>(MAX_NUM_BI_SAMPLES);
constexpr int BLOCK_SIZE = 512;
constexpr int WMMA_M = 16;
constexpr int WMMA_N = 16;
constexpr int WMMA_K = 16;
template <typename Data_t>
__device__ __forceinline__ void load_vec(Data_t* vec_buffer,
const Data_t* d_vec,
const int load_dims,
const int padding_dims,
const int lane_id)
{
if constexpr (std::is_same_v<Data_t, float> or std::is_same_v<Data_t, uint8_t> or
std::is_same_v<Data_t, int8_t>) {
constexpr int num_load_elems_per_warp = raft::warp_size();
for (int step = 0; step < raft::ceildiv(padding_dims, num_load_elems_per_warp); step++) {
int idx = step * num_load_elems_per_warp + lane_id;
if (idx < load_dims) {
vec_buffer[idx] = d_vec[idx];
} else if (idx < padding_dims) {
vec_buffer[idx] = 0.0f;
}
}
}
if constexpr (std::is_same_v<Data_t, __half>) {
if ((size_t)d_vec % sizeof(float2) == 0 && (size_t)vec_buffer % sizeof(float2) == 0 &&
load_dims % 4 == 0 && padding_dims % 4 == 0) {
constexpr int num_load_elems_per_warp = raft::warp_size() * 4;
#pragma unroll
for (int step = 0; step < raft::ceildiv(padding_dims, num_load_elems_per_warp); step++) {
int idx_in_vec = step * num_load_elems_per_warp + lane_id * 4;
if (idx_in_vec + 4 <= load_dims) {
*(float2*)(vec_buffer + idx_in_vec) = *(float2*)(d_vec + idx_in_vec);
} else if (idx_in_vec + 4 <= padding_dims) {
*(float2*)(vec_buffer + idx_in_vec) = float2({0.0f, 0.0f});
}
}
} else {
constexpr int num_load_elems_per_warp = raft::warp_size();
for (int step = 0; step < raft::ceildiv(padding_dims, num_load_elems_per_warp); step++) {
int idx = step * num_load_elems_per_warp + lane_id;
if (idx < load_dims) {
vec_buffer[idx] = d_vec[idx];
} else if (idx < padding_dims) {
vec_buffer[idx] = 0.0f;
}
}
}
}
}
// TODO: Replace with RAFT utilities https://github.com/rapidsai/raft/issues/1827
/** Calculate L2 norm, and cast data to __half */
template <typename Data_t>
RAFT_KERNEL preprocess_data_kernel(
const Data_t* input_data,
__half* output_data,
int dim,
DistData_t* l2_norms,
size_t list_offset = 0,
cuvs::distance::DistanceType metric = cuvs::distance::DistanceType::L2Expanded)
{
extern __shared__ char buffer[];
__shared__ float l2_norm;
Data_t* s_vec = (Data_t*)buffer;
size_t list_id = list_offset + blockIdx.x;
load_vec(s_vec, input_data + blockIdx.x * dim, dim, dim, threadIdx.x % raft::warp_size());
if (threadIdx.x == 0) { l2_norm = 0; }
__syncthreads();
if (metric == cuvs::distance::DistanceType::L2Expanded ||
metric == cuvs::distance::DistanceType::CosineExpanded) {
int lane_id = threadIdx.x % raft::warp_size();
for (int step = 0; step < raft::ceildiv(dim, raft::warp_size()); step++) {
int idx = step * raft::warp_size() + lane_id;
float part_dist = 0;
if (idx < dim) {
part_dist = s_vec[idx];
part_dist = part_dist * part_dist;
}
__syncwarp();
for (int offset = raft::warp_size() >> 1; offset >= 1; offset >>= 1) {
part_dist += __shfl_down_sync(raft::warp_full_mask(), part_dist, offset);
}
if (lane_id == 0) { l2_norm += part_dist; }
__syncwarp();
}
}
for (int step = 0; step < raft::ceildiv(dim, raft::warp_size()); step++) {
int idx = step * raft::warp_size() + threadIdx.x;
if (idx < dim) {
if (metric == cuvs::distance::DistanceType::InnerProduct) {
output_data[list_id * dim + idx] = input_data[(size_t)blockIdx.x * dim + idx];
} else if (metric == cuvs::distance::DistanceType::CosineExpanded) {
output_data[list_id * dim + idx] =
(float)input_data[(size_t)blockIdx.x * dim + idx] / sqrt(l2_norm);
} else {
output_data[list_id * dim + idx] = input_data[(size_t)blockIdx.x * dim + idx];
if (idx == 0) { l2_norms[list_id] = l2_norm; }
}
}
}
}
template <typename Index_t>
RAFT_KERNEL add_rev_edges_kernel(const Index_t* graph,
Index_t* rev_graph,
int num_samples,
int2* list_sizes)
{
size_t list_id = blockIdx.x;
int2 list_size = list_sizes[list_id];
for (int idx = threadIdx.x; idx < list_size.x; idx += blockDim.x) {
// each node has same number (num_samples) of forward and reverse edges
size_t rev_list_id = graph[list_id * num_samples + idx];
// there are already num_samples forward edges
int idx_in_rev_list = atomicAdd(&list_sizes[rev_list_id].y, 1);
if (idx_in_rev_list >= num_samples) {
atomicExch(&list_sizes[rev_list_id].y, num_samples);
} else {
rev_graph[rev_list_id * num_samples + idx_in_rev_list] = list_id;
}
}
}
template <typename Index_t, typename ID_t = InternalID_t<Index_t>>
__device__ void insert_to_global_graph(ResultItem<Index_t> elem,
size_t list_id,
ID_t* graph,
DistData_t* dists,
int node_degree,
int* locks)
{
int tx = threadIdx.x;
int lane_id = tx % raft::warp_size();
size_t global_idx_base = list_id * node_degree;
if (elem.id() == list_id) return;
const int num_segments = raft::ceildiv(node_degree, raft::warp_size());
int loop_flag = 0;
do {
int segment_id = elem.id() % num_segments;
if (lane_id == 0) {
loop_flag = atomicCAS(&locks[list_id * num_segments + segment_id], 0, 1) == 0;
}
loop_flag = __shfl_sync(raft::warp_full_mask(), loop_flag, 0);
if (loop_flag == 1) {
ResultItem<Index_t> knn_list_frag;
int local_idx = segment_id * raft::warp_size() + lane_id;
size_t global_idx = global_idx_base + local_idx;
if (local_idx < node_degree) {
knn_list_frag.id_with_flag() = graph[global_idx].id_with_flag();
knn_list_frag.dist() = dists[global_idx];
}
int pos_to_insert = -1;
ResultItem<Index_t> prev_elem;
prev_elem.id_with_flag() =
__shfl_up_sync(raft::warp_full_mask(), knn_list_frag.id_with_flag(), 1);
prev_elem.dist() = __shfl_up_sync(raft::warp_full_mask(), knn_list_frag.dist(), 1);
if (lane_id == 0) {
prev_elem = ResultItem<Index_t>{std::numeric_limits<Index_t>::min(),
std::numeric_limits<DistData_t>::lowest()};
}
if (elem > prev_elem && elem < knn_list_frag) {
pos_to_insert = segment_id * raft::warp_size() + lane_id;
} else if (elem == prev_elem || elem == knn_list_frag) {
pos_to_insert = -2;
}
uint mask = __ballot_sync(raft::warp_full_mask(), pos_to_insert >= 0);
if (mask) {
uint set_lane_id = __fns(mask, 0, 1);
pos_to_insert = __shfl_sync(raft::warp_full_mask(), pos_to_insert, set_lane_id);
}
if (pos_to_insert >= 0) {
int local_idx = segment_id * raft::warp_size() + lane_id;
if (local_idx > pos_to_insert) {
local_idx++;
} else if (local_idx == pos_to_insert) {
graph[global_idx_base + local_idx].id_with_flag() = elem.id_with_flag();
dists[global_idx_base + local_idx] = elem.dist();
local_idx++;
}
size_t global_pos = global_idx_base + local_idx;
if (local_idx < (segment_id + 1) * raft::warp_size() && local_idx < node_degree) {
graph[global_pos].id_with_flag() = knn_list_frag.id_with_flag();
dists[global_pos] = knn_list_frag.dist();
}
}
__threadfence();
if (loop_flag && lane_id == 0) { atomicExch(&locks[list_id * num_segments + segment_id], 0); }
}
} while (!loop_flag);
}
template <typename Index_t>
__device__ ResultItem<Index_t> get_min_item(const Index_t id,
const int idx_in_list,
const Index_t* neighbs,
const DistData_t* distances,
const bool find_in_row = true)
{
int lane_id = threadIdx.x % raft::warp_size();
static_assert(MAX_NUM_BI_SAMPLES == 64);
int idx[MAX_NUM_BI_SAMPLES / raft::warp_size()];
float dist[MAX_NUM_BI_SAMPLES / raft::warp_size()] = {std::numeric_limits<DistData_t>::max(),
std::numeric_limits<DistData_t>::max()};
idx[0] = lane_id;
idx[1] = raft::warp_size() + lane_id;
if (neighbs[idx[0]] != id) {
dist[0] = find_in_row ? distances[idx_in_list * SKEWED_MAX_NUM_BI_SAMPLES + lane_id]
: distances[idx_in_list + lane_id * SKEWED_MAX_NUM_BI_SAMPLES];
}
if (neighbs[idx[1]] != id) {
dist[1] =
find_in_row
? distances[idx_in_list * SKEWED_MAX_NUM_BI_SAMPLES + raft::warp_size() + lane_id]
: distances[idx_in_list + (raft::warp_size() + lane_id) * SKEWED_MAX_NUM_BI_SAMPLES];
}
if (dist[1] < dist[0]) {
dist[0] = dist[1];
idx[0] = idx[1];
}
__syncwarp();
for (int offset = raft::warp_size() >> 1; offset >= 1; offset >>= 1) {
float other_idx = __shfl_down_sync(raft::warp_full_mask(), idx[0], offset);
float other_dist = __shfl_down_sync(raft::warp_full_mask(), dist[0], offset);
if (other_dist < dist[0]) {
dist[0] = other_dist;
idx[0] = other_idx;
}
}
ResultItem<Index_t> result;
result.dist() = __shfl_sync(raft::warp_full_mask(), dist[0], 0);
result.id_with_flag() = neighbs[__shfl_sync(raft::warp_full_mask(), idx[0], 0)];
return result;
}
template <typename T>
__device__ __forceinline__ void remove_duplicates(
T* list_a, int list_a_size, T* list_b, int list_b_size, int& unique_counter, int execute_warp_id)
{
static_assert(raft::warp_size() == 32);
if (!(threadIdx.x >= execute_warp_id * raft::warp_size() &&
threadIdx.x < execute_warp_id * raft::warp_size() + raft::warp_size())) {
return;
}
int lane_id = threadIdx.x % raft::warp_size();
T elem = std::numeric_limits<T>::max();
if (lane_id < list_a_size) { elem = list_a[lane_id]; }
warp_bitonic_sort(&elem, lane_id);
if (elem != std::numeric_limits<T>::max()) { list_a[lane_id] = elem; }
T elem_b = std::numeric_limits<T>::max();
if (lane_id < list_b_size) { elem_b = list_b[lane_id]; }
__syncwarp();
int idx_l = 0;
int idx_r = list_a_size;
bool existed = false;
while (idx_l < idx_r) {
int idx = (idx_l + idx_r) / 2;
int elem = list_a[idx];
if (elem == elem_b) {
existed = true;
break;
}
if (elem_b > elem) {
idx_l = idx + 1;
} else {
idx_r = idx;
}
}
if (!existed && elem_b != std::numeric_limits<T>::max()) {
int idx = atomicAdd(&unique_counter, 1);
list_a[list_a_size + idx] = elem_b;
}
}
// launch_bounds here denote BLOCK_SIZE = 512 and MIN_BLOCKS_PER_SM = 4
// Per
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications,
// MAX_RESIDENT_THREAD_PER_SM = BLOCK_SIZE * BLOCKS_PER_SM = 2048
// For architectures 750 and 860 (890), the values for MAX_RESIDENT_THREAD_PER_SM
// is 1024 and 1536 respectively, which means the bounds don't work anymore
template <typename Index_t, typename ID_t = InternalID_t<Index_t>>
RAFT_KERNEL
#ifdef __CUDA_ARCH__
#if (__CUDA_ARCH__) == 750 || ((__CUDA_ARCH__) >= 860 && (__CUDA_ARCH__) <= 890) || \
(__CUDA_ARCH__) == 1200
__launch_bounds__(BLOCK_SIZE)
#else
__launch_bounds__(BLOCK_SIZE, 4)
#endif
#endif
local_join_kernel(const Index_t* graph_new,
const Index_t* rev_graph_new,
const int2* sizes_new,
const Index_t* graph_old,
const Index_t* rev_graph_old,
const int2* sizes_old,
const int width,
const __half* data,
const int data_dim,
ID_t* graph,
DistData_t* dists,
int graph_width,
int* locks,
DistData_t* l2_norms,
cuvs::distance::DistanceType metric)
{
#if (__CUDA_ARCH__ >= 700)
using namespace nvcuda;
__shared__ int s_list[MAX_NUM_BI_SAMPLES * 2];
constexpr int APAD = 8;
constexpr int BPAD = 8;
__shared__ __half s_nv[MAX_NUM_BI_SAMPLES][TILE_COL_WIDTH + APAD]; // New vectors
__shared__ __half s_ov[MAX_NUM_BI_SAMPLES][TILE_COL_WIDTH + BPAD]; // Old vectors
static_assert(sizeof(float) * MAX_NUM_BI_SAMPLES * SKEWED_MAX_NUM_BI_SAMPLES <=
sizeof(__half) * MAX_NUM_BI_SAMPLES * (TILE_COL_WIDTH + BPAD));
// s_distances: MAX_NUM_BI_SAMPLES x SKEWED_MAX_NUM_BI_SAMPLES, reuse the space of s_ov
float* s_distances = (float*)&s_ov[0][0];
int* s_unique_counter = (int*)&s_ov[0][0];
if (threadIdx.x == 0) {
s_unique_counter[0] = 0;
s_unique_counter[1] = 0;
}
Index_t* new_neighbors = s_list;
Index_t* old_neighbors = s_list + MAX_NUM_BI_SAMPLES;
size_t list_id = blockIdx.x;
int2 list_new_size2 = sizes_new[list_id];
int list_new_size = list_new_size2.x + list_new_size2.y;
int2 list_old_size2 = sizes_old[list_id];
int list_old_size = list_old_size2.x + list_old_size2.y;
if (!list_new_size) return;
int tx = threadIdx.x;
if (tx < list_new_size2.x) {
new_neighbors[tx] = graph_new[list_id * width + tx];
} else if (tx >= list_new_size2.x && tx < list_new_size) {
new_neighbors[tx] = rev_graph_new[list_id * width + tx - list_new_size2.x];
}
if (tx < list_old_size2.x) {
old_neighbors[tx] = graph_old[list_id * width + tx];
} else if (tx >= list_old_size2.x && tx < list_old_size) {
old_neighbors[tx] = rev_graph_old[list_id * width + tx - list_old_size2.x];
}
__syncthreads();
remove_duplicates(new_neighbors,
list_new_size2.x,
new_neighbors + list_new_size2.x,
list_new_size2.y,
s_unique_counter[0],
0);
remove_duplicates(old_neighbors,
list_old_size2.x,
old_neighbors + list_old_size2.x,
list_old_size2.y,
s_unique_counter[1],
1);
__syncthreads();
list_new_size = list_new_size2.x + s_unique_counter[0];
list_old_size = list_old_size2.x + s_unique_counter[1];
int warp_id = threadIdx.x / raft::warp_size();
int lane_id = threadIdx.x % raft::warp_size();
constexpr int num_warps = BLOCK_SIZE / raft::warp_size();
int warp_id_y = warp_id / 4;
int warp_id_x = warp_id % 4;
wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K, half, wmma::row_major> a_frag;
wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, half, wmma::col_major> b_frag;
wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> c_frag;
wmma::fill_fragment(c_frag, 0.0);
for (int step = 0; step < raft::ceildiv(data_dim, TILE_COL_WIDTH); step++) {
int num_load_elems = (step == raft::ceildiv(data_dim, TILE_COL_WIDTH) - 1)
? data_dim - step * TILE_COL_WIDTH
: TILE_COL_WIDTH;
#pragma unroll
for (int i = 0; i < MAX_NUM_BI_SAMPLES / num_warps; i++) {
int idx = i * num_warps + warp_id;
if (idx < list_new_size) {
size_t neighbor_id = new_neighbors[idx];
size_t idx_in_data = neighbor_id * data_dim;
load_vec(s_nv[idx],
data + idx_in_data + step * TILE_COL_WIDTH,
num_load_elems,
TILE_COL_WIDTH,
lane_id);
}
}
__syncthreads();
for (int i = 0; i < TILE_COL_WIDTH / WMMA_K; i++) {
wmma::load_matrix_sync(a_frag, s_nv[warp_id_y * WMMA_M] + i * WMMA_K, TILE_COL_WIDTH + APAD);
wmma::load_matrix_sync(b_frag, s_nv[warp_id_x * WMMA_N] + i * WMMA_K, TILE_COL_WIDTH + BPAD);
wmma::mma_sync(c_frag, a_frag, b_frag, c_frag);
__syncthreads();
}
}
wmma::store_matrix_sync(
s_distances + warp_id_y * WMMA_M * SKEWED_MAX_NUM_BI_SAMPLES + warp_id_x * WMMA_N,
c_frag,
SKEWED_MAX_NUM_BI_SAMPLES,
wmma::mem_row_major);
__syncthreads();
for (int i = threadIdx.x; i < MAX_NUM_BI_SAMPLES * SKEWED_MAX_NUM_BI_SAMPLES; i += blockDim.x) {
if (i % SKEWED_MAX_NUM_BI_SAMPLES < list_new_size &&
i / SKEWED_MAX_NUM_BI_SAMPLES < list_new_size) {
if (metric == cuvs::distance::DistanceType::InnerProduct) {
s_distances[i] = -s_distances[i];
} else if (metric == cuvs::distance::DistanceType::CosineExpanded) {
s_distances[i] = 1.0 - s_distances[i];
} else {
s_distances[i] = l2_norms[new_neighbors[i % SKEWED_MAX_NUM_BI_SAMPLES]] +
l2_norms[new_neighbors[i / SKEWED_MAX_NUM_BI_SAMPLES]] -
2.0 * s_distances[i];
}
} else {
s_distances[i] = std::numeric_limits<float>::max();
}
}
__syncthreads();
for (int step = 0; step < raft::ceildiv(list_new_size, num_warps); step++) {
int idx_in_list = step * num_warps + tx / raft::warp_size();
if (idx_in_list >= list_new_size) continue;
auto min_elem = get_min_item(s_list[idx_in_list], idx_in_list, new_neighbors, s_distances);
if (min_elem.id() < gridDim.x) {
insert_to_global_graph(min_elem, s_list[idx_in_list], graph, dists, graph_width, locks);
}
}
if (!list_old_size) return;
__syncthreads();
wmma::fill_fragment(c_frag, 0.0);
for (int step = 0; step < raft::ceildiv(data_dim, TILE_COL_WIDTH); step++) {
int num_load_elems = (step == raft::ceildiv(data_dim, TILE_COL_WIDTH) - 1)
? data_dim - step * TILE_COL_WIDTH
: TILE_COL_WIDTH;
if (TILE_COL_WIDTH < data_dim) {
#pragma unroll
for (int i = 0; i < MAX_NUM_BI_SAMPLES / num_warps; i++) {
int idx = i * num_warps + warp_id;
if (idx < list_new_size) {
size_t neighbor_id = new_neighbors[idx];
size_t idx_in_data = neighbor_id * data_dim;
load_vec(s_nv[idx],
data + idx_in_data + step * TILE_COL_WIDTH,
num_load_elems,
TILE_COL_WIDTH,
lane_id);
}
}
}
#pragma unroll
for (int i = 0; i < MAX_NUM_BI_SAMPLES / num_warps; i++) {
int idx = i * num_warps + warp_id;
if (idx < list_old_size) {
size_t neighbor_id = old_neighbors[idx];
size_t idx_in_data = neighbor_id * data_dim;
load_vec(s_ov[idx],
data + idx_in_data + step * TILE_COL_WIDTH,
num_load_elems,
TILE_COL_WIDTH,
lane_id);
}
}
__syncthreads();
for (int i = 0; i < TILE_COL_WIDTH / WMMA_K; i++) {
wmma::load_matrix_sync(a_frag, s_nv[warp_id_y * WMMA_M] + i * WMMA_K, TILE_COL_WIDTH + APAD);
wmma::load_matrix_sync(b_frag, s_ov[warp_id_x * WMMA_N] + i * WMMA_K, TILE_COL_WIDTH + BPAD);
wmma::mma_sync(c_frag, a_frag, b_frag, c_frag);
__syncthreads();
}
}
wmma::store_matrix_sync(
s_distances + warp_id_y * WMMA_M * SKEWED_MAX_NUM_BI_SAMPLES + warp_id_x * WMMA_N,
c_frag,
SKEWED_MAX_NUM_BI_SAMPLES,
wmma::mem_row_major);
__syncthreads();
for (int i = threadIdx.x; i < MAX_NUM_BI_SAMPLES * SKEWED_MAX_NUM_BI_SAMPLES; i += blockDim.x) {
if (i % SKEWED_MAX_NUM_BI_SAMPLES < list_old_size &&
i / SKEWED_MAX_NUM_BI_SAMPLES < list_new_size) {
if (metric == cuvs::distance::DistanceType::InnerProduct) {
s_distances[i] = -s_distances[i];
} else if (metric == cuvs::distance::DistanceType::CosineExpanded) {
s_distances[i] = 1.0 - s_distances[i];
} else {
s_distances[i] = l2_norms[old_neighbors[i % SKEWED_MAX_NUM_BI_SAMPLES]] +
l2_norms[new_neighbors[i / SKEWED_MAX_NUM_BI_SAMPLES]] -
2.0 * s_distances[i];
}
} else {
s_distances[i] = std::numeric_limits<float>::max();
}
}
__syncthreads();
for (int step = 0; step < raft::ceildiv(MAX_NUM_BI_SAMPLES * 2, num_warps); step++) {
int idx_in_list = step * num_warps + tx / raft::warp_size();
if (idx_in_list >= list_new_size && idx_in_list < MAX_NUM_BI_SAMPLES) continue;
if (idx_in_list >= MAX_NUM_BI_SAMPLES + list_old_size && idx_in_list < MAX_NUM_BI_SAMPLES * 2)
continue;
ResultItem<Index_t> min_elem{std::numeric_limits<Index_t>::max(),
std::numeric_limits<DistData_t>::max()};
if (idx_in_list < MAX_NUM_BI_SAMPLES) {
auto temp_min_item =
get_min_item(s_list[idx_in_list], idx_in_list, old_neighbors, s_distances);
if (temp_min_item.dist() < min_elem.dist()) { min_elem = temp_min_item; }
} else {
auto temp_min_item = get_min_item(
s_list[idx_in_list], idx_in_list - MAX_NUM_BI_SAMPLES, new_neighbors, s_distances, false);
if (temp_min_item.dist() < min_elem.dist()) { min_elem = temp_min_item; }
}
if (min_elem.id() < gridDim.x) {
insert_to_global_graph(min_elem, s_list[idx_in_list], graph, dists, graph_width, locks);
}
}
#endif
}
namespace {
template <typename Index_t>
int insert_to_ordered_list(InternalID_t<Index_t>* list,
DistData_t* dist_list,
const int width,
const InternalID_t<Index_t> neighb_id,
const DistData_t dist)
{
if (dist > dist_list[width - 1]) { return width; }
int idx_insert = width;
bool position_found = false;
for (int i = 0; i < width; i++) {
if (list[i].id() == neighb_id.id()) { return width; }
if (!position_found && dist_list[i] > dist) {
idx_insert = i;
position_found = true;
}
}
if (idx_insert == width) return idx_insert;
memmove(list + idx_insert + 1, list + idx_insert, sizeof(*list) * (width - idx_insert - 1));
memmove(dist_list + idx_insert + 1,
dist_list + idx_insert,
sizeof(*dist_list) * (width - idx_insert - 1));
list[idx_insert] = neighb_id;
dist_list[idx_insert] = dist;
return idx_insert;
};
} // namespace
template <typename Index_t>
GnndGraph<Index_t>::GnndGraph(raft::resources const& res,
const size_t nrow,
const size_t node_degree,
const size_t internal_node_degree,
const size_t num_samples)