-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathhnswalg.h
1519 lines (1299 loc) · 52.1 KB
/
hnswalg.h
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
/*-
* -\-\-
* voyager
* --
* Copyright (C) 2016 - 2023 Spotify AB
*
* This file is heavily based on hnswlib (https://github.com/nmslib/hnswlib,
* Apache 2.0-licensed, no copyright author listed)
* --
* 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 "Spaces/Space.h"
#include "hnswlib.h"
#include "visited_list_pool.h"
#include <assert.h>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <list>
#include <random>
#include <shared_mutex>
#include <stdlib.h>
#include <unordered_map>
#include <unordered_set>
class IndexCannotBeShrunkError : public std::runtime_error {
public:
IndexCannotBeShrunkError(const std::string &what)
: std::runtime_error(what) {}
};
class IndexFullError : public std::runtime_error {
public:
IndexFullError(const std::string &what) : std::runtime_error(what) {}
};
namespace hnswlib {
typedef unsigned int tableint;
typedef unsigned int linklistsizeint;
template <typename dist_t, typename data_t = dist_t>
class HierarchicalNSW : public AlgorithmInterface<dist_t, data_t> {
public:
static const tableint max_update_element_locks = 65536;
HierarchicalNSW(Space<dist_t, data_t> *s,
std::shared_ptr<InputStream> inputStream,
size_t max_elements = 0, bool search_only = false)
: search_only_(search_only) {
loadIndex(inputStream, s, max_elements);
}
HierarchicalNSW(Space<dist_t, data_t> *s, size_t max_elements, size_t M = 16,
size_t ef_construction = 200, size_t random_seed = 100)
: link_list_locks_(max_elements),
link_list_update_locks_(max_update_element_locks),
element_levels_(max_elements) {
max_elements_ = max_elements;
num_deleted_ = 0;
data_size_ = s->get_data_size();
fstdistfunc_ = s->get_dist_func();
dist_func_param_ = s->get_dist_func_param();
M_ = M;
maxM_ = M_;
maxM0_ = M_ * 2;
ef_construction_ = std::max(ef_construction, M_);
ef_ = 10;
level_generator_.seed(random_seed);
update_probability_generator_.seed(random_seed + 1);
size_links_level0_ = maxM0_ * sizeof(tableint) + sizeof(linklistsizeint);
size_data_per_element_ =
size_links_level0_ + data_size_ + sizeof(labeltype);
offsetData_ = size_links_level0_;
label_offset_ = size_links_level0_ + data_size_;
offsetLevel0_ = 0;
data_level0_memory_ =
(char *)malloc(max_elements_ * size_data_per_element_);
if (data_level0_memory_ == nullptr)
throw std::runtime_error("Not enough memory");
cur_element_count = 0;
visited_list_pool_ = new VisitedListPool(1, max_elements);
// initializations for special treatment of the first node
enterpoint_node_ = -1;
maxlevel_ = -1;
linkLists_ = (char **)malloc(sizeof(void *) * max_elements_);
if (linkLists_ == nullptr)
throw std::runtime_error(
"Not enough memory: HierarchicalNSW failed to allocate linklists");
size_links_per_element_ =
maxM_ * sizeof(tableint) + sizeof(linklistsizeint);
mult_ = 1 / log(1.0 * M_);
revSize_ = 1.0 / mult_;
}
struct CompareByFirst {
constexpr bool
operator()(std::pair<dist_t, tableint> const &a,
std::pair<dist_t, tableint> const &b) const noexcept {
return a.first < b.first;
}
};
~HierarchicalNSW() {
free(data_level0_memory_);
for (tableint i = 0; i < cur_element_count; i++) {
if (element_levels_[i] > 0)
free(linkLists_[i]);
}
free(linkLists_);
delete visited_list_pool_;
}
size_t max_elements_;
size_t cur_element_count;
size_t size_data_per_element_;
size_t size_links_per_element_;
size_t num_deleted_;
size_t M_;
size_t maxM_;
size_t maxM0_;
size_t ef_construction_;
double mult_, revSize_;
int maxlevel_;
std::shared_mutex resizeLock;
VisitedListPool *visited_list_pool_;
std::mutex cur_element_count_guard_;
std::vector<std::mutex> link_list_locks_;
// Locks to prevent race condition during update/insert of an element at same
// time. Note: Locks for additions can also be used to prevent this race
// condition if the querying of KNN is not exposed along with update/inserts
// i.e multithread insert/update/query in parallel.
std::vector<std::mutex> link_list_update_locks_;
tableint enterpoint_node_;
size_t size_links_level0_;
size_t offsetData_, offsetLevel0_;
char *data_level0_memory_;
char **linkLists_;
std::vector<int> element_levels_;
size_t data_size_;
bool search_only_ = false;
size_t label_offset_;
DISTFUNC<dist_t, data_t> fstdistfunc_;
size_t dist_func_param_;
std::unordered_map<labeltype, tableint> label_lookup_;
std::default_random_engine level_generator_;
std::default_random_engine update_probability_generator_;
inline labeltype getExternalLabel(tableint internal_id) const {
labeltype return_label;
memcpy(&return_label,
(data_level0_memory_ + internal_id * size_data_per_element_ +
label_offset_),
sizeof(labeltype));
return return_label;
}
inline void setExternalLabel(tableint internal_id, labeltype label) const {
memcpy((data_level0_memory_ + internal_id * size_data_per_element_ +
label_offset_),
&label, sizeof(labeltype));
}
inline labeltype *getExternalLabeLp(tableint internal_id) const {
return (labeltype *)(data_level0_memory_ +
internal_id * size_data_per_element_ + label_offset_);
}
inline data_t *getDataByInternalId(tableint internal_id) const {
return reinterpret_cast<data_t *>(data_level0_memory_ +
internal_id * size_data_per_element_ +
offsetData_);
}
int getRandomLevel(double reverse_size) {
std::uniform_real_distribution<double> distribution(0.0, 1.0);
double r = -log(distribution(level_generator_)) * reverse_size;
return (int)r;
}
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>, CompareByFirst>
searchBaseLayer(tableint ep_id, const data_t *data_point, int layer,
VisitedList *vl = nullptr) {
bool wasPassedVisitedList = vl != nullptr;
if (!wasPassedVisitedList) {
vl = visited_list_pool_->getFreeVisitedList();
} else {
vl->reset();
}
vl_type *visited_array = vl->mass;
vl_type visited_array_tag = vl->curV;
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst>
top_candidates;
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst>
candidateSet;
dist_t lowerBound;
if (!isMarkedDeleted(ep_id)) {
dist_t dist = fstdistfunc_(data_point, getDataByInternalId(ep_id),
dist_func_param_);
top_candidates.emplace(dist, ep_id);
lowerBound = dist;
candidateSet.emplace(-dist, ep_id);
} else {
lowerBound = std::numeric_limits<dist_t>::max();
candidateSet.emplace(-lowerBound, ep_id);
}
visited_array[ep_id] = visited_array_tag;
while (!candidateSet.empty()) {
std::pair<dist_t, tableint> curr_el_pair = candidateSet.top();
if ((-curr_el_pair.first) > lowerBound &&
top_candidates.size() == ef_construction_) {
break;
}
candidateSet.pop();
tableint curNodeNum = curr_el_pair.second;
std::unique_lock<std::mutex> lock(link_list_locks_[curNodeNum]);
int *data; // = (int *)(linkList0_ + curNodeNum *
// size_links_per_element0_);
if (layer == 0) {
data = (int *)get_linklist0(curNodeNum);
} else {
data = (int *)get_linklist(curNodeNum, layer);
// data = (int *) (linkLists_[curNodeNum] + (layer -
// 1) * size_links_per_element_);
}
size_t size = getListCount((linklistsizeint *)data);
tableint *datal = (tableint *)(data + 1);
for (size_t j = 0; j < size; j++) {
tableint candidate_id = *(datal + j);
// if (candidate_id == 0) continue;
if (visited_array[candidate_id] == visited_array_tag)
continue;
visited_array[candidate_id] = visited_array_tag;
data_t *currObj1 = getDataByInternalId(candidate_id);
dist_t dist1 = fstdistfunc_(data_point, currObj1, dist_func_param_);
if (top_candidates.size() < ef_construction_ || lowerBound > dist1) {
candidateSet.emplace(-dist1, candidate_id);
if (!isMarkedDeleted(candidate_id))
top_candidates.emplace(dist1, candidate_id);
if (top_candidates.size() > ef_construction_)
top_candidates.pop();
if (!top_candidates.empty())
lowerBound = top_candidates.top().first;
}
}
}
if (!wasPassedVisitedList) {
visited_list_pool_->releaseVisitedList(vl);
}
return top_candidates;
}
mutable std::atomic<long> metric_distance_computations;
mutable std::atomic<long> metric_hops;
template <bool has_deletions, bool collect_metrics = false>
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>, CompareByFirst>
searchBaseLayerST(tableint ep_id, const data_t *data_point, size_t ef,
VisitedList *vl = nullptr) const {
bool wasPassedVisitedList = vl != nullptr;
if (!wasPassedVisitedList) {
vl = visited_list_pool_->getFreeVisitedList();
} else {
vl->reset();
}
vl_type *visited_array = vl->mass;
vl_type visited_array_tag = vl->curV;
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst>
top_candidates;
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst>
candidate_set;
dist_t lowerBound;
if (!has_deletions || !isMarkedDeleted(ep_id)) {
dist_t dist = fstdistfunc_(data_point, getDataByInternalId(ep_id),
dist_func_param_);
lowerBound = dist;
top_candidates.emplace(dist, ep_id);
candidate_set.emplace(-dist, ep_id);
} else {
lowerBound = std::numeric_limits<dist_t>::max();
candidate_set.emplace(-lowerBound, ep_id);
}
visited_array[ep_id] = visited_array_tag;
while (!candidate_set.empty()) {
std::pair<dist_t, tableint> current_node_pair = candidate_set.top();
if ((-current_node_pair.first) > lowerBound &&
(top_candidates.size() == ef || has_deletions == false)) {
break;
}
candidate_set.pop();
tableint current_node_id = current_node_pair.second;
int *data = (int *)get_linklist0(current_node_id);
size_t size = getListCount((linklistsizeint *)data);
// bool cur_node_deleted =
// isMarkedDeleted(current_node_id);
if (collect_metrics) {
metric_hops++;
metric_distance_computations += size;
}
for (size_t j = 1; j <= size; j++) {
int candidate_id = *(data + j);
// if (candidate_id == 0) continue;
if (!(visited_array[candidate_id] == visited_array_tag)) {
visited_array[candidate_id] = visited_array_tag;
data_t *currObj1 = (getDataByInternalId(candidate_id));
dist_t dist = fstdistfunc_(data_point, currObj1, dist_func_param_);
if (top_candidates.size() < ef || lowerBound > dist) {
candidate_set.emplace(-dist, candidate_id);
if (!has_deletions || !isMarkedDeleted(candidate_id))
top_candidates.emplace(dist, candidate_id);
if (top_candidates.size() > ef)
top_candidates.pop();
if (!top_candidates.empty())
lowerBound = top_candidates.top().first;
}
}
}
}
if (!wasPassedVisitedList) {
visited_list_pool_->releaseVisitedList(vl);
}
return top_candidates;
}
void getNeighborsByHeuristic2(
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst> &top_candidates,
const size_t M) {
if (top_candidates.size() < M) {
return;
}
std::priority_queue<std::pair<dist_t, tableint>> queue_closest;
std::vector<std::pair<dist_t, tableint>> return_list;
while (top_candidates.size() > 0) {
queue_closest.emplace(-top_candidates.top().first,
top_candidates.top().second);
top_candidates.pop();
}
while (queue_closest.size()) {
if (return_list.size() >= M)
break;
std::pair<dist_t, tableint> curent_pair = queue_closest.top();
dist_t dist_to_query = -curent_pair.first;
queue_closest.pop();
bool good = true;
for (std::pair<dist_t, tableint> second_pair : return_list) {
dist_t curdist = fstdistfunc_(getDataByInternalId(second_pair.second),
getDataByInternalId(curent_pair.second),
dist_func_param_);
;
if (curdist < dist_to_query) {
good = false;
break;
}
}
if (good) {
return_list.push_back(curent_pair);
}
}
for (std::pair<dist_t, tableint> curent_pair : return_list) {
top_candidates.emplace(-curent_pair.first, curent_pair.second);
}
}
linklistsizeint *get_linklist0(tableint internal_id) const {
return (linklistsizeint *)(data_level0_memory_ +
internal_id * size_data_per_element_ +
offsetLevel0_);
};
linklistsizeint *get_linklist0(tableint internal_id,
char *data_level0_memory_) const {
return (linklistsizeint *)(data_level0_memory_ +
internal_id * size_data_per_element_ +
offsetLevel0_);
};
linklistsizeint *get_linklist(tableint internal_id, int level) const {
return (linklistsizeint *)(linkLists_[internal_id] +
(level - 1) * size_links_per_element_);
};
linklistsizeint *get_linklist_at_level(tableint internal_id,
int level) const {
return level == 0 ? get_linklist0(internal_id)
: get_linklist(internal_id, level);
};
tableint mutuallyConnectNewElement(
const data_t *data_point, tableint cur_c,
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst> &top_candidates,
int level, bool isUpdate) {
size_t Mcurmax = level ? maxM_ : maxM0_;
getNeighborsByHeuristic2(top_candidates, M_);
if (top_candidates.size() > M_)
throw std::runtime_error(
"Should be not be more than M_ candidates returned by the heuristic");
std::vector<tableint> selectedNeighbors;
selectedNeighbors.reserve(M_);
while (top_candidates.size() > 0) {
selectedNeighbors.push_back(top_candidates.top().second);
top_candidates.pop();
}
tableint next_closest_entry_point = selectedNeighbors.back();
{
linklistsizeint *ll_cur;
if (level == 0)
ll_cur = get_linklist0(cur_c);
else
ll_cur = get_linklist(cur_c, level);
if (*ll_cur && !isUpdate) {
throw std::runtime_error(
"The newly inserted element should have blank link list");
}
setListCount(ll_cur, selectedNeighbors.size());
tableint *data = (tableint *)(ll_cur + 1);
for (size_t idx = 0; idx < selectedNeighbors.size(); idx++) {
if (data[idx] && !isUpdate)
throw std::runtime_error("Possible memory corruption");
if (level > element_levels_[selectedNeighbors[idx]])
throw std::runtime_error(
"Trying to make a link on a non-existent level");
data[idx] = selectedNeighbors[idx];
}
}
for (size_t idx = 0; idx < selectedNeighbors.size(); idx++) {
std::unique_lock<std::mutex> lock(
link_list_locks_[selectedNeighbors[idx]]);
linklistsizeint *ll_other;
if (level == 0)
ll_other = get_linklist0(selectedNeighbors[idx]);
else
ll_other = get_linklist(selectedNeighbors[idx], level);
size_t sz_link_list_other = getListCount(ll_other);
if (sz_link_list_other > Mcurmax)
throw std::runtime_error("Bad value of sz_link_list_other");
if (selectedNeighbors[idx] == cur_c)
throw std::runtime_error("Trying to connect an element to itself");
if (level > element_levels_[selectedNeighbors[idx]])
throw std::runtime_error(
"Trying to make a link on a non-existent level");
tableint *data = (tableint *)(ll_other + 1);
bool is_cur_c_present = false;
if (isUpdate) {
for (size_t j = 0; j < sz_link_list_other; j++) {
if (data[j] == cur_c) {
is_cur_c_present = true;
break;
}
}
}
// If cur_c is already present in the neighboring connections of
// `selectedNeighbors[idx]` then no need to modify any connections or run
// the heuristics.
if (!is_cur_c_present) {
if (sz_link_list_other < Mcurmax) {
data[sz_link_list_other] = cur_c;
setListCount(ll_other, sz_link_list_other + 1);
} else {
// finding the "weakest" element to replace it with the new one
dist_t d_max = fstdistfunc_(
getDataByInternalId(cur_c),
getDataByInternalId(selectedNeighbors[idx]), dist_func_param_);
// Heuristic:
std::priority_queue<std::pair<dist_t, tableint>,
std::vector<std::pair<dist_t, tableint>>,
CompareByFirst>
candidates;
candidates.emplace(d_max, cur_c);
for (size_t j = 0; j < sz_link_list_other; j++) {
candidates.emplace(
fstdistfunc_(getDataByInternalId(data[j]),
getDataByInternalId(selectedNeighbors[idx]),
dist_func_param_),
data[j]);
}
getNeighborsByHeuristic2(candidates, Mcurmax);
int indx = 0;
while (candidates.size() > 0) {
data[indx] = candidates.top().second;
candidates.pop();
indx++;
}
setListCount(ll_other, indx);
// Nearest K:
/*int indx = -1;
for (int j = 0; j < sz_link_list_other; j++) {
dist_t d = fstdistfunc_(getDataByInternalId(data[j]),
getDataByInternalId(rez[idx]), dist_func_param_); if (d > d_max) {
indx = j;
d_max = d;
}
}
if (indx >= 0) {
data[indx] = cur_c;
} */
}
}
}
return next_closest_entry_point;
}
std::mutex global;
size_t ef_;
void setEf(size_t ef) { ef_ = ef; }
std::priority_queue<std::pair<dist_t, tableint>>
searchKnnInternal(data_t *query_data, int k, VisitedList *vl = nullptr) {
std::priority_queue<std::pair<dist_t, tableint>> top_candidates;
if (cur_element_count == 0)
return top_candidates;
tableint currObj = enterpoint_node_;
dist_t curdist = fstdistfunc_(
query_data, getDataByInternalId(enterpoint_node_), dist_func_param_);
for (size_t level = maxlevel_; level > 0; level--) {
bool changed = true;
while (changed) {
changed = false;
int *data;
data = (int *)get_linklist(currObj, level);
int size = getListCount(data);
tableint *datal = (tableint *)(data + 1);
for (int i = 0; i < size; i++) {
tableint cand = datal[i];
if (cand < 0 || cand > max_elements_)
throw std::runtime_error("cand error");
dist_t d = fstdistfunc_(query_data, getDataByInternalId(cand),
dist_func_param_);
if (d < curdist) {
curdist = d;
currObj = cand;
changed = true;
}
}
}
}
if (num_deleted_) {
std::priority_queue<std::pair<dist_t, tableint>> top_candidates1 =
searchBaseLayerST<true>(currObj, query_data, ef_, vl);
top_candidates.swap(top_candidates1);
} else {
std::priority_queue<std::pair<dist_t, tableint>> top_candidates1 =
searchBaseLayerST<false>(currObj, query_data, ef_, vl);
top_candidates.swap(top_candidates1);
}
while (top_candidates.size() > k) {
top_candidates.pop();
}
return top_candidates;
};
void resizeIndex(size_t new_max_elements) {
if (search_only_)
throw std::runtime_error(
"resizeIndex is not supported in search only mode");
std::unique_lock<std::shared_mutex> lock(resizeLock);
if (new_max_elements < cur_element_count)
throw IndexCannotBeShrunkError(
"Cannot resize to " + std::to_string(new_max_elements) +
" elements, as this index already contains " +
std::to_string(cur_element_count) + " elements.");
delete visited_list_pool_;
visited_list_pool_ = new VisitedListPool(1, new_max_elements);
element_levels_.resize(new_max_elements);
std::vector<std::mutex>(new_max_elements).swap(link_list_locks_);
// Reallocate base layer
char *data_level0_memory_new = (char *)realloc(
data_level0_memory_, new_max_elements * size_data_per_element_);
if (data_level0_memory_new == nullptr)
throw std::runtime_error(
"Not enough memory: resizeIndex failed to allocate base layer");
data_level0_memory_ = data_level0_memory_new;
// Reallocate all other layers
char **linkLists_new =
(char **)realloc(linkLists_, sizeof(void *) * new_max_elements);
if (linkLists_new == nullptr)
throw std::runtime_error(
"Not enough memory: resizeIndex failed to allocate other layers");
linkLists_ = linkLists_new;
max_elements_ = new_max_elements;
}
void saveIndex(const std::string &filename) {
saveIndex(std::make_shared<FileOutputStream>(filename));
}
void saveIndex(std::shared_ptr<OutputStream> output) {
writeBinaryPOD(output, offsetLevel0_);
writeBinaryPOD(output, max_elements_);
writeBinaryPOD(output, cur_element_count);
writeBinaryPOD(output, size_data_per_element_);
writeBinaryPOD(output, label_offset_);
writeBinaryPOD(output, offsetData_);
writeBinaryPOD(output, maxlevel_);
writeBinaryPOD(output, enterpoint_node_);
writeBinaryPOD(output, maxM_);
writeBinaryPOD(output, maxM0_);
writeBinaryPOD(output, M_);
writeBinaryPOD(output, mult_);
writeBinaryPOD(output, ef_construction_);
output->write(data_level0_memory_,
cur_element_count * size_data_per_element_);
for (size_t i = 0; i < cur_element_count; i++) {
unsigned int linkListSize =
element_levels_[i] > 0 ? size_links_per_element_ * element_levels_[i]
: 0;
writeBinaryPOD(output, linkListSize);
if (linkListSize)
output->write(linkLists_[i], linkListSize);
}
}
void loadIndex(std::shared_ptr<InputStream> inputStream,
Space<dist_t, data_t> *s, size_t max_elements_i = 0) {
size_t totalFileSize = 0;
if (inputStream->isSeekable()) {
totalFileSize = inputStream->getTotalLength();
}
readBinaryPOD(inputStream, offsetLevel0_);
if (totalFileSize > 0 && offsetLevel0_ > totalFileSize) {
throw std::domain_error("Index appears to contain corrupted data; level "
"0 offset parameter (" +
std::to_string(offsetLevel0_) +
") exceeded size of index file (" +
std::to_string(totalFileSize) + ").");
}
readBinaryPOD(inputStream, max_elements_);
readBinaryPOD(inputStream, cur_element_count);
size_t max_elements = max_elements_i;
if (max_elements < cur_element_count)
max_elements = max_elements_;
max_elements_ = max_elements;
readBinaryPOD(inputStream, size_data_per_element_);
readBinaryPOD(inputStream, label_offset_);
readBinaryPOD(inputStream, offsetData_);
readBinaryPOD(inputStream, maxlevel_);
readBinaryPOD(inputStream, enterpoint_node_);
if (enterpoint_node_ >= cur_element_count) {
throw std::runtime_error(
"Index seems to be corrupted or unsupported. "
"Entry point into HNSW data structure was at element index " +
std::to_string(enterpoint_node_) + ", but only " +
std::to_string(cur_element_count) +
" elements are present in the index.");
}
readBinaryPOD(inputStream, maxM_);
readBinaryPOD(inputStream, maxM0_);
readBinaryPOD(inputStream, M_);
readBinaryPOD(inputStream, mult_);
readBinaryPOD(inputStream, ef_construction_);
data_size_ = s->get_data_size();
fstdistfunc_ = s->get_dist_func();
dist_func_param_ = s->get_dist_func_param();
size_links_per_element_ =
maxM_ * sizeof(tableint) + sizeof(linklistsizeint);
size_links_level0_ = maxM0_ * sizeof(tableint) + sizeof(linklistsizeint);
size_t expected_size_per_element =
size_links_level0_ + data_size_ + sizeof(labeltype);
if (size_data_per_element_ != expected_size_per_element) {
throw std::domain_error(
"Storage data type does not match the index data being loaded; "
"expected " +
std::to_string(expected_size_per_element) +
" bytes per element, but loaded data contains " +
std::to_string(size_data_per_element_) +
" bytes per element. Data being loaded might not be a Voyager index, "
"may be corrupt, or may be using a different storage data type.");
}
long long position = inputStream->getPosition();
if (inputStream->isSeekable()) {
inputStream->advanceBy(cur_element_count * size_data_per_element_);
for (size_t i = 0; i < cur_element_count; i++) {
if (inputStream->getPosition() < 0 ||
inputStream->getPosition() >= (long long)totalFileSize) {
throw std::runtime_error(
"Index seems to be corrupted or unsupported. Seeked to " +
std::to_string(position +
(cur_element_count * size_data_per_element_) +
(sizeof(unsigned int) * i)) +
" bytes to read linked list, but resulting stream position was " +
std::to_string(inputStream->getPosition()) +
" (of total file size " + std::to_string(totalFileSize) +
" bytes).");
}
unsigned int linkListSize;
readBinaryPOD(inputStream, linkListSize);
if (linkListSize != 0) {
if ((size_t)inputStream->getPosition() + linkListSize >
totalFileSize) {
throw std::runtime_error(
"Index seems to be corrupted or unsupported. Advancing to the "
"next linked list requires " +
std::to_string(linkListSize) +
" additional bytes (from position " +
std::to_string(inputStream->getPosition()) +
"), but index data only has " + std::to_string(totalFileSize) +
" bytes in total.");
}
inputStream->advanceBy(linkListSize);
}
}
if (inputStream->getPosition() != (long long)totalFileSize)
throw std::runtime_error(
"Index seems to be corrupted or unsupported. After reading all "
"linked lists, extra data remained at the end of the index.");
inputStream->setPosition(position);
}
data_level0_memory_ = (char *)malloc(max_elements * size_data_per_element_);
if (data_level0_memory_ == nullptr) {
throw std::runtime_error(
"Not enough memory: loadIndex failed to allocate level0 (" +
std::to_string(max_elements * size_data_per_element_) + " bytes)");
}
{
size_t bytes_to_read = cur_element_count * size_data_per_element_;
size_t bytes_read = inputStream->read(data_level0_memory_, bytes_to_read);
if (bytes_read != bytes_to_read) {
throw std::runtime_error("Tried to read " +
std::to_string(bytes_to_read) +
" bytes from stream, but only received " +
std::to_string(bytes_read) + " bytes!");
}
}
linkLists_ = (char **)malloc(sizeof(void *) * max_elements);
if (linkLists_ == nullptr)
throw std::runtime_error(
"Not enough memory: loadIndex failed to allocate linklists (" +
std::to_string(sizeof(void *) * max_elements) + " bytes)");
size_t linkListBufferSize = sizeof(void *) * max_elements;
std::vector<char> linkListBuffer(linkListBufferSize);
{
size_t bytes_read = 0;
while (true) {
long long bytes_to_read = linkListBuffer.size() - bytes_read;
long long bytes_read_this_iteration = inputStream->read(
linkListBuffer.data() + bytes_read, bytes_to_read);
if (bytes_read_this_iteration > 0) {
bytes_read += bytes_read_this_iteration;
}
if (bytes_read_this_iteration == bytes_to_read) {
// The link list data will usually be smaller than the buffer we've
// allocated, but in case it's not, enlarge the buffer and keep
// reading:
try {
linkListBuffer.resize(linkListBuffer.size() * 2);
} catch (std::exception const &e) {
throw std::runtime_error(
"Failed to resize linked list buffer to "
"double its previous size (from " +
std::to_string(linkListBuffer.size()) + " to " +
std::to_string(linkListBuffer.size() * 2) + ")");
}
} else {
// We've hit the end of the stream (as we read fewer bytes than asked
// for) so stop reading.
try {
linkListBuffer.resize(bytes_read);
} catch (std::exception const &e) {
throw std::runtime_error("Failed to resize linked list buffer to "
"the number of bytes read (" +
std::to_string(bytes_read) + ")");
}
break;
}
}
}
if (!search_only_) {
std::vector<std::mutex>(max_elements).swap(link_list_locks_);
std::vector<std::mutex>(max_update_element_locks)
.swap(link_list_update_locks_);
}
visited_list_pool_ = new VisitedListPool(1, max_elements);
element_levels_ = std::vector<int>(max_elements);
revSize_ = 1.0 / mult_;
ef_ = 10;
size_t indexInLinkListBuffer = 0;
for (size_t i = 0; i < cur_element_count; i++) {
if (!search_only_)
label_lookup_[getExternalLabel(i)] = i;
unsigned int linkListSize;
linkListSize = *((int *)(linkListBuffer.data() + indexInLinkListBuffer));
indexInLinkListBuffer += sizeof(int);
if (linkListSize == 0) {
element_levels_[i] = 0;
linkLists_[i] = nullptr;
} else {
element_levels_[i] = linkListSize / size_links_per_element_;
linkLists_[i] = (char *)malloc(linkListSize);
if (linkLists_[i] == nullptr)
throw std::runtime_error(
"Not enough memory: loadIndex failed to allocate linklist");
std::memcpy(linkLists_[i],
(linkListBuffer.data() + indexInLinkListBuffer),
linkListSize);
indexInLinkListBuffer += linkListSize;
}
}
if (enterpoint_node_ > 0 && enterpoint_node_ != (tableint)-1 &&
!linkLists_[enterpoint_node_]) {
throw std::runtime_error(
"Index seems to be corrupted or unsupported. "
"Entry point into HNSW data structure was at element index " +
std::to_string(enterpoint_node_) +
", but no linked list was present at that index.");
}
for (size_t i = 0; i < cur_element_count; i++) {
if (isMarkedDeleted(i))
num_deleted_ += 1;
}
return;
}
size_t getDimensionality() { return dist_func_param_; }
std::vector<data_t> getDataByLabel(labeltype label) const {
if (search_only_)
throw std::runtime_error(
"getDataByLabel is not supported in search only mode");
tableint label_c;
auto search = label_lookup_.find(label);
if (search == label_lookup_.end() || isMarkedDeleted(search->second)) {
throw std::runtime_error("Label " + std::to_string(label) +
" not found in index.");
}
label_c = search->second;
data_t *data_ptr = getDataByInternalId(label_c);
size_t dim = dist_func_param_;
std::vector<data_t> data;
for (unsigned long i = 0; i < dim; i++) {
data.push_back(*data_ptr);
data_ptr += 1;
}
return data;
}
data_t *getRawDataPointerByLabel(labeltype label) {
tableint label_c;
auto search = label_lookup_.find(label);
if (search == label_lookup_.end() || isMarkedDeleted(search->second)) {
throw std::runtime_error("Label not found");
}
label_c = search->second;
return (data_t *)getDataByInternalId(label_c);
}
dist_t getDistanceByLabels(labeltype labelA, labeltype labelB) {
tableint internalIDA, internalIDB;
auto search = label_lookup_.find(labelA);
if (search == label_lookup_.end() || isMarkedDeleted(search->second)) {
throw std::runtime_error("Label not found");
}
internalIDA = search->second;