-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathcagra_build.cuh
More file actions
2307 lines (2049 loc) · 103 KB
/
Copy pathcagra_build.cuh
File metadata and controls
2307 lines (2049 loc) · 103 KB
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
/*
* SPDX-FileCopyrightText: Copyright (c) 2023-2026, NVIDIA CORPORATION.
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "../../../core/nvtx.hpp"
#include "../../../preprocessing/quantize/vpq_build-ext.cuh"
#include "jit_lto_kernels/graph_core.cuh"
#include <raft/core/copy.cuh>
#include <raft/core/device_mdarray.hpp>
#include <raft/core/device_mdspan.hpp>
#include <raft/core/error.hpp>
#include <raft/core/host_device_accessor.hpp>
#include <raft/core/host_mdarray.hpp>
#include <raft/core/host_mdspan.hpp>
#include <raft/core/logger.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/util/integer_utils.hpp>
#include <cuvs/cluster/kmeans.hpp>
#include <cuvs/distance/distance.hpp>
#include <cuvs/neighbors/cagra.hpp>
#include <cuvs/neighbors/ivf_pq.hpp>
#include <cuvs/neighbors/nn_descent.hpp>
#include <cuvs/neighbors/refine.hpp>
#include <cuvs/util/file_io.hpp>
#include <cuvs/util/host_memory.hpp>
// TODO: This shouldn't be calling spatial/knn APIs
#include "../ann_utils.cuh"
#include <rmm/resource_ref.hpp>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <omp.h>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>
#include <sys/mman.h>
#include <sys/stat.h>
namespace cuvs::neighbors::cagra::detail {
// Helpers to convert bytes to MiB and GiB
constexpr double to_mib(size_t bytes) { return static_cast<double>(bytes) / (1 << 20); }
constexpr double to_gib(size_t bytes) { return static_cast<double>(bytes) / (1 << 30); }
template <typename T, typename IdxT>
void check_graph_degree(size_t& intermediate_degree, size_t& graph_degree, size_t dataset_size)
{
if (intermediate_degree >= static_cast<size_t>(dataset_size)) {
RAFT_LOG_WARN(
"Intermediate graph degree cannot be larger than dataset size, reducing it to %lu",
dataset_size);
intermediate_degree = dataset_size - 1;
}
if (intermediate_degree < graph_degree) {
RAFT_LOG_WARN(
"Graph degree (%lu) cannot be larger than intermediate graph degree (%lu), reducing "
"graph_degree.",
graph_degree,
intermediate_degree);
graph_degree = intermediate_degree;
}
}
// ACE: Get partition labels for partitioned approach
// TODO(julianmi): Use all neighbors APIs.
template <typename T, typename IdxT>
void ace_get_partition_labels(
raft::resources const& res,
raft::host_matrix_view<const T, int64_t, raft::row_major> dataset,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_labels,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_histogram,
size_t min_partition_size,
double sampling_rate = 0.01)
{
size_t dataset_size = dataset.extent(0);
size_t dataset_dim = dataset.extent(1);
size_t labels_size = partition_labels.extent(0);
size_t labels_dim = partition_labels.extent(1);
RAFT_EXPECTS(dataset_size == labels_size, "Dataset size must match partition labels extent");
size_t n_partitions = partition_histogram.extent(0);
RAFT_EXPECTS(labels_dim == 2, "Labels must have 2 columns");
RAFT_EXPECTS(partition_histogram.extent(1) == 2, "Partition histogram must have 2 columns");
cudaStream_t stream = raft::resource::get_cuda_stream(res);
// Sampling vectors from dataset. Uses float conversion on host instead of
// raft::matrix::sample_rows to minimize GPU memory usage.
// TODO(julianmi): Switch to sample_rows when https://github.com/rapidsai/cuvs/issues/1461 is
// addressed.
size_t n_samples = dataset_size * sampling_rate;
const size_t min_samples = 100 * n_partitions;
n_samples = std::max(n_samples, min_samples);
n_samples = std::min(n_samples, dataset_size);
RAFT_LOG_DEBUG("ACE: n_samples: %lu", n_samples);
auto sample_db = raft::make_host_matrix<float, int64_t>(n_samples, dataset_dim);
#pragma omp parallel for
for (size_t i = 0; i < n_samples; i++) {
size_t j = i * dataset_size / n_samples;
for (size_t k = 0; k < dataset_dim; k++) {
sample_db(i, k) = static_cast<float>(dataset(j, k));
}
}
auto sample_db_dev = raft::make_device_matrix<float, int64_t>(res, n_samples, dataset_dim);
raft::copy(res, sample_db_dev.view(), sample_db.view());
cuvs::cluster::kmeans::balanced_params kmeans_params;
auto centroids_dev = raft::make_device_matrix<float, int64_t>(res, n_partitions, dataset_dim);
cuvs::cluster::kmeans::fit(res, kmeans_params, sample_db_dev.view(), centroids_dev.view());
// Compute distances between dataset and centroid vectors
// Uses float conversion on host instead of batch_load_iterator to minimize GPU memory usage.
const size_t chunk_size = 32 * 1024;
auto _sub_dataset = raft::make_host_matrix<float, int64_t>(chunk_size, dataset_dim);
auto _sub_distances = raft::make_host_matrix<float, int64_t>(chunk_size, n_partitions);
auto _sub_dataset_dev = raft::make_device_matrix<float, int64_t>(res, chunk_size, dataset_dim);
auto _sub_distances_dev = raft::make_device_matrix<float, int64_t>(res, chunk_size, n_partitions);
size_t report_interval = dataset_size / 10;
report_interval = (report_interval / chunk_size) * chunk_size;
report_interval = std::max(report_interval, chunk_size);
for (size_t i_base = 0; i_base < dataset_size; i_base += chunk_size) {
const size_t sub_dataset_size = std::min(chunk_size, dataset_size - i_base);
if (i_base % report_interval == 0) {
RAFT_LOG_INFO("ACE: Processing chunk %lu / %lu (%.1f%%)",
i_base,
dataset_size,
static_cast<double>(100 * i_base) / dataset_size);
}
auto sub_dataset = raft::make_host_matrix_view<float, int64_t>(
_sub_dataset.data_handle(), sub_dataset_size, dataset_dim);
#pragma omp parallel for
for (size_t i_sub = 0; i_sub < sub_dataset_size; i_sub++) {
size_t i = i_base + i_sub;
for (size_t k = 0; k < dataset_dim; k++) {
sub_dataset(i_sub, k) = static_cast<float>(dataset(i, k));
}
}
auto sub_dataset_dev_view = raft::make_device_matrix_view<float, int64_t>(
_sub_dataset_dev.data_handle(), sub_dataset_size, dataset_dim);
raft::copy(res, sub_dataset_dev_view, sub_dataset);
auto sub_dataset_dev = raft::make_device_matrix_view<const float, int64_t>(
_sub_dataset_dev.data_handle(), sub_dataset_size, dataset_dim);
auto sub_distances = raft::make_host_matrix_view<float, int64_t>(
_sub_distances.data_handle(), sub_dataset_size, n_partitions);
auto sub_distances_dev = raft::make_device_matrix_view<float, int64_t>(
_sub_distances_dev.data_handle(), sub_dataset_size, n_partitions);
cuvs::distance::pairwise_distance(res,
sub_dataset_dev,
centroids_dev.view(),
sub_distances_dev,
cuvs::distance::DistanceType::L2Expanded);
raft::copy(res, sub_distances, sub_distances_dev);
raft::resource::sync_stream(res, stream);
// Find two closest partitions to each dataset vector
#pragma omp parallel for
for (size_t i_sub = 0; i_sub < sub_dataset_size; i_sub++) {
size_t core_label = 0;
size_t augmented_label = 1;
if (sub_distances(i_sub, 0) > sub_distances(i_sub, 1)) {
core_label = 1;
augmented_label = 0;
}
for (size_t c = 2; c < n_partitions; c++) {
if (sub_distances(i_sub, c) < sub_distances(i_sub, core_label)) {
augmented_label = core_label;
core_label = c;
} else if (sub_distances(i_sub, c) < sub_distances(i_sub, augmented_label)) {
augmented_label = c;
}
}
size_t i = i_base + i_sub;
partition_labels(i, 0) = core_label;
partition_labels(i, 1) = augmented_label;
#pragma omp atomic update
partition_histogram(core_label, 0) += 1;
#pragma omp atomic update
partition_histogram(augmented_label, 1) += 1;
}
}
}
// ACE: Check partition sizes for stable KNN graph construction
template <typename IdxT>
void ace_check_partition_sizes(
size_t dataset_size,
size_t n_partitions,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_labels,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_histogram,
size_t min_partition_size)
{
// Collect partition histogram statistics
size_t total_core_vectors = 0;
size_t total_augmented_vectors = 0;
size_t min_core_vectors = dataset_size;
size_t max_core_vectors = 0;
size_t min_augmented_vectors = dataset_size;
size_t max_augmented_vectors = 0;
size_t min_total_vectors = dataset_size;
size_t max_total_vectors = 0;
for (size_t c = 0; c < n_partitions; c++) {
size_t core_count = partition_histogram(c, 0);
size_t augmented_count = partition_histogram(c, 1);
size_t total_count = core_count + augmented_count;
if (total_count > 0) {
total_core_vectors += core_count;
total_augmented_vectors += augmented_count;
min_core_vectors = std::min(min_core_vectors, core_count);
max_core_vectors = std::max(max_core_vectors, core_count);
min_augmented_vectors = std::min(min_augmented_vectors, augmented_count);
max_augmented_vectors = std::max(max_augmented_vectors, augmented_count);
min_total_vectors = std::min(min_total_vectors, total_count);
max_total_vectors = std::max(max_total_vectors, total_count);
}
}
double avg_core_vectors = static_cast<double>(total_core_vectors) / n_partitions;
double avg_augmented_vectors = static_cast<double>(total_augmented_vectors) / n_partitions;
double avg_total_vectors = 2.0 * static_cast<double>(dataset_size) / n_partitions;
double expected_avg_vectors = 2.0 * static_cast<double>(dataset_size) / n_partitions;
RAFT_LOG_INFO("ACE: Core vectors - Total: %lu, Avg: %.1f, Min: %lu, Max: %lu",
total_core_vectors,
avg_core_vectors,
min_core_vectors,
max_core_vectors);
RAFT_LOG_INFO("ACE: Augmented vectors - Total: %lu, Avg: %.1f, Min: %lu, Max: %lu",
total_augmented_vectors,
avg_augmented_vectors,
min_augmented_vectors,
max_augmented_vectors);
RAFT_LOG_INFO("ACE: Total per partition - Total: %lu, Avg: %.1f, Min: %lu, Max: %lu",
total_core_vectors + total_augmented_vectors,
avg_total_vectors,
min_total_vectors,
max_total_vectors);
// Check for partition imbalance and issue warnings
size_t very_small_threshold = min_partition_size;
size_t very_large_threshold = static_cast<size_t>(5.0 * expected_avg_vectors);
for (size_t c = 0; c < n_partitions; c++) {
size_t total_count = partition_histogram(c, 0) + partition_histogram(c, 1);
if (total_count > 0 && total_count < very_small_threshold) {
RAFT_LOG_WARN(
"ACE: Partition %lu is very small (%lu vectors, expected ~%.1f). This may affect graph "
"quality.",
c,
total_count,
expected_avg_vectors);
} else if (total_count > very_large_threshold) {
RAFT_LOG_WARN(
"ACE: Partition %lu is very large (%lu vectors, expected ~%.1f, threshold: %lu). This may "
"indicate imbalance and can lead to memory issues in restricted environments.",
c,
total_count,
expected_avg_vectors,
very_large_threshold);
}
}
}
// ACE: Create forward/backward mappings between original and reordered vector IDs
// The in-memory path can be parallelized but the disk path requires ordering.
template <typename IdxT>
void ace_create_forward_and_backward_lists(
size_t dataset_size,
size_t n_partitions,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_labels,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_histogram,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_forward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets)
{
core_partition_offsets(0) = 0;
augmented_partition_offsets(0) = 0;
for (size_t c = 1; c < n_partitions; c++) {
core_partition_offsets(c) = core_partition_offsets(c - 1) + partition_histogram(c - 1, 0);
augmented_partition_offsets(c) =
augmented_partition_offsets(c - 1) + partition_histogram(c - 1, 1);
}
if (static_cast<size_t>(core_forward_mapping.extent(0)) == 0) {
// Memory path: both backward mappings
RAFT_EXPECTS(static_cast<size_t>(core_backward_mapping.extent(0)) == dataset_size,
"core_backward_mapping must be of size dataset_size");
RAFT_EXPECTS(static_cast<size_t>(augmented_backward_mapping.extent(0)) == dataset_size,
"augmented_backward_mapping must be of size dataset_size");
#pragma omp parallel for
for (size_t i = 0; i < dataset_size; i++) {
size_t core_partition_id = partition_labels(i, 0);
size_t core_id;
#pragma omp atomic capture
core_id = core_partition_offsets(core_partition_id)++;
RAFT_EXPECTS(core_id < dataset_size, "Vector ID must be smaller than dataset_size");
core_backward_mapping(core_id) = i;
size_t augmented_partition_id = partition_labels(i, 1);
size_t augmented_id;
#pragma omp atomic capture
augmented_id = augmented_partition_offsets(augmented_partition_id)++;
RAFT_EXPECTS(augmented_id < dataset_size, "Vector ID must be smaller than dataset_size");
augmented_backward_mapping(augmented_id) = i;
}
} else {
// Disk path: all three mappings
RAFT_EXPECTS(static_cast<size_t>(core_forward_mapping.extent(0)) == dataset_size,
"core_forward_mapping must be of size dataset_size");
RAFT_EXPECTS(static_cast<size_t>(core_backward_mapping.extent(0)) == dataset_size,
"core_backward_mapping must be of size dataset_size");
RAFT_EXPECTS(static_cast<size_t>(augmented_backward_mapping.extent(0)) == dataset_size,
"augmented_backward_mapping must be of size dataset_size");
for (size_t i = 0; i < dataset_size; i++) {
size_t core_partition_id = partition_labels(i, 0);
size_t core_id;
core_id = core_partition_offsets(core_partition_id)++;
RAFT_EXPECTS(core_id < dataset_size, "Vector ID must be smaller than dataset_size");
core_backward_mapping(core_id) = i;
core_forward_mapping(i) = core_id;
size_t augmented_partition_id = partition_labels(i, 1);
size_t augmented_id;
augmented_id = augmented_partition_offsets(augmented_partition_id)++;
RAFT_EXPECTS(augmented_id < dataset_size, "Vector ID must be smaller than dataset_size");
augmented_backward_mapping(augmented_id) = i;
}
}
// Restore idxptr arrays
for (size_t c = n_partitions; c > 0; c--) {
core_partition_offsets(c) = core_partition_offsets(c - 1);
augmented_partition_offsets(c) = augmented_partition_offsets(c - 1);
}
core_partition_offsets(0) = 0;
augmented_partition_offsets(0) = 0;
}
// ACE: Gather partition dataset
template <typename T, typename IdxT>
void ace_gather_partition_dataset(
size_t core_sub_dataset_size,
size_t augmented_sub_dataset_size,
size_t dataset_dim,
size_t partition_id,
raft::host_matrix_view<const T, int64_t, row_major> dataset,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets,
raft::host_matrix_view<T, int64_t, raft::row_major> sub_dataset)
{
const size_t vector_size_bytes = dataset_dim * sizeof(T);
// Copy core partition vectors
#pragma omp parallel for
for (size_t j = 0; j < core_sub_dataset_size; j++) {
size_t i = core_backward_mapping(j + core_partition_offsets(partition_id));
memcpy(&sub_dataset(j, 0), &dataset(i, 0), vector_size_bytes);
}
// Copy augmented partition vectors (2nd closest partition)
#pragma omp parallel for
for (size_t j = 0; j < augmented_sub_dataset_size; j++) {
size_t i = augmented_backward_mapping(j + augmented_partition_offsets(partition_id));
memcpy(&sub_dataset(j + core_sub_dataset_size, 0), &dataset(i, 0), vector_size_bytes);
}
}
// ACE: Adjust IDs from core and augmented partitions to global reordered IDs
template <typename IdxT>
void ace_adjust_sub_graph_ids(
size_t core_sub_dataset_size,
size_t augmented_sub_dataset_size,
size_t graph_degree,
size_t partition_id,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> sub_search_graph,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> search_graph,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_backward_mapping)
{
#pragma omp parallel for
for (size_t i = 0; i < core_sub_dataset_size; i++) {
// Map row index from local → reordered → original
size_t i_reordered = i + core_partition_offsets(partition_id);
size_t i_original = core_backward_mapping(i_reordered);
for (size_t k = 0; k < graph_degree; k++) {
size_t j = sub_search_graph(i, k);
size_t j_original;
if (j < core_sub_dataset_size) {
// core partition neighbor: local → core reordered → original
size_t j_reordered = j + core_partition_offsets(partition_id);
j_original = core_backward_mapping(j_reordered);
} else {
// Augmented partition neighbor: local → augmented reordered → original
size_t j_augmented = j - core_sub_dataset_size;
j_original =
augmented_backward_mapping(j_augmented + augmented_partition_offsets(partition_id));
}
search_graph(i_original, k) = j_original;
}
}
}
// ACE: Adjust ids in sub search graph in place for disk version
template <typename IdxT>
void ace_adjust_sub_graph_ids_disk(
size_t core_sub_dataset_size,
size_t augmented_sub_dataset_size,
size_t graph_degree,
size_t partition_id,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> sub_search_graph,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_forward_mapping)
{
#pragma omp parallel for
for (size_t i = 0; i < core_sub_dataset_size; i++) {
for (size_t k = 0; k < graph_degree; k++) {
size_t j = sub_search_graph(i, k);
if (j < core_sub_dataset_size) {
// core partition neighbor: local → core reordered
sub_search_graph(i, k) = j + core_partition_offsets(partition_id);
} else {
// Augmented partition neighbor: local → augmented reordered→ original → core reordered
size_t j_augmented = j - core_sub_dataset_size;
size_t j_original =
augmented_backward_mapping(j_augmented + augmented_partition_offsets(partition_id));
sub_search_graph(i, k) = core_forward_mapping(j_original);
}
}
}
}
// ACE: Reorder dataset based on partition assignments and store to disk
// Writes two files: reordered_dataset.npy (core partitions) and augmented_dataset.npy (secondary
// partitions). Uses buffered writes optimized for NVMe storage.
template <typename T, typename IdxT>
void ace_reorder_and_store_dataset(
raft::resources const& res,
const std::string& build_dir,
raft::host_matrix_view<const T, int64_t, row_major> dataset,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_labels,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_histogram,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_backward_mapping,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets,
cuvs::util::file_descriptor& reordered_fd,
cuvs::util::file_descriptor& augmented_fd,
cuvs::util::file_descriptor& mapping_fd,
size_t reordered_header_size,
size_t augmented_header_size,
size_t mapping_header_size)
{
auto start = std::chrono::high_resolution_clock::now();
size_t dataset_size = dataset.extent(0);
size_t dataset_dim = dataset.extent(1);
size_t n_partitions = partition_histogram.extent(0);
RAFT_LOG_DEBUG(
"ACE: Reordering and storing dataset to disk (%lu vectors, %lu dimensions, %lu partitions)",
dataset_size,
dataset_dim,
n_partitions);
// Calculate total sizes for pre-allocation
size_t total_core_vectors = 0;
size_t total_augmented_vectors = 0;
size_t max_core_vectors = 0;
size_t max_augmented_vectors = 0;
for (size_t p = 0; p < n_partitions; p++) {
total_core_vectors += partition_histogram(p, 0);
total_augmented_vectors += partition_histogram(p, 1);
max_core_vectors = std::max<size_t>(max_core_vectors, partition_histogram(p, 0));
max_augmented_vectors = std::max<size_t>(max_augmented_vectors, partition_histogram(p, 1));
}
RAFT_EXPECTS(total_core_vectors == dataset_size,
"Total core vectors must be equal to dataset size");
RAFT_EXPECTS(total_augmented_vectors == dataset_size,
"Total augmented vectors must be equal to dataset size");
// Pre-allocate file space for better performance
const size_t vector_size = dataset_dim * sizeof(T);
size_t reordered_file_size = total_core_vectors * vector_size;
size_t augmented_file_size = total_augmented_vectors * vector_size;
RAFT_LOG_DEBUG("ACE: Reordered dataset: %lu core vectors (%.2f GiB)",
total_core_vectors,
reordered_file_size / (1024.0 * 1024.0 * 1024.0));
RAFT_LOG_DEBUG("ACE: Augmented dataset: %lu secondary vectors (%.2f GiB)",
total_augmented_vectors,
augmented_file_size / (1024.0 * 1024.0 * 1024.0));
// Calculate partition start offsets for reordered and augmented datasets
auto core_partition_starts = raft::make_host_vector<size_t, int64_t>(n_partitions + 1);
memset(core_partition_starts.data_handle(), 0, (n_partitions + 1) * sizeof(size_t));
auto augmented_partition_starts = raft::make_host_vector<size_t, int64_t>(n_partitions + 1);
memset(augmented_partition_starts.data_handle(), 0, (n_partitions + 1) * sizeof(size_t));
auto core_partition_current = raft::make_host_vector<size_t, int64_t>(n_partitions);
memset(core_partition_current.data_handle(), 0, n_partitions * sizeof(size_t));
auto augmented_partition_current = raft::make_host_vector<size_t, int64_t>(n_partitions);
memset(augmented_partition_current.data_handle(), 0, n_partitions * sizeof(size_t));
for (size_t p = 0; p < n_partitions; p++) {
core_partition_starts(p + 1) = core_partition_starts(p) + partition_histogram(p, 0);
augmented_partition_starts(p + 1) = augmented_partition_starts(p) + partition_histogram(p, 1);
}
const size_t free_memory = cuvs::util::get_free_host_memory();
// Conservatively allocate 50% of free memory per partition. Accounts for internal buffers and
// overhead.
// TODO: Adjust overhead if needed.
const size_t memory_per_partition = 0.5 * free_memory / (n_partitions * 2);
size_t disk_write_size = raft::bound_by_power_of_two<size_t>(memory_per_partition);
// 64MB should be enough to saturate typical NVMe SSDs.
disk_write_size = std::min<size_t>(disk_write_size, 64 * 1024 * 1024);
size_t vectors_per_buffer = std::max<size_t>(64, disk_write_size / vector_size);
RAFT_LOG_DEBUG("ACE: Reorder buffers: %lu vectors per buffer (%.2f MiB)",
vectors_per_buffer,
to_mib(vectors_per_buffer * vector_size));
std::vector<raft::host_matrix<T, int64_t>> core_buffers;
std::vector<raft::host_matrix<T, int64_t>> augmented_buffers;
auto core_buffer_counts = raft::make_host_vector<size_t, int64_t>(n_partitions);
auto augmented_buffer_counts = raft::make_host_vector<size_t, int64_t>(n_partitions);
core_buffers.reserve(n_partitions);
augmented_buffers.reserve(n_partitions);
for (size_t p = 0; p < n_partitions; p++) {
core_buffers.emplace_back(raft::make_host_matrix<T, int64_t>(vectors_per_buffer, dataset_dim));
augmented_buffers.emplace_back(
raft::make_host_matrix<T, int64_t>(vectors_per_buffer, dataset_dim));
core_buffer_counts(p) = 0;
augmented_buffer_counts(p) = 0;
}
auto flush_core_buffer = [&](size_t partition_id) {
const size_t count = core_buffer_counts(partition_id);
if (count > 0) {
const size_t bytes_to_write = count * vector_size;
const size_t file_offset =
(core_partition_starts(partition_id) + core_partition_current(partition_id)) * vector_size +
reordered_header_size;
cuvs::util::write_large_file(
reordered_fd, core_buffers[partition_id].data_handle(), bytes_to_write, file_offset);
core_partition_current(partition_id) += count;
core_buffer_counts(partition_id) = 0;
}
};
auto flush_augmented_buffer = [&](size_t partition_id) {
const size_t count = augmented_buffer_counts(partition_id);
if (count > 0) {
const size_t bytes_to_write = count * vector_size;
const size_t file_offset =
(augmented_partition_starts(partition_id) + augmented_partition_current(partition_id)) *
vector_size +
augmented_header_size;
cuvs::util::write_large_file(
augmented_fd, augmented_buffers[partition_id].data_handle(), bytes_to_write, file_offset);
augmented_partition_current(partition_id) += count;
augmented_buffer_counts(partition_id) = 0;
}
};
size_t vectors_processed = 0;
const size_t log_interval = std::max(dataset_size / 10, size_t(1));
for (size_t i = 0; i < dataset_size; i++) {
size_t core_partition = partition_labels(i, 0);
size_t secondary_partition = partition_labels(i, 1);
// Add vector to core partition buffer
size_t core_buffer_row = core_buffer_counts(core_partition);
memcpy(
&core_buffers[core_partition](core_buffer_row, 0), &dataset(i, 0), dataset_dim * sizeof(T));
core_buffer_counts(core_partition)++;
// Flush core buffer if full
if (core_buffer_counts(core_partition) >= vectors_per_buffer) {
flush_core_buffer(core_partition);
}
// Add vector to augmented partition buffer
size_t augmented_buffer_row = augmented_buffer_counts(secondary_partition);
memcpy(&augmented_buffers[secondary_partition](augmented_buffer_row, 0),
&dataset(i, 0),
dataset_dim * sizeof(T));
augmented_buffer_counts(secondary_partition)++;
// Flush augmented buffer if full
if (augmented_buffer_counts(secondary_partition) >= vectors_per_buffer) {
flush_augmented_buffer(secondary_partition);
}
vectors_processed++;
if (vectors_processed % log_interval == 0) {
RAFT_LOG_INFO("ACE: Processed %lu/%lu vectors (%.1f%%)",
vectors_processed,
dataset_size,
100.0 * vectors_processed / dataset_size);
}
}
// Flush all remaining buffers
RAFT_LOG_DEBUG("ACE: Flushing remaining buffers...");
#pragma omp parallel sections
{
#pragma omp section
{
for (size_t p = 0; p < n_partitions; p++) {
flush_core_buffer(p);
}
}
#pragma omp section
{
for (size_t p = 0; p < n_partitions; p++) {
flush_augmented_buffer(p);
}
}
}
const size_t mapping_file_size = dataset_size * sizeof(IdxT);
cuvs::util::write_large_file(
mapping_fd, core_backward_mapping.data_handle(), mapping_file_size, mapping_header_size);
auto end = std::chrono::high_resolution_clock::now();
auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
// Calculate total bytes written
size_t total_bytes_written = reordered_file_size + augmented_file_size + mapping_file_size;
double throughput_mb_s =
elapsed_ms > 0 ? to_mib(total_bytes_written) / (elapsed_ms / 1000.0) : 0.0;
RAFT_LOG_INFO(
"ACE: Dataset (%.2f GiB reordered, %.2f GiB augmented, %.2f GiB mapping) reordering completed "
"in %ld ms (%.1f MiB/s)",
reordered_file_size / (1024.0 * 1024.0 * 1024.0),
augmented_file_size / (1024.0 * 1024.0 * 1024.0),
mapping_file_size / (1024.0 * 1024.0 * 1024.0),
elapsed_ms,
throughput_mb_s);
}
// ACE: Load partition dataset and augmented dataset from disk
template <typename T, typename IdxT>
void ace_load_partition_dataset_from_disk(
raft::resources const& res,
const std::string& build_dir,
size_t partition_id,
size_t dataset_dim,
raft::host_matrix_view<IdxT, int64_t, raft::row_major> partition_histogram,
raft::host_vector_view<IdxT, int64_t, raft::row_major> core_partition_offsets,
raft::host_vector_view<IdxT, int64_t, raft::row_major> augmented_partition_offsets,
raft::host_matrix_view<T, int64_t, raft::row_major> sub_dataset)
{
size_t n_partitions = partition_histogram.extent(0);
RAFT_LOG_DEBUG("ACE: Loading partition %lu dataset from disk", partition_id);
size_t core_size = partition_histogram(partition_id, 0);
size_t augmented_size = partition_histogram(partition_id, 1);
size_t total_partition_size = core_size + augmented_size;
RAFT_LOG_DEBUG("ACE: Partition %lu: %lu core + %lu augmented = %lu total vectors",
partition_id,
core_size,
augmented_size,
total_partition_size);
RAFT_EXPECTS(static_cast<size_t>(sub_dataset.extent(0)) == total_partition_size,
"sub_dataset rows (%lu) must match total partition size (%lu)",
sub_dataset.extent(0),
total_partition_size);
RAFT_EXPECTS(static_cast<size_t>(sub_dataset.extent(1)) == dataset_dim,
"sub_dataset columns (%lu) must match dataset dimensions (%lu)",
sub_dataset.extent(1),
dataset_dim);
const size_t vector_size = dataset_dim * sizeof(T);
const std::string reordered_dataset_path = build_dir + "/reordered_dataset.npy";
const std::string augmented_dataset_path = build_dir + "/augmented_dataset.npy";
if (!std::filesystem::exists(reordered_dataset_path)) {
RAFT_FAIL("ACE: Required file does not exist: %s", reordered_dataset_path.c_str());
}
if (!std::filesystem::exists(augmented_dataset_path)) {
RAFT_FAIL("ACE: Required file does not exist: %s", augmented_dataset_path.c_str());
}
size_t core_header_size = 0;
size_t augmented_header_size = 0;
size_t core_file_offset = 0;
size_t augmented_file_offset = 0;
{
std::ifstream is(reordered_dataset_path, std::ios::in | std::ios::binary);
if (!is) { RAFT_FAIL("Cannot open file %s", reordered_dataset_path.c_str()); }
auto start_pos = is.tellg();
raft::detail::numpy_serializer::read_header(is);
core_header_size = static_cast<size_t>(is.tellg() - start_pos);
}
{
std::ifstream is(augmented_dataset_path, std::ios::in | std::ios::binary);
if (!is) { RAFT_FAIL("Cannot open file %s", augmented_dataset_path.c_str()); }
auto start_pos = is.tellg();
raft::detail::numpy_serializer::read_header(is);
augmented_header_size = static_cast<size_t>(is.tellg() - start_pos);
}
for (size_t p = 0; p < partition_id; p++) {
core_file_offset += partition_histogram(p, 0);
augmented_file_offset += partition_histogram(p, 1);
}
core_file_offset *= vector_size;
augmented_file_offset *= vector_size;
core_file_offset += core_header_size;
augmented_file_offset += augmented_header_size;
RAFT_LOG_DEBUG("ACE: Core file offset: %lu bytes, Augmented file offset: %lu bytes",
core_file_offset,
augmented_file_offset);
// Read core and augmented data in parallel
std::exception_ptr core_exception = nullptr;
std::exception_ptr augmented_exception = nullptr;
#pragma omp parallel sections
{
#pragma omp section
{
try {
if (core_size > 0) {
RAFT_LOG_DEBUG(
"ACE: Reading %lu core vectors from offset %lu", core_size, core_file_offset);
cuvs::util::file_descriptor reordered_fd(reordered_dataset_path, O_RDONLY);
const size_t core_bytes = core_size * vector_size;
cuvs::util::read_large_file(
reordered_fd, sub_dataset.data_handle(), core_bytes, core_file_offset);
}
} catch (...) {
core_exception = std::current_exception();
}
}
#pragma omp section
{
try {
if (augmented_size > 0) {
RAFT_LOG_DEBUG("ACE: Reading %lu augmented vectors from offset %lu",
augmented_size,
augmented_file_offset);
cuvs::util::file_descriptor augmented_fd(augmented_dataset_path, O_RDONLY);
const size_t augmented_bytes = augmented_size * vector_size;
T* augmented_dest = sub_dataset.data_handle() + (core_size * dataset_dim);
cuvs::util::read_large_file(
augmented_fd, augmented_dest, augmented_bytes, augmented_file_offset);
}
} catch (...) {
augmented_exception = std::current_exception();
}
}
}
// Check for exceptions from parallel sections
if (core_exception) { std::rethrow_exception(core_exception); }
if (augmented_exception) { std::rethrow_exception(augmented_exception); }
}
// Memory requirements for ACE operation
struct ace_memory_requirements {
size_t partition_labels_size;
size_t id_mapping_size;
size_t sub_dataset_size;
size_t sub_graph_size;
size_t cagra_graph_size;
size_t total_size;
size_t available_host_memory;
size_t available_gpu_memory;
};
// TODO: Adjust overhead factor if needed. Very conservative for now.
constexpr double usable_cpu_memory_fraction = 0.8;
constexpr double usable_gpu_memory_fraction = 0.8;
constexpr double imbalance_factor = 3.0;
// Calculate CAGRA optimize workspace memory requirements.
// This is the working memory on top of the input/output memory usage.
inline std::pair<size_t, size_t> optimize_workspace_size(size_t n_rows,
size_t graph_degree,
size_t intermediate_degree,
size_t index_size,
bool mst_optimize = false)
{
// MST optimization memory (host only)
size_t mst_host = n_rows * index_size; // mst_graph_num_edges
if (mst_optimize) {
mst_host += n_rows * graph_degree * index_size; // mst_graph allocated in optimize
mst_host += n_rows * graph_degree * index_size; // mst_graph allocated in mst_optimize
mst_host += n_rows * index_size * 7; // vectors with _max_edges suffix
mst_host += (graph_degree - 1) * (graph_degree - 1) * index_size; // iB_candidates
}
// Prune stage memory
// We neglect 8 bytes (both on host and device) for stats
size_t prune_host = n_rows * intermediate_degree * sizeof(uint8_t); // detour count
size_t prune_dev = n_rows * intermediate_degree * 1; // detour count (uint8_t)
prune_dev += n_rows * sizeof(uint32_t); // d_num_detour_edges
prune_dev += n_rows * intermediate_degree * index_size; // d_input_graph
// Reverse graph stage memory
size_t rev_host = n_rows * graph_degree * index_size; // rev_graph
rev_host += n_rows * sizeof(uint32_t); // rev_graph_count
rev_host += n_rows * index_size; // dest_nodes
size_t rev_dev = n_rows * graph_degree * index_size; // d_rev_graph
rev_dev += n_rows * sizeof(uint32_t); // d_rev_graph_count
rev_dev += n_rows * sizeof(uint32_t); // d_dest_nodes
// Memory for merging graphs (host only)
size_t combine_host =
n_rows * sizeof(uint32_t) + graph_degree * sizeof(uint32_t); // in_edge_count + hist
size_t total_host = mst_host + std::max({prune_host, rev_host, combine_host});
size_t total_dev = std::max(prune_dev, rev_dev);
return std::make_pair(total_host, total_dev);
}
// Check if disk mode should be used for ACE based on memory constraints
template <typename T, typename IdxT>
bool ace_check_use_disk_mode(bool use_disk,
std::string& build_dir,
size_t dataset_size,
size_t dataset_dim,
size_t n_partitions,
size_t intermediate_degree,
size_t graph_degree,
std::optional<double> max_host_memory_gb,
std::optional<double> max_gpu_memory_gb,
ace_memory_requirements& mem)
{
// Use overridden memory limits if provided (> 0), otherwise query actual system memory
if (max_host_memory_gb.has_value() && max_host_memory_gb.value() > 0) {
mem.available_host_memory = static_cast<size_t>(max_host_memory_gb.value() * (1ULL << 30));
RAFT_LOG_INFO("ACE: Using overridden host memory limit: %.2f GiB", max_host_memory_gb.value());
} else {
mem.available_host_memory = cuvs::util::get_free_host_memory();
}
// Optimistic memory model: focus on largest arrays, assumes all partitions are of equal size
// For memory path:
// - Partition labels (core + augmented): 2 * dataset_size * sizeof(IdxT)
// - Backward ID mapping arrays (core + augmented): 2 * dataset_size * sizeof(IdxT)
// - Avg. per-partition dataset: 2 * (dataset_size / n_partitions) * dataset_dim * sizeof(T)
// - Avg. per-partition graph during build: 2 * (dataset_size / n_partitions) * (intermediate +
// final)
// * sizeof(IdxT)
// - Final assembled graph: dataset_size * graph_degree * sizeof(IdxT)
mem.partition_labels_size = 2 * dataset_size * sizeof(IdxT);
mem.id_mapping_size = 2 * dataset_size * sizeof(IdxT);
mem.sub_dataset_size =
imbalance_factor * 2 * (dataset_size / n_partitions) * dataset_dim * sizeof(T);
mem.sub_graph_size = imbalance_factor * 2 * (dataset_size / n_partitions) *
(intermediate_degree + graph_degree) * sizeof(IdxT);
mem.cagra_graph_size = dataset_size * graph_degree * sizeof(IdxT);
mem.total_size = mem.partition_labels_size + mem.id_mapping_size + mem.sub_dataset_size +
mem.sub_graph_size + mem.cagra_graph_size;
RAFT_LOG_INFO("ACE: Estimated host memory required: %.2f GiB, available: %.2f GiB",
to_gib(mem.total_size),
to_gib(mem.available_host_memory));
bool host_memory_limited =
static_cast<size_t>(usable_cpu_memory_fraction * mem.available_host_memory) < mem.total_size;
// GPU is mostly limited by the index size (update_graph() in the end of this routine).
// Check if GPU has enough memory for the final graph or use disk mode instead.
// TODO: Extend model or use managed memory if running out of GPU memory.
if (max_gpu_memory_gb.has_value() && max_gpu_memory_gb.value() > 0) {
mem.available_gpu_memory = static_cast<size_t>(max_gpu_memory_gb.value() * (1ULL << 30));
RAFT_LOG_INFO("ACE: Using overridden GPU memory limit: %.2f GiB", max_gpu_memory_gb.value());
} else {
mem.available_gpu_memory = rmm::available_device_memory().second;
}
bool gpu_memory_limited =
static_cast<size_t>(usable_gpu_memory_fraction * mem.available_gpu_memory) <
std::max(mem.sub_graph_size, mem.sub_dataset_size);
RAFT_LOG_INFO("ACE: Estimated GPU memory required: %.2f GiB, available: %.2f GiB",
to_gib(mem.cagra_graph_size),
to_gib(mem.available_gpu_memory));
bool use_disk_mode = use_disk || host_memory_limited || gpu_memory_limited;
if (use_disk_mode) {
bool valid_build_dir = !build_dir.empty();
valid_build_dir &= build_dir.length() <= 255;
valid_build_dir &= build_dir.find('\0') == std::string::npos;
valid_build_dir &= build_dir.find("//") == std::string::npos;
if (!valid_build_dir) {
RAFT_LOG_WARN("ACE: Invalid build_dir path, resetting to default: /tmp/ace_build");
build_dir = "/tmp/ace_build";
}
if (mkdir(build_dir.c_str(), 0755) != 0 && errno != EEXIST) {
RAFT_EXPECTS(false, "Failed to create ACE build directory: %s", build_dir.c_str());
}
}
if (host_memory_limited && gpu_memory_limited) {
RAFT_LOG_INFO(
"ACE: Graph does not fit in host and GPU memory. Using disk-mode with temporary storage %s",
build_dir.c_str());
} else if (host_memory_limited) {
RAFT_LOG_INFO(
"ACE: Graph does not fit in host memory. Using disk-mode with temporary storage %s",
build_dir.c_str());
} else if (gpu_memory_limited) {
RAFT_LOG_INFO(
"ACE: Graph does not fit in GPU memory. Using disk-mode with temporary storage %s",
build_dir.c_str());
} else if (use_disk) {
RAFT_LOG_INFO(
"ACE: Graph fits in host and GPU memory but disk mode is forced. Using disk-mode with "
"temporary storage %s",
build_dir.c_str());
} else {
RAFT_LOG_INFO("ACE: Graph fits in host and GPU memory. Using in-memory mode.");
}
return use_disk_mode;
}
// Validate and adjust partitions for disk mode memory requirements
template <typename T, typename IdxT>
void ace_validate_disk_mode_partitions(size_t& n_partitions,
size_t dataset_size,
size_t dataset_dim,
size_t intermediate_degree,
size_t graph_degree,
bool guarantee_connectivity,
ace_memory_requirements& mem)
{
// In disk mode, we don't need the full dataset or final graph in memory.
// Host memory model for disk mode:
// - Partition labels (core + augmented): 2 * dataset_size * sizeof(IdxT)
// - ID mapping arrays (core + augmented): 2 * dataset_size * sizeof(IdxT)
// - Avg. per-partition dataset during processing: 2 * (dataset_size / n_partitions) *
// dataset_dim * sizeof(T)
// - Avg. per-partition graph during build: 2 * (dataset_size / n_partitions) * (intermediate +
// final) * sizeof(IdxT)
size_t original_n_partitions = n_partitions;
size_t host_suggested_partitions = n_partitions;
size_t gpu_suggested_partitions = n_partitions;
bool host_memory_insufficient = false;
bool gpu_memory_insufficient = false;
// Compute optimize workspace requirements
size_t sub_partition_size =
static_cast<size_t>(imbalance_factor * 2 * (dataset_size / n_partitions));
auto [host_workspace_size, gpu_workspace_size] = optimize_workspace_size(
sub_partition_size, graph_degree, intermediate_degree, sizeof(IdxT), guarantee_connectivity);
// Check host memory requirements
size_t disk_mode_host_required = mem.partition_labels_size + mem.id_mapping_size +
mem.sub_dataset_size + mem.sub_graph_size + host_workspace_size;
if (static_cast<size_t>(usable_cpu_memory_fraction * mem.available_host_memory) <
disk_mode_host_required) {