-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathhgraph_build.cpp
More file actions
1726 lines (1626 loc) · 75 KB
/
hgraph_build.cpp
File metadata and controls
1726 lines (1626 loc) · 75 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
// Copyright 2024-present the vsag project
//
// 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.
#include <cxxabi.h>
#include <fmt/core.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <fstream>
#include <future>
#include <iosfwd>
#include <limits>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "algorithm/hgraph/hgraph_cache.h"
#include "algorithm/hgraph/hgraph_parameter.h"
#include "algorithm/inner_index_interface.h"
#include "basic_types.h"
#include "common.h"
#include "container_types.h"
#include "data_type.h"
#include "datacell/attribute_inverted_interface.h"
#include "datacell/extra_info_interface.h"
#include "datacell/flatten_datacell_parameter.h"
#include "datacell/flatten_interface.h"
#include "datacell/graph_interface.h"
#include "hash_types.h"
#include "hgraph.h" // IWYU pragma: keep
#include "impl/basic_optimizer.h"
#include "impl/heap/distance_heap.h"
#include "impl/heap/standard_heap.h"
#include "impl/inner_search_param.h"
#include "impl/label_table/label_table.h"
#include "impl/logger/logger.h"
#include "impl/odescent/odescent_graph_builder.h"
#include "impl/odescent/odescent_graph_parameter.h"
#include "impl/pruning_strategy.h"
#include "impl/reorder/flatten_reorder.h"
#include "impl/reorder/reorder.h"
#include "impl/runtime_parameter.h"
#include "impl/searcher/basic_searcher.h"
#include "impl/thread_pool/safe_thread_pool.h"
#include "index_common_param.h"
#include "index_feature_list.h"
#include "inner_string_params.h"
#include "io/io_parameter.h"
#include "io/memory_io_parameter.h"
#include "metric_type.h"
#include "quantization/quantizer_parameter.h"
#include "quantization/scalar_quantization/scalar_quantizer_parameter.h"
#include "storage/stream_reader.h"
#include "storage/stream_writer.h"
#include "tsl/robin_hash.h"
#include "tsl/robin_map.h"
#include "tsl/robin_set.h"
#include "utils/lock_strategy.h"
#include "utils/util_functions.h"
#include "utils/visited_list.h"
#include "vsag/attribute.h"
#include "vsag/constants.h"
#include "vsag/dataset.h"
#include "vsag/index.h"
#include "vsag/index_features.h"
namespace vsag {
class Allocator;
class IteratorFilterContext;
struct QueryContext;
static FlattenInterfacePtr
make_temporary_sq8_flatten(MetricType metric,
DataTypes data_type,
int64_t dim,
int64_t extra_info_size,
const std::shared_ptr<SafeThreadPool>& thread_pool,
Allocator* allocator) {
auto sq8_param = std::make_shared<FlattenDataCellParameter>();
sq8_param->quantizer_parameter = std::make_shared<ScalarQuantizerParameter<8>>();
sq8_param->io_parameter = std::make_shared<MemoryIOParameter>();
IndexCommonParam common_param;
common_param.metric_ = metric;
common_param.data_type_ = data_type;
common_param.dim_ = dim;
common_param.extra_info_size_ = extra_info_size;
common_param.thread_pool_ = thread_pool;
common_param.allocator_ = std::shared_ptr<Allocator>(allocator, [](Allocator*) {});
return FlattenInterface::MakeInstance(sq8_param, common_param);
}
static bool
need_temporary_sq8_build_data(const FlattenInterfacePtr& basic_flatten_codes,
bool has_precise_reorder) {
return not has_precise_reorder and
basic_flatten_codes->GetQuantizerName() == QUANTIZATION_TYPE_VALUE_RABITQ;
}
void
HGraph::Train(const DatasetPtr& base) {
int64_t total_elements = base->GetNumElements();
int64_t dim = base->GetDim();
DatasetPtr train_data =
vsag::sample_train_data(base, total_elements, dim, train_sample_count_, allocator_);
const auto* data_ptr = get_data(train_data);
this->basic_flatten_codes_->Train(data_ptr, train_data->GetNumElements());
if (has_precise_reorder()) {
this->high_precise_codes_->Train(data_ptr, train_data->GetNumElements());
}
if (create_new_raw_vector_) {
// nothing to do since raw_vector_ is fp32
this->raw_vector_->Train(data_ptr, train_data->GetNumElements());
}
}
std::vector<int64_t>
HGraph::Build(const DatasetPtr& data) {
CHECK_ARGUMENT(GetNumElements() == 0, "index is not empty");
if (this->has_loaded_cache()) {
// A previously exported cache has been imported via ImportCache().
// Take the accelerated build path that warm-starts neighbours from
// the cache and refines them, instead of building from scratch.
auto ret = this->build_with_cache(data);
if (use_elp_optimizer_) {
elp_optimize();
}
return ret;
}
this->Train(data);
std::vector<int64_t> ret;
if (graph_type_ == GRAPH_TYPE_VALUE_NSW) {
ret = this->Add(data);
} else {
ret = this->build_by_odescent(data);
}
if (use_elp_optimizer_) {
elp_optimize();
}
return ret;
}
std::vector<int64_t>
HGraph::build_by_odescent(const DatasetPtr& data) {
std::vector<int64_t> failed_ids;
auto total = data->GetNumElements();
const auto* labels = data->GetIds();
const auto* vectors = data->GetFloat32Vectors();
const auto* extra_infos = data->GetExtraInfos();
const auto* source_id = data->GetSourceID();
Vector<int64_t> valid_indices(allocator_);
UnorderedSet<LabelType> seen_labels(allocator_);
for (int64_t i = 0; i < total; ++i) {
auto label = labels[i];
if (this->label_table_->CheckLabel(label) or seen_labels.find(label) != seen_labels.end()) {
failed_ids.emplace_back(label);
continue;
}
seen_labels.insert(label);
valid_indices.emplace_back(i);
}
auto inner_ids = this->get_unique_inner_ids(static_cast<InnerIdType>(valid_indices.size()));
auto current_count = total_count_.load();
uint64_t new_ids_count = 0;
for (auto inner_id : inner_ids) {
if (inner_id >= current_count) {
++new_ids_count;
}
}
this->resize(current_count + new_ids_count);
this->total_count_ += new_ids_count;
Vector<Vector<InnerIdType>> route_graph_ids(allocator_);
auto need_sq8_build_data =
need_temporary_sq8_build_data(this->basic_flatten_codes_, this->has_precise_reorder());
FlattenInterfacePtr temporary_sq8_build_data = nullptr;
if (need_sq8_build_data and raw_vector_ == nullptr) {
temporary_sq8_build_data =
make_temporary_sq8_flatten(this->metric_,
this->data_type_,
this->dim_,
static_cast<int64_t>(this->extra_info_size_),
this->thread_pool_,
this->allocator_);
temporary_sq8_build_data->Train(vectors, total);
}
bool defer_persistent_codes = temporary_sq8_build_data != nullptr;
if (not defer_persistent_codes) {
this->Train(data);
}
Vector<std::pair<InnerIdType, int64_t>> deferred_code_ids(allocator_);
for (InnerIdType cur_size = 0; cur_size < valid_indices.size(); ++cur_size) {
auto i = valid_indices[cur_size];
auto label = labels[i];
InnerIdType inner_id = inner_ids.at(cur_size);
this->label_table_->Insert(inner_id, label);
// Persist source_id alongside label so day2 ExportCache produces a
// non-empty source_id_table_. Same array-indexing semantics as Add().
if (source_id != nullptr && not source_id[i].empty()) {
this->label_table_->InsertSourceId(inner_id, source_id[i]);
}
if (not defer_persistent_codes) {
this->insert_persistent_codes(vectors + dim_ * i, inner_id);
} else {
deferred_code_ids.emplace_back(inner_id, i);
}
if (temporary_sq8_build_data != nullptr) {
temporary_sq8_build_data->InsertVector(vectors + dim_ * i, inner_id);
}
auto level = this->get_random_level() - 1;
if (level >= 0) {
if (level >= static_cast<int>(route_graph_ids.size()) || route_graph_ids.empty()) {
for (auto k = static_cast<int>(route_graph_ids.size()); k <= level; ++k) {
route_graph_ids.emplace_back(allocator_);
}
entry_point_id_ = inner_id;
}
for (int j = 0; j <= level; ++j) {
route_graph_ids[j].emplace_back(inner_id);
}
}
}
auto build_data = (has_precise_reorder() and not build_by_base_) ? this->high_precise_codes_
: this->basic_flatten_codes_;
if (need_sq8_build_data) {
build_data = raw_vector_ != nullptr ? raw_vector_ : temporary_sq8_build_data;
}
{
odescent_param_->max_degree = bottom_graph_->MaximumDegree();
ODescent odescent_builder(
odescent_param_, build_data, allocator_, this->thread_pool_.get());
odescent_builder.Build();
odescent_builder.SaveGraph(bottom_graph_);
}
for (auto& route_graph_id : route_graph_ids) {
odescent_param_->max_degree = bottom_graph_->MaximumDegree() / 2;
ODescent sparse_odescent_builder(
odescent_param_, build_data, allocator_, this->thread_pool_.get());
auto graph = this->generate_one_route_graph();
sparse_odescent_builder.Build(route_graph_id);
sparse_odescent_builder.SaveGraph(graph);
this->route_graphs_.emplace_back(graph);
}
if (defer_persistent_codes) {
build_data.reset();
temporary_sq8_build_data.reset();
this->Train(data);
for (const auto& [inner_id, local_idx] : deferred_code_ids) {
this->insert_persistent_codes(vectors + dim_ * local_idx, inner_id);
}
}
return failed_ids;
}
std::vector<int64_t>
HGraph::Add(const DatasetPtr& data, AddMode mode) {
std::shared_lock<std::shared_mutex> force_remove_rlock;
if (this->support_force_remove()) {
force_remove_rlock = std::shared_lock<std::shared_mutex>(this->force_remove_mutex_);
}
std::vector<int64_t> failed_ids;
auto base_dim = data->GetDim();
if (data_type_ != DataTypes::DATA_TYPE_SPARSE) {
CHECK_ARGUMENT(base_dim == dim_,
fmt::format("base.dim({}) must be equal to index.dim({})", base_dim, dim_));
}
CHECK_ARGUMENT(get_data(data) != nullptr, "base.float_vector is nullptr");
auto need_sq8_build_data =
need_temporary_sq8_build_data(this->basic_flatten_codes_, this->has_precise_reorder());
CHECK_ARGUMENT(not(need_sq8_build_data and this->total_count_ != 0 and
raw_vector_ == nullptr and temporary_build_flatten_codes_ == nullptr),
"adding to a non-empty HGraph that needs temporary SQ8 build data requires "
"raw vectors");
bool created_temporary_build_data = false;
if (need_sq8_build_data and this->total_count_ == 0 and raw_vector_ == nullptr and
temporary_build_flatten_codes_ == nullptr) {
temporary_build_flatten_codes_ =
make_temporary_sq8_flatten(this->metric_,
this->data_type_,
this->dim_,
static_cast<int64_t>(this->extra_info_size_),
this->thread_pool_,
this->allocator_);
temporary_build_flatten_codes_->Train(get_data(data), data->GetNumElements());
created_temporary_build_data = true;
}
struct temporary_build_flatten_guard {
HGraph* hgraph;
bool enabled;
~temporary_build_flatten_guard() {
if (enabled) {
hgraph->temporary_build_flatten_codes_.reset();
}
}
} temporary_build_flatten_guard_instance{this, created_temporary_build_data};
bool defer_persistent_codes = created_temporary_build_data;
{
std::scoped_lock lock(this->add_mutex_);
if (this->total_count_ == 0 and not defer_persistent_codes) {
this->Train(data);
}
}
auto add_func = [&](const void* data,
int level,
InnerIdType inner_id,
const char* extra_info,
const AttributeSet* attrs) -> void {
if (this->extra_infos_ != nullptr) {
this->extra_infos_->InsertExtraInfo(extra_info, inner_id);
}
if (attrs != nullptr and this->use_attribute_filter_) {
this->attr_filter_index_->Insert(*attrs, inner_id);
}
this->add_one_point(data, level, inner_id, not defer_persistent_codes);
};
std::vector<std::future<void>> futures;
auto total = data->GetNumElements();
const auto* labels = data->GetIds();
const auto* source_id = data->GetSourceID();
const auto* extra_infos = data->GetExtraInfos();
const auto* attr_sets = data->GetAttributeSets();
bool use_parallel_add = this->thread_pool_ != nullptr;
Vector<std::pair<InnerIdType, LabelType>> inner_ids(allocator_);
for (int64_t j = 0; j < total; ++j) {
// Check if label already exists (skip removed IDs)
{
std::shared_lock label_lock(this->label_lookup_mutex_);
auto [found, _] = this->label_table_->TryGetIdByLabel(labels[j]);
if (found) {
failed_ids.emplace_back(labels[j]);
continue;
}
}
InnerIdType inner_id;
{
std::scoped_lock lock(this->add_mutex_);
inner_id = this->get_unique_inner_ids(1).at(0);
if (inner_id >= total_count_) {
this->resize(total_count_.load() + 1);
++total_count_;
}
}
{
std::scoped_lock label_lock(this->label_lookup_mutex_);
this->label_table_->Insert(inner_id, labels[j]);
// NOTE: Dataset::GetSourceID() returns a pointer to an array of N
// source_id strings (one per row), matching the semantics already
// used by build_with_cache() at line ~1234. Use array indexing
// instead of dereferencing the head pointer.
if (source_id != nullptr && not source_id[j].empty()) {
this->label_table_->InsertSourceId(inner_id, source_id[j]);
}
inner_ids.emplace_back(inner_id, j);
}
}
if (temporary_build_flatten_codes_ != nullptr) {
for (const auto& [inner_id, local_idx] : inner_ids) {
temporary_build_flatten_codes_->InsertVector(get_data(data, local_idx), inner_id);
}
}
for (auto& [inner_id, local_idx] : inner_ids) {
int level;
{
std::scoped_lock label_lock(this->label_lookup_mutex_);
level = this->get_random_level() - 1;
}
const auto* extra_info = extra_infos + local_idx * extra_info_size_;
const AttributeSet* cur_attr_set = nullptr;
if (attr_sets != nullptr) {
cur_attr_set = attr_sets + local_idx;
}
if (use_parallel_add) {
auto future = this->thread_pool_->GeneralEnqueue(
add_func, get_data(data, local_idx), level, inner_id, extra_info, cur_attr_set);
futures.emplace_back(std::move(future));
} else {
add_func(get_data(data, local_idx), level, inner_id, extra_info, cur_attr_set);
}
}
if (use_parallel_add) {
for (auto& future : futures) {
future.get();
}
}
if (defer_persistent_codes) {
temporary_build_flatten_codes_.reset();
{
std::scoped_lock lock(this->add_mutex_);
this->Train(data);
}
futures.clear();
for (const auto& id_pair : inner_ids) {
auto inner_id = id_pair.first;
auto local_idx = id_pair.second;
if (use_parallel_add) {
auto future =
this->thread_pool_->GeneralEnqueue([this, data, inner_id, local_idx]() {
this->insert_persistent_codes(get_data(data, local_idx), inner_id);
});
futures.emplace_back(std::move(future));
} else {
this->insert_persistent_codes(get_data(data, local_idx), inner_id);
}
}
if (use_parallel_add) {
for (auto& future : futures) {
future.get();
}
}
}
return failed_ids;
}
void
HGraph::add_one_point(const void* data, int level, InnerIdType inner_id) {
this->add_one_point(data, level, inner_id, true);
}
void
HGraph::insert_persistent_codes(const void* data, InnerIdType inner_id) {
std::shared_lock<std::shared_mutex> add_lock;
if (not this->support_force_remove()) {
add_lock = std::shared_lock<std::shared_mutex>(this->add_mutex_);
}
this->basic_flatten_codes_->InsertVector(data, inner_id);
if (has_precise_reorder()) {
this->high_precise_codes_->InsertVector(data, inner_id);
}
if (create_new_raw_vector_) {
raw_vector_->InsertVector(data, inner_id);
}
}
void
HGraph::add_one_point(const void* data, int level, InnerIdType inner_id, bool insert_codes) {
std::unique_lock<std::shared_mutex> add_lock(this->add_mutex_, std::defer_lock);
if (this->support_force_remove()) {
add_lock.lock();
}
if (insert_codes) {
this->insert_persistent_codes(data, inner_id);
}
if (not this->support_force_remove()) {
add_lock.lock();
}
if (level >= static_cast<int>(this->route_graphs_.size()) || bottom_graph_->TotalCount() == 0) {
std::scoped_lock<std::shared_mutex> wlock(this->global_mutex_);
// level maybe a negative number(-1)
for (auto j = static_cast<int>(this->route_graphs_.size()); j <= level; ++j) {
this->route_graphs_.emplace_back(this->generate_one_route_graph());
}
auto insert_success = this->graph_add_one(data, level, inner_id);
if (insert_success) {
entry_point_id_ = inner_id;
} else {
this->route_graphs_.pop_back();
}
add_lock.unlock();
} else {
add_lock.unlock();
std::shared_lock rlock(this->global_mutex_);
this->graph_add_one(data, level, inner_id);
}
}
bool
HGraph::graph_add_one(const void* data, int level, InnerIdType inner_id) {
DistHeapPtr result = nullptr;
InnerSearchParam param;
param.topk = 1;
param.ep = this->entry_point_id_;
param.ef = 1;
param.is_inner_id_allowed = nullptr;
auto flatten_codes = basic_flatten_codes_;
if (temporary_build_flatten_codes_ != nullptr) {
flatten_codes = temporary_build_flatten_codes_;
} else if (need_temporary_sq8_build_data(this->basic_flatten_codes_,
this->has_precise_reorder()) and
raw_vector_ != nullptr) {
flatten_codes = raw_vector_;
} else if (has_precise_reorder() and not build_by_base_) {
flatten_codes = high_precise_codes_;
}
for (auto j = this->route_graphs_.size() - 1; j > level; --j) {
result = search_one_graph(
data, route_graphs_[j], flatten_codes, param, (VisitedListPtr) nullptr, nullptr);
param.ep = result->Top().second;
}
param.ef = this->ef_construct_;
param.topk = static_cast<int64_t>(ef_construct_);
if (this->support_duplicate_) {
param.find_duplicate = true;
param.duplicate_query_id = inner_id;
param.duplicate_distance_threshold = this->duplicate_distance_threshold_;
}
if (bottom_graph_->TotalCount() != 0) {
result = search_one_graph(data,
this->bottom_graph_,
flatten_codes,
param,
// to specify which overloaded function to call
(VisitedListPtr) nullptr,
nullptr);
if (this->support_duplicate_ && param.duplicate_id >= 0) {
std::unique_lock lock(this->label_lookup_mutex_);
bottom_graph_->SetDuplicateId(static_cast<InnerIdType>(param.duplicate_id), inner_id);
return false;
}
auto filtered_result = std::make_shared<StandardHeap<true, false>>(allocator_, -1);
while (not result->Empty()) {
auto [dist, id] = result->Top();
result->Pop();
if (id != inner_id) {
filtered_result->Push(dist, id);
}
}
LockGuard cur_lock(neighbors_mutex_, inner_id);
mutually_connect_new_element(inner_id,
filtered_result,
this->bottom_graph_,
flatten_codes,
neighbors_mutex_,
allocator_,
alpha_);
} else {
LockGuard cur_lock(neighbors_mutex_, inner_id);
bottom_graph_->InsertNeighborsById(inner_id, Vector<InnerIdType>(allocator_));
}
for (int64_t j = 0; j <= level; ++j) {
if (route_graphs_[j]->TotalCount() != 0) {
result = search_one_graph(data,
route_graphs_[j],
flatten_codes,
param,
// to specify which overloaded function to call
(VisitedListPtr) nullptr,
nullptr);
auto filtered_result = std::make_shared<StandardHeap<true, false>>(allocator_, -1);
while (not result->Empty()) {
auto [dist, id] = result->Top();
result->Pop();
if (id != inner_id) {
filtered_result->Push(dist, id);
}
}
LockGuard cur_lock(neighbors_mutex_, inner_id);
mutually_connect_new_element(inner_id,
filtered_result,
route_graphs_[j],
flatten_codes,
neighbors_mutex_,
allocator_,
alpha_);
} else {
LockGuard cur_lock(neighbors_mutex_, inner_id);
route_graphs_[j]->InsertNeighborsById(inner_id, Vector<InnerIdType>(allocator_));
}
}
return true;
}
void
HGraph::resize(uint64_t new_size) {
auto cur_size = this->max_capacity_.load();
uint64_t new_size_power_2 =
next_multiple_of_power_of_two(new_size, this->resize_increase_count_bit_);
if (cur_size >= new_size_power_2) {
return;
}
std::scoped_lock lock(this->global_mutex_);
cur_size = this->max_capacity_.load();
if (cur_size < new_size_power_2) {
this->neighbors_mutex_->Resize(new_size_power_2);
pool_ = std::make_shared<VisitedListPool>(1, allocator_, new_size_power_2, allocator_);
this->label_table_->Resize(new_size_power_2);
bottom_graph_->Resize(new_size_power_2);
this->basic_flatten_codes_->Resize(new_size_power_2);
if (has_precise_reorder()) {
this->high_precise_codes_->Resize(new_size_power_2);
}
if (create_new_raw_vector_) {
this->raw_vector_->Resize(new_size_power_2);
}
if (this->extra_infos_ != nullptr) {
this->extra_infos_->Resize(new_size_power_2);
}
this->max_capacity_.store(new_size_power_2);
this->cal_memory_usage();
}
}
void
HGraph::InitFeatures() {
// Common Init
// Build & Add
this->index_feature_list_->SetFeatures({
IndexFeature::SUPPORT_BUILD,
IndexFeature::SUPPORT_BUILD_WITH_MULTI_THREAD,
IndexFeature::SUPPORT_ADD_AFTER_BUILD,
IndexFeature::SUPPORT_MERGE_INDEX,
});
// search
this->index_feature_list_->SetFeatures({
IndexFeature::SUPPORT_KNN_SEARCH,
IndexFeature::SUPPORT_KNN_SEARCH_WITH_ID_FILTER,
IndexFeature::SUPPORT_KNN_ITERATOR_FILTER_SEARCH,
});
// update
if (data_type_ != DataTypes::DATA_TYPE_SPARSE) {
this->index_feature_list_->SetFeatures({IndexFeature::SUPPORT_UPDATE_VECTOR_CONCURRENT});
}
this->index_feature_list_->SetFeatures({IndexFeature::SUPPORT_UPDATE_ID_CONCURRENT});
// concurrency
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_SEARCH_CONCURRENT);
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_ADD_CONCURRENT);
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_ADD_SEARCH_CONCURRENT);
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_ADD_SEARCH_DELETE_CONCURRENT);
// serialize
this->index_feature_list_->SetFeatures({
IndexFeature::SUPPORT_DESERIALIZE_BINARY_SET,
IndexFeature::SUPPORT_DESERIALIZE_FILE,
IndexFeature::SUPPORT_DESERIALIZE_READER_SET,
IndexFeature::SUPPORT_SERIALIZE_BINARY_SET,
IndexFeature::SUPPORT_SERIALIZE_FILE,
IndexFeature::SUPPORT_SERIALIZE_WRITE_FUNC,
});
// other
this->index_feature_list_->SetFeatures({IndexFeature::SUPPORT_ESTIMATE_MEMORY,
IndexFeature::SUPPORT_GET_MEMORY_USAGE,
IndexFeature::SUPPORT_CHECK_ID_EXIST,
IndexFeature::SUPPORT_CLONE,
IndexFeature::SUPPORT_EXPORT_MODEL,
IndexFeature::SUPPORT_TUNE});
// About Train
auto name = this->basic_flatten_codes_->GetQuantizerName();
if (name != QUANTIZATION_TYPE_VALUE_FP32 and name != QUANTIZATION_TYPE_VALUE_BF16 and
name != QUANTIZATION_TYPE_VALUE_FP16) {
this->index_feature_list_->SetFeature(IndexFeature::NEED_TRAIN);
} else {
this->index_feature_list_->SetFeatures({
IndexFeature::SUPPORT_RANGE_SEARCH,
IndexFeature::SUPPORT_RANGE_SEARCH_WITH_ID_FILTER,
});
}
bool have_fp32 = false;
bool hold_molds = false;
if (name == QUANTIZATION_TYPE_VALUE_FP32) {
have_fp32 = true;
hold_molds |= this->basic_flatten_codes_->HoldMolds();
}
if (has_precise_reorder() and not ignore_reorder_ and
this->high_precise_codes_->GetQuantizerName() == QUANTIZATION_TYPE_VALUE_FP32) {
have_fp32 = true;
hold_molds |= this->high_precise_codes_->HoldMolds();
}
if (have_fp32) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_CAL_DISTANCE_BY_ID);
if (metric_ != MetricType::METRIC_TYPE_COSINE || hold_molds) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_GET_RAW_VECTOR_BY_IDS);
}
}
if (raw_vector_ != nullptr) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_GET_RAW_VECTOR_BY_IDS);
}
// metric
if (metric_ == MetricType::METRIC_TYPE_IP) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_METRIC_TYPE_INNER_PRODUCT);
} else if (metric_ == MetricType::METRIC_TYPE_L2SQR) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_METRIC_TYPE_L2);
} else if (metric_ == MetricType::METRIC_TYPE_COSINE) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_METRIC_TYPE_COSINE);
}
if (this->extra_infos_ != nullptr) {
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_GET_EXTRA_INFO_BY_ID);
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_KNN_SEARCH_WITH_EX_FILTER);
this->index_feature_list_->SetFeature(IndexFeature::SUPPORT_UPDATE_EXTRA_INFO_CONCURRENT);
}
}
void
HGraph::elp_optimize() {
InnerSearchParam param;
param.ep = 0;
param.ef = 80;
param.topk = 10;
param.is_inner_id_allowed = nullptr;
searcher_->SetMockParameters(bottom_graph_, basic_flatten_codes_, pool_, param, dim_);
// TODO(ZXY): optimize PREFETCH_DEPTH_CODE and add default value for the others
optimizer_->RegisterParameter(RuntimeParameter(PREFETCH_STRIDE_CODE, 1, 10, 1));
optimizer_->RegisterParameter(RuntimeParameter(PREFETCH_STRIDE_VISIT, 1, 10, 1));
optimizer_->Optimize(searcher_);
}
void
HGraph::reorder(const void* query,
const FlattenInterfacePtr& flatten,
DistHeapPtr& candidate_heap,
int64_t k,
IteratorFilterContext* iter_ctx,
QueryContext& ctx,
const DistanceRecordVector* rabitq_lower_bound_candidates) const {
uint64_t size = candidate_heap->Size();
if (k <= 0) {
k = static_cast<int64_t>(size);
}
auto reorder_impl = reorder_;
if (reorder_impl == nullptr) {
reorder_impl = std::make_shared<FlattenReorder>(flatten, allocator_);
}
auto reorder_heap = reorder_impl->Reorder(candidate_heap,
static_cast<const float*>(query),
k,
ctx,
iter_ctx,
rabitq_lower_bound_candidates);
candidate_heap = reorder_heap;
}
void
HGraph::ExportCache(std::ostream& out_stream) const {
IOStreamWriter writer(out_stream);
this->fullfill_cache();
this->cache_->Serialize(writer);
}
void
HGraph::ImportCache(std::istream& in_stream) {
IOStreamReader reader(in_stream);
this->cache_->Deserialize(reader);
}
void
HGraph::fullfill_cache() const {
auto& source_ids = this->cache_->source_ids_;
auto& source_cache_map = this->cache_->neighbors_;
source_ids.clear();
source_cache_map.clear();
source_ids.reserve(this->total_count_);
Vector<InnerIdType> inner_id_list(allocator_);
for (InnerIdType inner_id = 0; inner_id < this->total_count_; ++inner_id) {
auto source_id = this->label_table_->GetSourceId(inner_id);
source_ids.push_back(source_id);
if (source_id.empty()) {
continue;
}
auto [it, _] = source_cache_map.try_emplace(source_id, Vector<InnerIdType>(allocator_));
auto& cached = it.value();
cached.push_back(inner_id);
inner_id_list.clear();
this->bottom_graph_->GetNeighbors(inner_id, inner_id_list);
cached.insert(cached.end(), inner_id_list.begin(), inner_id_list.end());
}
}
namespace {
uint64_t
build_cache_now_us() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
}
constexpr uint32_t HIT_REFINE_ROUNDS = 1;
// MISSED side requires >=3 rounds: cold-start nodes (no warm seed) need
// multiple sweeps to (a) discover neighbors via search, (b) install reverse
// edges into hit-node adjacency lists, and (c) re-search with the newly
// populated frontier. Bisection on the miss-only smoke test
// (ef_construction=50, 200 vectors) shows ROUNDS<=2 fails REQUIRE(found_self);
// ROUNDS=3 passes consistently. Upstream uses 4; we keep 3 to bound cost.
constexpr uint32_t MISSED_REFINE_ROUNDS = 3;
// refine ef tuned down from ef_construct_ (=300/400) to 64 to avoid the
// pathological hit_refine bottleneck where each node spends 308us re-exploring
// the bottom graph with ef=300 (10092s total for 32.96M nodes, 1.73x slower
// than full rebuild). With ef=64, expected per-node ~60us (5x faster).
// Reference gby BuildCacheOptions default for hit_refine_ef is also 64.
constexpr uint32_t HIT_REFINE_EF = 64;
// MISSED_REFINE_EF kept higher than HIT because missed nodes have NO seed
// neighbors and need wider exploration. User-directed asymmetric config.
constexpr uint32_t MISSED_REFINE_EF = 200;
} // namespace
DistHeapPtr
HGraph::collect_refine_candidates(const DatasetPtr& data,
InnerIdType inner_id,
uint32_t input_idx,
const FlattenInterfacePtr& flatten_codes,
uint32_t refine_ef,
bool use_self_as_entry) const {
const uint32_t effective_refine_ef = refine_ef == 0 ? this->ef_construct_ : refine_ef;
CHECK_ARGUMENT(effective_refine_ef > 0, "refine ef must be greater than 0");
auto candidates = std::make_shared<StandardHeap<true, false>>(allocator_, -1);
std::unordered_set<InnerIdType> seen;
Vector<InnerIdType> current_neighbors(allocator_);
this->bottom_graph_->GetNeighbors(inner_id, current_neighbors);
seen.reserve(current_neighbors.size() + effective_refine_ef);
// Optimisation #2: replace the per-neighbour ComputePairVectors loop with
// a single batched flatten->Query call. The original code looped 64 times
// (max_degree per node) and each call paid for a separate query-vector
// load + distance kernel invocation; with N nodes refined we performed
// N*64 scalar distance computations. The batched path uses
// FactoryComputer(query) once and then asks the flatten cell to fill an
// array of N distances in one shot, which lets the underlying SIMD /
// prefetching code amortise the query load across all neighbours. Bit
// equivalence with the scalar path is preserved because Query() is the
// canonical primitive that ComputePairVectors itself delegates to.
if (not current_neighbors.empty()) {
// De-duplicate against `seen` and skip self-loops before issuing the
// batched Query so we never spend SIMD cycles on rows we will discard.
Vector<InnerIdType> filtered_ids(allocator_);
filtered_ids.reserve(current_neighbors.size());
for (const auto neighbor : current_neighbors) {
if (neighbor == inner_id || not seen.emplace(neighbor).second) {
continue;
}
filtered_ids.push_back(neighbor);
}
if (not filtered_ids.empty()) {
auto computer = flatten_codes->FactoryComputer(get_data(data, input_idx));
Vector<float> filtered_dists(filtered_ids.size(), allocator_);
flatten_codes->Query(filtered_dists.data(),
computer,
filtered_ids.data(),
static_cast<InnerIdType>(filtered_ids.size()),
nullptr);
for (uint64_t k = 0; k < filtered_ids.size(); ++k) {
candidates->Push(filtered_dists[k], filtered_ids[k]);
}
}
}
if (this->entry_point_id_ != INVALID_ENTRY_POINT && this->bottom_graph_->TotalCount() > 0) {
// For cache-hit nodes, start the search from inner_id itself so the
// warm-started stale neighbours act as the initial frontier and refine
// exploits the local neighbourhood efficiently. For cache-missed /
// cold-start nodes, use the global entry point for broad exploration.
// When the node has no cached neighbours, self-entry is meaningless,
// so fall back to the global entry point.
const auto search_entry_point =
(use_self_as_entry && not current_neighbors.empty()) ? inner_id : this->entry_point_id_;
InnerSearchParam param;
param.topk = static_cast<int64_t>(effective_refine_ef);
param.ef = effective_refine_ef;
param.ep = search_entry_point;
param.is_inner_id_allowed = nullptr;
auto result = this->search_one_graph(get_data(data, input_idx),
this->bottom_graph_,
flatten_codes,
param,
(VisitedListPtr) nullptr,
nullptr);
// Optimisation #1: reuse the (dist, inner_id) records produced by
// search_one_graph instead of recomputing the same distance via
// ComputePairVectors. The searcher already computed dist(query, id)
// for every node it visited; the heap returned here stores those
// exact (dist, id) pairs. Re-running ComputePairVectors would do the
// same fp32 kernel call a second time for every candidate (~64 per
// node for hit_refine, ~400 for missed_refine), which dominates the
// candidate-collection cost. Dropping the recompute is bit-equivalent:
// both paths go through flatten_codes->ComputePairVectors with the
// same query and same inner_ids.
while (not result->Empty()) {
auto candidate = result->Top();
const InnerIdType candidate_id = candidate.second;
if (candidate_id == inner_id || not seen.emplace(candidate_id).second) {
result->Pop();
continue;
}
candidates->Push(candidate.first, candidate.second);
result->Pop();
}
}
return candidates;
}
void
HGraph::select_refine_neighbors_with_distances(const DatasetPtr& data,
InnerIdType inner_id,
uint32_t input_idx,
const FlattenInterfacePtr& flatten_codes,
uint32_t refine_ef,
bool use_self_as_entry,
Vector<InnerIdType>& out_neighbors,
Vector<float>& out_distances) const {
out_neighbors.clear();
out_distances.clear();
auto candidates = this->collect_refine_candidates(
data, inner_id, input_idx, flatten_codes, refine_ef, use_self_as_entry);
if (candidates->Empty()) {
return;
}
const uint64_t max_size = this->bottom_graph_->MaximumDegree();
select_edges_by_heuristic(candidates, max_size, flatten_codes, allocator_, this->alpha_);
out_neighbors.reserve(candidates->Size());
out_distances.reserve(candidates->Size());
while (not candidates->Empty()) {
out_neighbors.emplace_back(candidates->Top().second);
out_distances.emplace_back(candidates->Top().first);
candidates->Pop();
}
}
void
HGraph::refine_nodes_two_phase(
const DatasetPtr& data,
const std::vector<InnerIdType>& ids_to_refine,
std::string_view phase_name,
uint32_t rounds,
uint32_t refine_ef,
bool use_self_as_entry,
const FlattenInterfacePtr& flatten_codes,
const std::unordered_map<InnerIdType, uint32_t>& inner_id_to_input_idx) {
if (ids_to_refine.empty() || rounds == 0) {
return;
}
uint32_t parallelism = 1;
if (this->thread_pool_ != nullptr && this->build_thread_count_ > 1 &&
ids_to_refine.size() > 1) {
parallelism = std::min<uint32_t>(static_cast<uint32_t>(this->build_thread_count_),
static_cast<uint32_t>(ids_to_refine.size()));
}
const uint32_t effective_refine_ef = refine_ef == 0 ? this->ef_construct_ : refine_ef;
CHECK_ARGUMENT(effective_refine_ef > 0, "refine ef must be greater than 0");
logger::info("[hgraph_build_cache] starting {} nodes={} rounds={} parallelism={}",
phase_name,
ids_to_refine.size(),
rounds,
parallelism);
constexpr int64_t block_size = 128;
const auto begin = build_cache_now_us();
for (uint32_t round = 0; round < rounds; ++round) {
const auto round_begin = build_cache_now_us();
// ===== Phase 1: parallel search & local select (also keep distances) =====
Vector<Vector<InnerIdType>> selected_neighbors(
ids_to_refine.size(), Vector<InnerIdType>(allocator_), allocator_);
Vector<Vector<float>> selected_distances(
ids_to_refine.size(), Vector<float>(allocator_), allocator_);
if (parallelism <= 1) {
for (uint64_t i = 0; i < ids_to_refine.size(); ++i) {
const auto inner_id = ids_to_refine[i];
auto data_iter = inner_id_to_input_idx.find(inner_id);
CHECK_ARGUMENT(data_iter != inner_id_to_input_idx.end(),
fmt::format("missing input row for inner_id {}", inner_id));
this->select_refine_neighbors_with_distances(data,
inner_id,