-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathindex.cpp
3766 lines (3324 loc) · 142 KB
/
index.cpp
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) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include <omp.h>
#include <array>
#include <type_traits>
#include "boost/dynamic_bitset.hpp"
#include "index_factory.h"
#include "memory_mapper.h"
#include "timer.h"
#include "tsl/robin_map.h"
#include "tsl/robin_set.h"
#include "windows_customizations.h"
#include "tag_uint128.h"
#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
#include "gperftools/malloc_extension.h"
#endif
#ifdef _WINDOWS
#include <xmmintrin.h>
#endif
#include "index.h"
#include <limits>
#define MAX_POINTS_FOR_USING_BITSET 10000000
namespace diskann
{
// Initialize an index with metric m, load the data of type T with filename
// (bin), and initialize max_points
template <typename T, typename TagT, typename LabelT>
Index<T, TagT, LabelT>::Index(const IndexConfig &index_config, std::shared_ptr<AbstractDataStore<T>> data_store,
std::unique_ptr<AbstractGraphStore> graph_store,
std::shared_ptr<AbstractDataStore<T>> pq_data_store)
: _dist_metric(index_config.metric), _dim(index_config.dimension), _max_points(index_config.max_points),
_num_frozen_pts(index_config.num_frozen_pts), _dynamic_index(index_config.dynamic_index),
_enable_tags(index_config.enable_tags), _indexingMaxC(DEFAULT_MAXC), _query_scratch(nullptr),
_pq_dist(index_config.pq_dist_build), _use_opq(index_config.use_opq),
_filtered_index(index_config.filtered_index), _num_pq_chunks(index_config.num_pq_chunks),
_delete_set(new tsl::robin_set<uint32_t>), _conc_consolidate(index_config.concurrent_consolidate)
{
if (_dynamic_index && !_enable_tags)
{
throw ANNException("ERROR: Dynamic Indexing must have tags enabled.", -1, __FUNCSIG__, __FILE__, __LINE__);
}
if (_pq_dist)
{
if (_dynamic_index)
throw ANNException("ERROR: Dynamic Indexing not supported with PQ distance based "
"index construction",
-1, __FUNCSIG__, __FILE__, __LINE__);
if (_dist_metric == diskann::Metric::INNER_PRODUCT)
throw ANNException("ERROR: Inner product metrics not yet supported "
"with PQ distance "
"base index",
-1, __FUNCSIG__, __FILE__, __LINE__);
}
if (_dynamic_index && _num_frozen_pts == 0)
{
_num_frozen_pts = 1;
}
// Sanity check. While logically it is correct, max_points = 0 causes
// downstream problems.
if (_max_points == 0)
{
_max_points = 1;
}
const size_t total_internal_points = _max_points + _num_frozen_pts;
_start = (uint32_t)_max_points;
_data_store = data_store;
_pq_data_store = pq_data_store;
_graph_store = std::move(graph_store);
_locks = std::vector<non_recursive_mutex>(total_internal_points);
if (_enable_tags)
{
_location_to_tag.reserve(total_internal_points);
_tag_to_location.reserve(total_internal_points);
}
if (_dynamic_index)
{
this->enable_delete(); // enable delete by default for dynamic index
if (_filtered_index)
{
_location_to_labels.resize(total_internal_points);
}
}
if (index_config.index_write_params != nullptr)
{
_indexingQueueSize = index_config.index_write_params->search_list_size;
_indexingRange = index_config.index_write_params->max_degree;
_indexingMaxC = index_config.index_write_params->max_occlusion_size;
_indexingAlpha = index_config.index_write_params->alpha;
_filterIndexingQueueSize = index_config.index_write_params->filter_list_size;
_indexingThreads = index_config.index_write_params->num_threads;
_saturate_graph = index_config.index_write_params->saturate_graph;
if (index_config.index_search_params != nullptr)
{
std::uint32_t default_queue_size = (std::max)(_indexingQueueSize, _filterIndexingQueueSize);
uint32_t num_scratch_spaces = index_config.index_search_params->num_search_threads + _indexingThreads;
initialize_query_scratch(num_scratch_spaces, index_config.index_search_params->initial_search_list_size,
default_queue_size, _indexingRange, _indexingMaxC, _data_store->get_dims());
}
}
}
template <typename T, typename TagT, typename LabelT>
Index<T, TagT, LabelT>::Index(Metric m, const size_t dim, const size_t max_points,
const std::shared_ptr<IndexWriteParameters> index_parameters,
const std::shared_ptr<IndexSearchParams> index_search_params, const size_t num_frozen_pts,
const bool dynamic_index, const bool enable_tags, const bool concurrent_consolidate,
const bool pq_dist_build, const size_t num_pq_chunks, const bool use_opq,
const bool filtered_index)
: Index(
IndexConfigBuilder()
.with_metric(m)
.with_dimension(dim)
.with_max_points(max_points)
.with_index_write_params(index_parameters)
.with_index_search_params(index_search_params)
.with_num_frozen_pts(num_frozen_pts)
.is_dynamic_index(dynamic_index)
.is_enable_tags(enable_tags)
.is_concurrent_consolidate(concurrent_consolidate)
.is_pq_dist_build(pq_dist_build)
.with_num_pq_chunks(num_pq_chunks)
.is_use_opq(use_opq)
.is_filtered(filtered_index)
.with_data_type(diskann_type_to_name<T>())
.build(),
IndexFactory::construct_datastore<T>(DataStoreStrategy::MEMORY,
(max_points == 0 ? (size_t)1 : max_points) +
(dynamic_index && num_frozen_pts == 0 ? (size_t)1 : num_frozen_pts),
dim, m),
IndexFactory::construct_graphstore(GraphStoreStrategy::MEMORY,
(max_points == 0 ? (size_t)1 : max_points) +
(dynamic_index && num_frozen_pts == 0 ? (size_t)1 : num_frozen_pts),
(size_t)((index_parameters == nullptr ? 0 : index_parameters->max_degree) *
defaults::GRAPH_SLACK_FACTOR * 1.05)))
{
if (_pq_dist)
{
_pq_data_store = IndexFactory::construct_pq_datastore<T>(DataStoreStrategy::MEMORY, max_points + num_frozen_pts,
dim, m, num_pq_chunks, use_opq);
}
else
{
_pq_data_store = _data_store;
}
}
template <typename T, typename TagT, typename LabelT> Index<T, TagT, LabelT>::~Index()
{
// Ensure that no other activity is happening before dtor()
std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
for (auto &lock : _locks)
{
LockGuard lg(lock);
}
if (_opt_graph != nullptr)
{
delete[] _opt_graph;
}
if (!_query_scratch.empty())
{
ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
manager.destroy();
}
}
template <typename T, typename TagT, typename LabelT>
void Index<T, TagT, LabelT>::initialize_query_scratch(uint32_t num_threads, uint32_t search_l, uint32_t indexing_l,
uint32_t r, uint32_t maxc, size_t dim, size_t bitmask_size)
{
for (uint32_t i = 0; i < num_threads; i++)
{
auto scratch = new InMemQueryScratch<T>(search_l, indexing_l, r, maxc, dim, _data_store->get_aligned_dim(),
_data_store->get_alignment_factor(), _pq_dist, bitmask_size);
_query_scratch.push(scratch);
}
}
template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_tags(std::string tags_file)
{
if (!_enable_tags)
{
diskann::cout << "Not saving tags as they are not enabled." << std::endl;
return 0;
}
size_t tag_bytes_written;
TagT *tag_data = new TagT[_nd + _num_frozen_pts];
for (uint32_t i = 0; i < _nd; i++)
{
TagT tag;
if (_location_to_tag.try_get(i, tag))
{
tag_data[i] = tag;
}
else
{
// catering to future when tagT can be any type.
std::memset((char *)&tag_data[i], 0, sizeof(TagT));
}
}
if (_num_frozen_pts > 0)
{
std::memset((char *)&tag_data[_start], 0, sizeof(TagT) * _num_frozen_pts);
}
try
{
tag_bytes_written = save_bin<TagT>(tags_file, tag_data, _nd + _num_frozen_pts, 1);
}
catch (std::system_error &e)
{
throw FileException(tags_file, e, __FUNCSIG__, __FILE__, __LINE__);
}
delete[] tag_data;
return tag_bytes_written;
}
template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_data(std::string data_file)
{
// Note: at this point, either _nd == _max_points or any frozen points have
// been temporarily moved to _nd, so _nd + _num_frozen_pts is the valid
// location limit.
return _data_store->save(data_file, (location_t)(_nd + _num_frozen_pts));
}
// save the graph index on a file as an adjacency list. For each point,
// first store the number of neighbors, and then the neighbor list (each as
// 4 byte uint32_t)
template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_graph(std::string graph_file)
{
return _graph_store->store(graph_file, _nd + _num_frozen_pts, _num_frozen_pts, _start);
}
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::save_delete_list(const std::string &filename)
{
if (_delete_set->size() == 0)
{
return 0;
}
std::unique_ptr<uint32_t[]> delete_list = std::make_unique<uint32_t[]>(_delete_set->size());
uint32_t i = 0;
for (auto &del : *_delete_set)
{
delete_list[i++] = del;
}
return save_bin<uint32_t>(filename, delete_list.get(), _delete_set->size(), 1);
}
template <typename T, typename TagT, typename LabelT>
void Index<T, TagT, LabelT>::save(const char *filename, bool compact_before_save)
{
diskann::Timer timer;
std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
if (compact_before_save)
{
compact_data();
compact_frozen_point();
}
else
{
if (!_data_compacted)
{
throw ANNException("Index save for non-compacted index is not yet implemented", -1, __FUNCSIG__, __FILE__,
__LINE__);
}
}
if (!_save_as_one_file)
{
if (_filtered_index)
{
if (_label_to_start_id.size() > 0)
{
std::ofstream medoid_writer(std::string(filename) + "_labels_to_medoids.txt");
if (medoid_writer.fail())
{
throw diskann::ANNException(std::string("Failed to open file ") + filename, -1);
}
for (auto iter : _label_to_start_id)
{
medoid_writer << iter.first << ", " << iter.second << std::endl;
}
medoid_writer.close();
}
if (_use_universal_label)
{
std::ofstream universal_label_writer(std::string(filename) + "_universal_label.txt");
assert(universal_label_writer.is_open());
universal_label_writer << _universal_label << std::endl;
universal_label_writer.close();
}
if (_location_to_labels.size() > 0)
{
std::ofstream label_writer(std::string(filename) + "_labels.txt");
assert(label_writer.is_open());
for (uint32_t i = 0; i < _nd + _num_frozen_pts; i++)
{
for (uint32_t j = 0; j + 1 < _location_to_labels[i].size(); j++)
{
label_writer << _location_to_labels[i][j] << ",";
}
if (_location_to_labels[i].size() != 0)
label_writer << _location_to_labels[i][_location_to_labels[i].size() - 1];
label_writer << std::endl;
}
label_writer.close();
// write compacted raw_labels if data hence _location_to_labels was also compacted
if (compact_before_save && _dynamic_index)
{
_label_map = load_label_map(std::string(filename) + "_labels_map.txt");
std::unordered_map<LabelT, std::string> mapped_to_raw_labels;
// invert label map
for (const auto &[key, value] : _label_map)
{
mapped_to_raw_labels.insert({value, key});
}
// write updated labels
std::ofstream raw_label_writer(std::string(filename) + "_raw_labels.txt");
assert(raw_label_writer.is_open());
for (uint32_t i = 0; i < _nd + _num_frozen_pts; i++)
{
for (uint32_t j = 0; j + 1 < _location_to_labels[i].size(); j++)
{
raw_label_writer << mapped_to_raw_labels[_location_to_labels[i][j]] << ",";
}
if (_location_to_labels[i].size() != 0)
raw_label_writer
<< mapped_to_raw_labels[_location_to_labels[i][_location_to_labels[i].size() - 1]];
raw_label_writer << std::endl;
}
raw_label_writer.close();
}
}
}
std::string graph_file = std::string(filename);
std::string tags_file = std::string(filename) + ".tags";
std::string data_file = std::string(filename) + ".data";
std::string delete_list_file = std::string(filename) + ".del";
// Because the save_* functions use append mode, ensure that
// the files are deleted before save. Ideally, we should check
// the error code for delete_file, but will ignore now because
// delete should succeed if save will succeed.
delete_file(graph_file);
save_graph(graph_file);
delete_file(data_file);
save_data(data_file);
delete_file(tags_file);
save_tags(tags_file);
delete_file(delete_list_file);
save_delete_list(delete_list_file);
}
else
{
diskann::cout << "Save index in a single file currently not supported. "
"Not saving the index."
<< std::endl;
}
// If frozen points were temporarily compacted to _nd, move back to
// _max_points.
reposition_frozen_point_to_end();
diskann::cout << "Time taken for save: " << timer.elapsed() / 1000000.0 << "s." << std::endl;
}
#ifdef EXEC_ENV_OLS
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_tags(AlignedFileReader &reader)
{
#else
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_tags(const std::string tag_filename)
{
if (_enable_tags && !file_exists(tag_filename))
{
diskann::cerr << "Tag file " << tag_filename << " does not exist!" << std::endl;
throw diskann::ANNException("Tag file " + tag_filename + " does not exist!", -1, __FUNCSIG__, __FILE__,
__LINE__);
}
#endif
if (!_enable_tags)
{
diskann::cout << "Tags not loaded as tags not enabled." << std::endl;
return 0;
}
size_t file_dim, file_num_points;
TagT *tag_data;
#ifdef EXEC_ENV_OLS
load_bin<TagT>(reader, tag_data, file_num_points, file_dim);
#else
load_bin<TagT>(std::string(tag_filename), tag_data, file_num_points, file_dim);
#endif
this->_table_stats.tag_memory_usage =
file_num_points * file_dim * sizeof(TagT)
+ file_num_points * (sizeof(TagT) + sizeof(uint32_t))
+ file_num_points * (sizeof(TagT) + sizeof(uint32_t));
if (file_dim != 1)
{
std::stringstream stream;
stream << "ERROR: Found " << file_dim << " dimensions for tags,"
<< "but tag file must have 1 dimension." << std::endl;
diskann::cerr << stream.str() << std::endl;
delete[] tag_data;
throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
}
const size_t num_data_points = file_num_points - _num_frozen_pts;
_location_to_tag.reserve(num_data_points);
_tag_to_location.reserve(num_data_points);
for (uint32_t i = 0; i < (uint32_t)num_data_points; i++)
{
TagT tag = *(tag_data + i);
if (_delete_set->find(i) == _delete_set->end())
{
_location_to_tag.set(i, tag);
_tag_to_location[tag] = i;
}
}
diskann::cout << "Tags loaded." << std::endl;
delete[] tag_data;
return file_num_points;
}
template <typename T, typename TagT, typename LabelT>
#ifdef EXEC_ENV_OLS
size_t Index<T, TagT, LabelT>::load_data(AlignedFileReader &reader)
{
#else
size_t Index<T, TagT, LabelT>::load_data(std::string filename)
{
#endif
size_t file_dim, file_num_points;
#ifdef EXEC_ENV_OLS
diskann::get_bin_metadata(reader, file_num_points, file_dim);
#else
if (!file_exists(filename))
{
std::stringstream stream;
stream << "ERROR: data file " << filename << " does not exist." << std::endl;
diskann::cerr << stream.str() << std::endl;
throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
}
diskann::get_bin_metadata(filename, file_num_points, file_dim);
#endif
// since we are loading a new dataset, _empty_slots must be cleared
_empty_slots.clear();
if (file_dim != _dim)
{
std::stringstream stream;
stream << "ERROR: Driver requests loading " << _dim << " dimension,"
<< "but file has " << file_dim << " dimension." << std::endl;
diskann::cerr << stream.str() << std::endl;
throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
}
if (file_num_points > _max_points + _num_frozen_pts)
{
// update and tag lock acquired in load() before calling load_data
resize(file_num_points - _num_frozen_pts);
}
#ifdef EXEC_ENV_OLS
// REFACTOR TODO: Must figure out how to support aligned reader in a clean
// manner.
copy_aligned_data_from_file<T>(reader, _data, file_num_points, file_dim, _data_store->get_aligned_dim());
#else
_data_store->load(filename); // offset == 0.
#endif
return file_num_points;
}
#ifdef EXEC_ENV_OLS
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_delete_set(AlignedFileReader &reader)
{
#else
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_delete_set(const std::string &filename)
{
#endif
std::unique_ptr<uint32_t[]> delete_list;
size_t npts, ndim;
#ifdef EXEC_ENV_OLS
diskann::load_bin<uint32_t>(reader, delete_list, npts, ndim);
#else
diskann::load_bin<uint32_t>(filename, delete_list, npts, ndim);
#endif
assert(ndim == 1);
for (uint32_t i = 0; i < npts; i++)
{
_delete_set->insert(delete_list[i]);
}
return npts;
}
// load the index from file and update the max_degree, cur (navigating
// node loc), and _final_graph (adjacency list)
template <typename T, typename TagT, typename LabelT>
#ifdef EXEC_ENV_OLS
void Index<T, TagT, LabelT>::load(AlignedFileReader &reader, uint32_t num_threads, uint32_t search_l)
{
#else
void Index<T, TagT, LabelT>::load(const char *filename, uint32_t num_threads, uint32_t search_l)
{
#endif
std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
_has_built = true;
size_t tags_file_num_pts = 0, graph_num_pts = 0, data_file_num_pts = 0, label_num_pts = 0;
std::string mem_index_file(filename);
std::string labels_file = mem_index_file + "_labels.txt";
std::string labels_to_medoids = mem_index_file + "_labels_to_medoids.txt";
std::string labels_map_file = mem_index_file + "_labels_map.txt";
if (!_save_as_one_file)
{
// For DLVS Store, we will not support saving the index in multiple
// files.
#ifndef EXEC_ENV_OLS
std::string data_file = std::string(filename) + ".data";
std::string tags_file = std::string(filename) + ".tags";
std::string delete_set_file = std::string(filename) + ".del";
std::string graph_file = std::string(filename);
data_file_num_pts = load_data(data_file);
this->_table_stats.node_count = data_file_num_pts;
this->_table_stats.node_mem_usage = this->_data_store->get_data_size();
if (file_exists(delete_set_file))
{
load_delete_set(delete_set_file);
}
if (_enable_tags)
{
tags_file_num_pts = load_tags(tags_file);
}
graph_num_pts = load_graph(graph_file, data_file_num_pts);
this->_table_stats.graph_mem_usage = _graph_store->get_graph_size();
#endif
}
else
{
diskann::cout << "Single index file saving/loading support not yet "
"enabled. Not loading the index."
<< std::endl;
return;
}
if (data_file_num_pts != graph_num_pts || (data_file_num_pts != tags_file_num_pts && _enable_tags))
{
std::stringstream stream;
stream << "ERROR: When loading index, loaded " << data_file_num_pts << " points from datafile, "
<< graph_num_pts << " from graph, and " << tags_file_num_pts
<< " tags, with num_frozen_pts being set to " << _num_frozen_pts << " in constructor." << std::endl;
diskann::cerr << stream.str() << std::endl;
throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
}
if (file_exists(labels_file))
{
_label_map = load_label_map(labels_map_file);
this->_table_stats.label_count = _label_map.size();
parse_label_file_in_bitset(labels_file, label_num_pts, _label_map.size());
assert(label_num_pts == data_file_num_pts - _num_frozen_pts);
this->_table_stats.label_mem_usage = _bitmask_buf._buf.size() * sizeof(std::uint64_t);
if (file_exists(labels_to_medoids))
{
std::ifstream medoid_stream(labels_to_medoids);
std::string line, token;
uint32_t line_cnt = 0;
_label_to_start_id.clear();
while (std::getline(medoid_stream, line))
{
std::istringstream iss(line);
uint32_t cnt = 0;
uint32_t medoid = 0;
LabelT label;
while (std::getline(iss, token, ','))
{
token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
LabelT token_as_num = (LabelT)std::stoul(token);
if (cnt == 0)
label = token_as_num;
else
medoid = token_as_num;
cnt++;
}
_label_to_start_id[label] = medoid;
line_cnt++;
}
}
std::string universal_label_file(filename);
universal_label_file += "_universal_label.txt";
if (file_exists(universal_label_file))
{
std::ifstream universal_label_reader(universal_label_file);
universal_label_reader >> _universal_label;
_use_universal_label = true;
universal_label_reader.close();
}
}
_nd = data_file_num_pts - _num_frozen_pts;
_empty_slots.clear();
_empty_slots.reserve(_max_points);
for (auto i = _nd; i < _max_points; i++)
{
_empty_slots.insert((uint32_t)i);
}
reposition_frozen_point_to_end();
_table_stats.total_mem_usage = _table_stats.node_mem_usage
+ _table_stats.graph_mem_usage
+ _table_stats.label_mem_usage
+ _table_stats.tag_memory_usage;
diskann::cout << "Num frozen points:" << _num_frozen_pts << " _nd: " << _nd << " _start: " << _start
<< " size(_location_to_tag): " << _location_to_tag.size()
<< " size(_tag_to_location):" << _tag_to_location.size() << " Max points: " << _max_points
<< std::endl;
// For incremental index, _query_scratch is initialized in the constructor.
// For the bulk index, the params required to initialize _query_scratch
// are known only at load time, hence this check and the call to
// initialize_q_s().
if (_query_scratch.size() == 0)
{
initialize_query_scratch(num_threads, search_l, search_l, (uint32_t)_graph_store->get_max_range_of_graph(), _indexingMaxC,
_dim, _bitmask_buf._bitmask_size);
}
}
#ifndef EXEC_ENV_OLS
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::get_graph_num_frozen_points(const std::string &graph_file)
{
size_t expected_file_size;
uint32_t max_observed_degree, start;
size_t file_frozen_pts;
std::ifstream in;
in.exceptions(std::ios::badbit | std::ios::failbit);
in.open(graph_file, std::ios::binary);
in.read((char *)&expected_file_size, sizeof(size_t));
in.read((char *)&max_observed_degree, sizeof(uint32_t));
in.read((char *)&start, sizeof(uint32_t));
in.read((char *)&file_frozen_pts, sizeof(size_t));
return file_frozen_pts;
}
#endif
#ifdef EXEC_ENV_OLS
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_graph(AlignedFileReader &reader, size_t expected_num_points)
{
#else
template <typename T, typename TagT, typename LabelT>
size_t Index<T, TagT, LabelT>::load_graph(std::string filename, size_t expected_num_points)
{
#endif
auto res = _graph_store->load(filename, expected_num_points);
_start = std::get<1>(res);
_num_frozen_pts = std::get<2>(res);
return std::get<0>(res);
}
template <typename T, typename TagT, typename LabelT>
int Index<T, TagT, LabelT>::_get_vector_by_tag(TagType &tag, DataType &vec)
{
try
{
TagT tag_val = std::any_cast<TagT>(tag);
T *vec_val = std::any_cast<T *>(vec);
return this->get_vector_by_tag(tag_val, vec_val);
}
catch (const std::bad_any_cast &e)
{
throw ANNException("Error: bad any cast while performing _get_vector_by_tags() " + std::string(e.what()), -1);
}
catch (const std::exception &e)
{
throw ANNException("Error: " + std::string(e.what()), -1);
}
}
template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::get_vector_by_tag(TagT &tag, T *vec)
{
std::shared_lock<std::shared_timed_mutex> lock(_tag_lock);
if (_tag_to_location.find(tag) == _tag_to_location.end())
{
diskann::cout << "Tag " << get_tag_string(tag) << " does not exist" << std::endl;
return -1;
}
location_t location = _tag_to_location[tag];
_data_store->get_vector(location, vec);
return 0;
}
template <typename T, typename TagT, typename LabelT> uint32_t Index<T, TagT, LabelT>::calculate_entry_point()
{
// REFACTOR TODO: This function does not support multi-threaded calculation of medoid.
// Must revisit if perf is a concern.
return _data_store->calculate_medoid();
}
template <typename T, typename TagT, typename LabelT> std::vector<uint32_t> Index<T, TagT, LabelT>::get_init_ids()
{
std::vector<uint32_t> init_ids;
init_ids.reserve(1 + _num_frozen_pts);
init_ids.emplace_back(_start);
for (uint32_t frozen = (uint32_t)_max_points; frozen < _max_points + _num_frozen_pts; frozen++)
{
if (frozen != _start)
{
init_ids.emplace_back(frozen);
}
}
return init_ids;
}
// Find common filter between a node's labels and a given set of labels, while
// taking into account universal label
template <typename T, typename TagT, typename LabelT>
bool Index<T, TagT, LabelT>::detect_common_filters(uint32_t point_id, bool search_invocation,
const std::vector<LabelT> &incoming_labels)
{
auto &curr_node_labels = _location_to_labels[point_id];
std::vector<LabelT> common_filters;
std::set_intersection(incoming_labels.begin(), incoming_labels.end(), curr_node_labels.begin(),
curr_node_labels.end(), std::back_inserter(common_filters));
if (common_filters.size() > 0)
{
// This is to reduce the repetitive calls. If common_filters size is > 0 ,
// we dont need to check further for universal label
return true;
}
if (_use_universal_label)
{
if (!search_invocation)
{
if (std::find(incoming_labels.begin(), incoming_labels.end(), _universal_label) != incoming_labels.end() ||
std::find(curr_node_labels.begin(), curr_node_labels.end(), _universal_label) != curr_node_labels.end())
common_filters.push_back(_universal_label);
}
else
{
if (std::find(curr_node_labels.begin(), curr_node_labels.end(), _universal_label) != curr_node_labels.end())
common_filters.push_back(_universal_label);
}
}
return (common_filters.size() > 0);
}
template <typename T, typename TagT, typename LabelT>
std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::iterate_to_fixed_point(
InMemQueryScratch<T> *scratch, const uint32_t Lsize, const std::vector<uint32_t> &init_ids, bool use_filter,
const std::vector<LabelT> &filter_labels, bool search_invocation)
{
std::vector<Neighbor> &expanded_nodes = scratch->pool();
NeighborPriorityQueue &best_L_nodes = scratch->best_l_nodes();
best_L_nodes.reserve(Lsize);
tsl::robin_set<uint32_t> &inserted_into_pool_rs = scratch->inserted_into_pool_rs();
boost::dynamic_bitset<> &inserted_into_pool_bs = scratch->inserted_into_pool_bs();
std::vector<uint32_t> &id_scratch = scratch->id_scratch();
std::vector<float> &dist_scratch = scratch->dist_scratch();
assert(id_scratch.size() == 0);
T *aligned_query = scratch->aligned_query();
std::vector<std::uint64_t>& query_bitmask_buf = scratch->query_label_bitmask();
float *pq_dists = nullptr;
_pq_data_store->preprocess_query(aligned_query, scratch);
if (expanded_nodes.size() > 0 || id_scratch.size() > 0)
{
throw ANNException("ERROR: Clear scratch space before passing.", -1, __FUNCSIG__, __FILE__, __LINE__);
}
// Decide whether to use bitset or robin set to mark visited nodes
auto total_num_points = _max_points + _num_frozen_pts;
bool fast_iterate = total_num_points <= MAX_POINTS_FOR_USING_BITSET;
if (fast_iterate)
{
if (inserted_into_pool_bs.size() < total_num_points)
{
// hopefully using 2X will reduce the number of allocations.
auto resize_size =
2 * total_num_points > MAX_POINTS_FOR_USING_BITSET ? MAX_POINTS_FOR_USING_BITSET : 2 * total_num_points;
inserted_into_pool_bs.resize(resize_size);
}
}
// Lambda to determine if a node has been visited
auto is_not_visited = [this, fast_iterate, &inserted_into_pool_bs, &inserted_into_pool_rs](const uint32_t id) {
return fast_iterate ? inserted_into_pool_bs[id] == 0
: inserted_into_pool_rs.find(id) == inserted_into_pool_rs.end();
};
// Lambda to batch compute query<-> node distances in PQ space
auto compute_dists = [this, scratch, pq_dists](const std::vector<uint32_t> &ids, std::vector<float> &dists_out) {
_pq_data_store->get_distance(scratch->aligned_query(), ids, dists_out, scratch);
};
// only support one filter label
std::array<std::uint64_t, 10> local_buf;
simple_bitmask_full_val bitmask_full_val;
if (use_filter)
{
if (_bitmask_buf._bitmask_size <= 10)
{
local_buf.fill(0);
bitmask_full_val._mask = local_buf.data();
}
else
{
query_bitmask_buf.resize(_bitmask_buf._bitmask_size, 0);
bitmask_full_val._mask = query_bitmask_buf.data();
}
for (size_t i = 0; i < filter_labels.size(); i++)
{
auto bitmask_val = simple_bitmask::get_bitmask_val(filter_labels[i]);
bitmask_full_val.merge_bitmask_val(bitmask_val);
}
if (_use_universal_label)
{
auto bitmask_val = simple_bitmask::get_bitmask_val(_universal_label);
bitmask_full_val.merge_bitmask_val(bitmask_val);
}
}
// Initialize the candidate pool with starting points
for (auto id : init_ids)
{
if (id >= _max_points + _num_frozen_pts)
{
diskann::cerr << "Out of range loc found as an edge : " << id << std::endl;
throw diskann::ANNException(std::string("Wrong loc") + std::to_string(id), -1, __FUNCSIG__, __FILE__,
__LINE__);
}
if (use_filter)
{
simple_bitmask bm(_bitmask_buf.get_bitmask(id), _bitmask_buf._bitmask_size);
if (!bm.test_full_mask_val(bitmask_full_val))
{
continue;
}
}
if (is_not_visited(id))
{
if (fast_iterate)
{
inserted_into_pool_bs[id] = 1;
}
else
{
inserted_into_pool_rs.insert(id);
}
float distance;
uint32_t ids[] = {id};
float distances[] = {std::numeric_limits<float>::max()};
_pq_data_store->get_distance(aligned_query, ids, 1, distances, scratch);
distance = distances[0];
Neighbor nn = Neighbor(id, distance);
best_L_nodes.insert(nn);
}
}
uint32_t hops = 0;
uint32_t cmps = 0;
cmps += static_cast<uint32_t>(init_ids.size());
std::vector<location_t> tmp_neighbor_list;
while (best_L_nodes.has_unexpanded_node())
{
auto nbr = best_L_nodes.closest_unexpanded();
auto n = nbr.id;
// Add node to expanded nodes to create pool for prune later
if (!search_invocation)
{
if (!use_filter)
{
expanded_nodes.emplace_back(nbr);
}
else
{ // in filter based indexing, the same point might invoke
// multiple iterate_to_fixed_points, so need to be careful
// not to add the same item to pool multiple times.
if (std::find(expanded_nodes.begin(), expanded_nodes.end(), nbr) == expanded_nodes.end())
{
expanded_nodes.emplace_back(nbr);
}
}
}
// Find which of the nodes in des have not been visited before
id_scratch.clear();
dist_scratch.clear();
if (_dynamic_index)
{
LockGuard guard(_locks[n]);
auto neighbour_list = _graph_store->get_neighbours(n);
for (auto id : neighbour_list)
{
assert(id < _max_points + _num_frozen_pts);
if (!is_not_visited(id))
{
continue;
}
cmps++;
if (use_filter)
{
// NOTE: NEED TO CHECK IF THIS CORRECT WITH NEW LOCKS.
simple_bitmask bm(_bitmask_buf.get_bitmask(id), _bitmask_buf._bitmask_size);
if (!bm.test_full_mask_val(bitmask_full_val))
{
continue;
}
}
id_scratch.push_back(id);
}
}
else
{
tmp_neighbor_list.clear();
_locks[n].lock_shared();
auto nbrs = _graph_store->get_neighbours(n);
tmp_neighbor_list.resize(nbrs.size());
memcpy(tmp_neighbor_list.data(), nbrs.data(), nbrs.size() * sizeof(location_t));