Repository navigation
Expand file tree
/
Copy pathquiver.rs
More file actions
4425 lines (4050 loc) · 153 KB
/
Copy pathquiver.rs
File metadata and controls
4425 lines (4050 loc) · 153 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
//! QuIVer — QUantized Index for Vector Retrieval
//!
//! BQ-native Vamana 图索引,论文核心实现。
//! 支持 rayon 并行批量构建(batch_build)。
//!
//! 核心架构:
//! - 2-bit Sign-Magnitude 量化 (pos + strong)
//! - Vamana α-diversity 剪枝构图
//! - 默认无训练SM-L2位运算导航 + 原始向量余弦精排
//!
//! 设计要点:
//! - Bitset visited: 可复用位向量,2.5KB/20K 节点
//! - Flat 邻接表: 连续内存,固定步长
//! - BQ 签名连续存储: SoA 布局,预取友好
use crate::index::bq::{Bq2Signature, Bq2Store};
use crate::vector::{
cosine_query_norm_f32_384, cosine_similarity_f32, cosine_similarity_f32_384_with_query_norm,
};
use rayon::prelude::*;
use std::cell::UnsafeCell;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
/// 默认SM-L2查询内核,以及可显式选择的校正与原生欧氏模式。
#[path = "quiver/corrected_sm.rs"]
pub mod corrected_sm;
mod connectivity;
#[cfg(test)]
mod connectivity_tests;
#[cfg(test)]
mod memory_safety_tests;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct NonNanF32(pub f32);
impl Eq for NonNanF32 {}
impl PartialOrd for NonNanF32 {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NonNanF32 {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0
.partial_cmp(&other.0)
.unwrap_or(std::cmp::Ordering::Equal)
}
}
/// 查询时导航评分器。评分越小,候选越优先;该抽象不参与 QuIVer 建图或裁边。
pub trait NavigationScorer {
fn score(&mut self, node_id: u64, bq_distance: u32) -> u32;
fn accept_result(&mut self, _node_id: u64) -> bool {
true
}
}
/// 与历史 QuIVer 查询完全等价的纯 BQ 导航评分器。
#[derive(Debug, Default, Clone, Copy)]
pub struct BqNavigationScorer;
impl NavigationScorer for BqNavigationScorer {
#[inline(always)]
fn score(&mut self, _node_id: u64, bq_distance: u32) -> u32 {
bq_distance
}
}
// ── Bitset ──
struct Bitset {
data: Vec<u64>,
len: usize,
}
impl Bitset {
fn new(n: usize) -> Self {
Self {
data: vec![0u64; n.div_ceil(64)],
len: n,
}
}
#[inline(always)]
fn set(&mut self, i: usize) {
self.data[i >> 6] |= 1u64 << (i & 63);
}
#[inline(always)]
fn test(&self, i: usize) -> bool {
(self.data[i >> 6] >> (i & 63)) & 1 != 0
}
fn clear(&mut self) {
self.data.iter_mut().for_each(|x| *x = 0);
}
fn grow(&mut self, new_n: usize) {
let need = new_n.div_ceil(64);
if need > self.data.len() {
self.data.resize(need, 0);
}
self.len = new_n;
}
}
struct SparseBitset {
data: Vec<u64>,
touched_words: Vec<usize>,
}
struct SearchScratch384 {
visited: SparseBitset,
candidates: BinaryHeap<Reverse<(NonNanF32, u32)>>,
results: BinaryHeap<(NonNanF32, u32)>,
vector: Vec<f32>,
scored: Vec<(f32, u32)>,
}
impl SearchScratch384 {
fn new() -> Self {
Self {
visited: SparseBitset::new(0),
candidates: BinaryHeap::new(),
results: BinaryHeap::new(),
vector: Vec::with_capacity(384),
scored: Vec::new(),
}
}
}
impl SparseBitset {
fn new(n: usize) -> Self {
Self {
data: vec![0; n.div_ceil(64)],
touched_words: Vec::new(),
}
}
fn begin(&mut self) {
for word in self.touched_words.drain(..) {
self.data[word] = 0;
}
}
#[inline(always)]
fn set(&mut self, index: usize) {
let word = index >> 6;
if self.data[word] == 0 {
self.touched_words.push(word);
}
self.data[word] |= 1u64 << (index & 63);
}
#[inline(always)]
fn test(&self, index: usize) -> bool {
(self.data[index >> 6] >> (index & 63)) & 1 != 0
}
fn grow(&mut self, new_n: usize) {
let words = new_n.div_ceil(64);
if words > self.data.len() {
self.data.resize(words, 0);
}
}
}
trait SearchVisited {
fn begin(&mut self);
fn set(&mut self, index: usize);
fn test(&self, index: usize) -> bool;
}
impl SearchVisited for Bitset {
fn begin(&mut self) {
self.clear();
}
fn set(&mut self, index: usize) {
self.set(index);
}
fn test(&self, index: usize) -> bool {
self.test(index)
}
}
impl SearchVisited for SparseBitset {
fn begin(&mut self) {
self.begin();
}
fn set(&mut self, index: usize) {
self.set(index);
}
fn test(&self, index: usize) -> bool {
self.test(index)
}
}
// ── Flat neighbor list ──
// Layer 0: 常规近邻按 m0 选择;既有双倍容量还可保留跨签名出口和导航树边。
// 每行存为 [degree, n0, n1, ...],stride = 2*m0+1。
// Upper layers: 用 Vec<Vec<u32>>(节点少,性能不敏感)
const EMPTY_NB: u32 = u32::MAX;
struct FlatAdj {
data: Vec<u32>, // n * stride 个 u32
stride: usize, // 每行元素数,第一个元素是度数
}
struct SpinLockGuard<'a> {
lock: &'a AtomicBool,
}
impl Drop for SpinLockGuard<'_> {
fn drop(&mut self) {
self.lock.store(false, Ordering::Release);
}
}
#[repr(transparent)]
struct NodeGuard<'a>((u32, SpinLockGuard<'a>));
impl NodeGuard<'_> {
#[inline(always)]
fn node(&self) -> u32 {
self.0.0
}
}
struct StripedSpinLocks {
locks: Vec<AtomicBool>,
mask: usize,
}
impl StripedSpinLocks {
fn new(nodes: usize, m: usize) -> Self {
// 96核时需要足够的条纹数减少争用;每核至少 256 条纹
let desired = nodes.clamp(256, 65536).max(m * 64);
let count = desired.next_power_of_two();
let locks = (0..count).map(|_| AtomicBool::new(false)).collect();
Self {
locks,
mask: count - 1,
}
}
#[inline(always)]
fn stripe(&self, node: u32) -> usize {
const FIB: usize = 0x9E3779B97F4A7C15usize;
(node as usize).wrapping_mul(FIB) & self.mask
}
#[inline(always)]
fn lock(&self, node: u32) -> NodeGuard<'_> {
let lock = &self.locks[self.stripe(node)];
while lock
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
std::hint::spin_loop();
}
NodeGuard((node, SpinLockGuard { lock }))
}
/// 计时版加锁:返回自旋等待耗时(ns),用于构图性能探针
#[inline(always)]
fn lock_timed(&self, node: u32) -> (NodeGuard<'_>, u64) {
let lock = &self.locks[self.stripe(node)];
let t0 = Instant::now();
let mut spun = false;
while lock
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
spun = true;
std::hint::spin_loop();
}
// 仅在确实自旋等待时计入耗时,避免无争用时 Instant 噪声主导
let wait = if spun {
t0.elapsed().as_nanos() as u64
} else {
0
};
(NodeGuard((node, SpinLockGuard { lock })), wait)
}
}
/// 构图性能探针:通过环境变量 TRIVIUM_BUILD_PROFILE=1 启用,默认零开销。
/// 分段累计纳秒,定位 spin-lock 弱扩展的真正主因。
struct BuildProfile {
enabled: bool,
bitset_ns: AtomicU64, // 每节点 Bitset 分配耗时
beam_ns: AtomicU64, // beam search 寻路耗时
fwd_ns: AtomicU64, // 前向候选准备+vamana_select+写自身边
rev_wait_ns: AtomicU64, // 反向剪枝的自旋锁等待耗时
rev_work_ns: AtomicU64, // 反向剪枝的锁内做活耗时(去掉等待)
nodes: AtomicU64, // 处理节点数
}
impl BuildProfile {
fn new() -> Self {
let enabled = std::env::var("TRIVIUM_BUILD_PROFILE").as_deref() == Ok("1");
Self {
enabled,
bitset_ns: AtomicU64::new(0),
beam_ns: AtomicU64::new(0),
fwd_ns: AtomicU64::new(0),
rev_wait_ns: AtomicU64::new(0),
rev_work_ns: AtomicU64::new(0),
nodes: AtomicU64::new(0),
}
}
#[inline(always)]
fn add(&self, counter: &AtomicU64, ns: u64) {
if self.enabled {
counter.fetch_add(ns, Ordering::Relaxed);
}
}
fn report(&self, wall_secs: f64, threads: usize) {
if !self.enabled {
return;
}
let nodes = self.nodes.load(Ordering::Relaxed).max(1);
let ms = |c: &AtomicU64| c.load(Ordering::Relaxed) as f64 / 1e6;
let per = |c: &AtomicU64| c.load(Ordering::Relaxed) as f64 / nodes as f64;
let total_cpu_ms = ms(&self.bitset_ns)
+ ms(&self.beam_ns)
+ ms(&self.fwd_ns)
+ ms(&self.rev_wait_ns)
+ ms(&self.rev_work_ns);
tracing::info!(
nodes,
threads,
wall_seconds = wall_secs,
total_cpu_ms,
"构图性能探针完成 (Graph build profiler completed)"
);
let line = |name: &str, c: &AtomicU64| {
let cpu_ms = ms(c);
let pct = if total_cpu_ms > 0.0 {
cpu_ms / total_cpu_ms * 100.0
} else {
0.0
};
tracing::info!(
stage = name,
cpu_ms,
percent = pct,
per_node_ns = per(c),
"构图阶段性能 (Graph build stage profile)"
);
};
line("Bitset分配/allocate", &self.bitset_ns);
line("束搜索寻路/beam search", &self.beam_ns);
line("前向选边/forward select", &self.fwd_ns);
line("反向剪枝锁等待/reverse wait", &self.rev_wait_ns);
line("反向剪枝工作/reverse work", &self.rev_work_ns);
}
}
impl FlatAdj {
fn new(stride: usize) -> Self {
Self {
data: Vec::new(),
stride,
}
}
/// 为新节点追加空邻居列表
fn push_empty(&mut self) {
self.data.push(0); // degree = 0
for _ in 1..self.stride {
self.data.push(EMPTY_NB);
}
}
#[inline(always)]
fn degree(&self, node: u32) -> usize {
self.data[node as usize * self.stride] as usize
}
#[inline(always)]
fn neighbors(&self, node: u32) -> &[u32] {
let base = node as usize * self.stride;
let deg = self.data[base] as usize;
&self.data[base + 1..base + 1 + deg]
}
/// 追加一条边(不检查重复,调用方保证)
fn push_neighbor(&mut self, node: u32, nb: u32) {
let base = node as usize * self.stride;
let deg = self.data[base] as usize;
if deg + 1 < self.stride {
self.data[base + 1 + deg] = nb;
self.data[base] = (deg + 1) as u32;
}
}
/// 替换整个邻居列表
fn set_neighbors(&mut self, node: u32, nbs: &[u32]) {
let base = node as usize * self.stride;
let count = nbs.len().min(self.stride - 1);
self.data[base] = count as u32;
for i in 0..count {
self.data[base + 1 + i] = nbs[i];
}
for i in count..(self.stride - 1) {
self.data[base + 1 + i] = EMPTY_NB;
}
}
fn contains(&self, node: u32, nb: u32) -> bool {
self.neighbors(node).contains(&nb)
}
fn reset_full(&mut self, nodes: usize) {
self.data.clear();
self.data.resize(nodes * self.stride, EMPTY_NB);
for node in 0..nodes {
self.data[node * self.stride] = 0;
}
}
}
// ── BQ-Vamana 图 ──
struct ConcurrentFlatAdj {
data: Box<[UnsafeCell<u32>]>,
stride: usize,
nodes: usize,
}
unsafe impl Sync for ConcurrentFlatAdj {}
impl ConcurrentFlatAdj {
fn new(nodes: usize, stride: usize) -> Self {
let len = nodes.checked_mul(stride).expect("并发邻接表容量溢出");
let mut data = Vec::with_capacity(len);
for i in 0..len {
let value = if i % stride == 0 { 0 } else { EMPTY_NB };
data.push(UnsafeCell::new(value));
}
Self {
data: data.into_boxed_slice(),
stride,
nodes,
}
}
#[inline(always)]
fn check_node(&self, node: u32) {
debug_assert!((node as usize) < self.nodes);
debug_assert!((node as usize + 1) * self.stride <= self.data.len());
}
fn neighbors_locked(&self, node: u32, locks: &StripedSpinLocks) -> Vec<u32> {
let guard = locks.lock(node);
self.neighbors_with_guard(&guard)
}
fn neighbors_raw(&self, node: u32) -> Vec<u32> {
self.check_node(node);
unsafe {
let base = node as usize * self.stride;
let deg = *self.data[base].get() as usize;
debug_assert!(deg < self.stride);
let mut out = Vec::with_capacity(deg);
for i in 0..deg.min(self.stride - 1) {
let nb = *self.data[base + 1 + i].get();
if nb != EMPTY_NB && (nb as usize) < self.nodes {
out.push(nb);
}
}
out
}
}
/// 邻接表单节点容量(不含度数槽)
#[inline(always)]
fn capacity(&self) -> usize {
self.stride - 1
}
/// 读取节点当前度数(需持锁调用,惰性剪枝用)
#[inline(always)]
fn degree_raw(&self, node: u32) -> usize {
self.check_node(node);
unsafe { (*self.data[node as usize * self.stride].get() as usize).min(self.stride - 1) }
}
/// 判断节点邻居中是否已含 nb(需持锁调用,惰性剪枝用)
fn contains_raw(&self, node: u32, nb: u32) -> bool {
self.check_node(node);
unsafe {
let base = node as usize * self.stride;
let deg = (*self.data[base].get() as usize).min(self.stride - 1);
for i in 0..deg {
if *self.data[base + 1 + i].get() == nb {
return true;
}
}
false
}
}
/// 追加一条边(不剪枝,调用方保证未满且无重复,需持锁调用)
#[inline(always)]
fn push_neighbor_raw(&self, node: u32, nb: u32) {
self.check_node(node);
unsafe {
let base = node as usize * self.stride;
let deg = *self.data[base].get() as usize;
if deg + 1 < self.stride {
*self.data[base + 1 + deg].get() = nb;
*self.data[base].get() = (deg + 1) as u32;
}
}
}
fn neighbors_with_guard(&self, guard: &NodeGuard<'_>) -> Vec<u32> {
self.neighbors_raw(guard.node())
}
fn set_neighbors_raw(&self, node: u32, nbs: &[u32]) {
self.check_node(node);
unsafe {
let base = node as usize * self.stride;
let count = nbs.len().min(self.stride - 1);
*self.data[base].get() = count as u32;
for i in 0..count {
debug_assert!((nbs[i] as usize) < self.nodes);
*self.data[base + 1 + i].get() = nbs[i];
}
for i in count..(self.stride - 1) {
*self.data[base + 1 + i].get() = EMPTY_NB;
}
}
}
fn set_neighbors_with_guard(&self, guard: &NodeGuard<'_>, nbs: &[u32]) {
self.set_neighbors_raw(guard.node(), nbs);
}
fn set_neighbors_locked(&self, node: u32, nbs: &[u32], locks: &StripedSpinLocks) {
let guard = locks.lock(node);
self.set_neighbors_with_guard(&guard, nbs);
}
fn set_neighbors_locked_fast(&self, node: u32, nbs: &[u32], locks: &StripedSpinLocks) {
let _guard = locks.lock(node);
self.set_neighbors_raw(node, nbs);
}
fn freeze_into_flat(self, dst: &mut FlatAdj) {
dst.data.clear();
dst.data.reserve(self.data.len());
for cell in self.data.iter() {
unsafe {
dst.data.push(*cell.get());
}
}
dst.stride = self.stride;
}
}
struct ExperimentalBuildView<'a> {
adj: &'a ConcurrentFlatAdj,
n: usize,
dim: usize,
m0: usize,
ef: usize,
alpha: f32,
sigs: &'a Bq2Store,
locks: &'a StripedSpinLocks,
profile: &'a BuildProfile,
/// 反向剪枝模式:true=旧的"每条边全量剪枝"(A/B对照用),false=惰性剪枝(默认)
eager: bool,
}
impl ExperimentalBuildView<'_> {
fn beam_search_l0_locked(
&self,
q_sig: &Bq2Signature,
entry: u32,
ef: usize,
visited: &mut Bitset,
) -> Vec<(NonNanF32, u32)> {
use std::cmp::Reverse;
use std::collections::BinaryHeap;
visited.clear();
let mut candidates: BinaryHeap<Reverse<(NonNanF32, u32)>> =
BinaryHeap::with_capacity(ef * 2);
let mut results: BinaryHeap<(NonNanF32, u32)> = BinaryHeap::with_capacity(ef + 1);
let d = NonNanF32(
self.sigs
.distance_to_sig_in_bounds(entry as usize, q_sig, self.dim) as f32,
);
visited.set(entry as usize);
candidates.push(Reverse((d, entry)));
results.push((d, entry));
while let Some(Reverse((cd, cur))) = candidates.pop() {
if results.len() >= ef && cd > results.peek().unwrap().0 {
break;
}
let nbs = self.adj.neighbors_locked(cur, self.locks);
// 批量预取未访问邻居的 BQ 签名
for &nb in &nbs {
if !visited.test(nb as usize) {
self.sigs.prefetch_sig(nb as usize);
}
}
for nb in nbs {
if visited.test(nb as usize) {
continue;
}
visited.set(nb as usize);
let nd = NonNanF32(
self.sigs
.distance_to_sig_in_bounds(nb as usize, q_sig, self.dim)
as f32,
);
if results.len() < ef || nd < results.peek().unwrap().0 {
candidates.push(Reverse((nd, nb)));
results.push((nd, nb));
if results.len() > ef {
results.pop();
}
}
}
}
let mut res: Vec<(NonNanF32, u32)> = results.into_vec();
res.sort_unstable_by(|a, b| a.0.cmp(&b.0));
res
}
fn connect_node_checked(&self, idx: u32, visited: &mut Bitset) {
if idx == 0 {
return;
}
let my_sig = self.sigs.get_sig_in_bounds(idx as usize);
let candidates_sym = self.beam_search_l0_locked(&my_sig, 0, self.ef, visited);
let mut candidates: Vec<(u32, u32)> = candidates_sym
.into_iter()
.filter(|&(_, id)| id != idx)
.map(|(_, id)| {
(
self.sigs
.distance_in_bounds(idx as usize, id as usize, self.dim),
id,
)
})
.collect();
let samples = self.ef.min(128).max(self.m0 * 2);
let mut state = (idx as usize)
.wrapping_mul(0x9E3779B97F4A7C15usize)
.wrapping_add(0xBF58476D1CE4E5B9usize);
for _ in 0..samples {
state ^= state >> 30;
state = state.wrapping_mul(0xBF58476D1CE4E5B9usize);
state ^= state >> 27;
state = state.wrapping_mul(0x94D049BB133111EBusize);
state ^= state >> 31;
let id = (state % self.n) as u32;
if id != idx {
candidates.push((
self.sigs
.distance_in_bounds(idx as usize, id as usize, self.dim),
id,
));
}
}
candidates.sort_unstable_by_key(|&(_, id)| id);
candidates.dedup_by_key(|&mut (_, id)| id);
candidates.sort_unstable_by_key(|&(d, _)| d);
if candidates.is_empty() {
candidates.push((self.sigs.distance_in_bounds(idx as usize, 0, self.dim), 0));
}
let selected =
QuIVer::vamana_select(self.sigs, idx, &candidates, self.m0, self.dim, self.alpha);
self.adj.set_neighbors_locked(idx, &selected, self.locks);
for &nb in &selected {
let guard = self.locks.lock(nb);
let mut current = self.adj.neighbors_with_guard(&guard);
if !current.contains(&idx) {
current.push(idx);
}
let mut nb_candidates: Vec<(u32, u32)> = current
.into_iter()
.filter(|&n| n != nb)
.map(|n| {
(
self.sigs
.distance_in_bounds(nb as usize, n as usize, self.dim),
n,
)
})
.collect();
nb_candidates.sort_unstable_by_key(|&(_, id)| id);
nb_candidates.dedup_by_key(|&mut (_, id)| id);
nb_candidates.sort_unstable_by_key(|&(d, _)| d);
let pruned =
QuIVer::vamana_select(self.sigs, nb, &nb_candidates, self.m0, self.dim, self.alpha);
self.adj.set_neighbors_with_guard(&guard, &pruned);
}
}
fn connect_node_fast(&self, idx: u32, visited: &mut Bitset) {
if idx == 0 {
return;
}
let prof = self.profile.enabled;
let my_sig = self.sigs.get_sig_in_bounds(idx as usize);
let t_beam = if prof { Some(Instant::now()) } else { None };
let candidates_sym = self.beam_search_l0_locked(&my_sig, 0, self.ef, visited);
if let Some(t) = t_beam {
self.profile
.add(&self.profile.beam_ns, t.elapsed().as_nanos() as u64);
}
let t_fwd = if prof { Some(Instant::now()) } else { None };
let mut candidates: Vec<(u32, u32)> = candidates_sym
.into_iter()
.filter(|&(_, id)| id != idx)
.map(|(_, id)| {
(
self.sigs
.distance_in_bounds(idx as usize, id as usize, self.dim),
id,
)
})
.collect();
let samples = self.ef.min(128).max(self.m0 * 2);
let mut state = (idx as usize)
.wrapping_mul(0x9E3779B97F4A7C15usize)
.wrapping_add(0xBF58476D1CE4E5B9usize);
for _ in 0..samples {
state ^= state >> 30;
state = state.wrapping_mul(0xBF58476D1CE4E5B9usize);
state ^= state >> 27;
state = state.wrapping_mul(0x94D049BB133111EBusize);
state ^= state >> 31;
let id = (state % self.n) as u32;
if id != idx {
candidates.push((
self.sigs
.distance_in_bounds(idx as usize, id as usize, self.dim),
id,
));
}
}
candidates.sort_unstable_by_key(|&(_, id)| id);
candidates.dedup_by_key(|&mut (_, id)| id);
candidates.sort_unstable_by_key(|&(d, _)| d);
if candidates.is_empty() {
candidates.push((self.sigs.distance_in_bounds(idx as usize, 0, self.dim), 0));
}
let selected =
QuIVer::vamana_select(self.sigs, idx, &candidates, self.m0, self.dim, self.alpha);
self.adj
.set_neighbors_locked_fast(idx, &selected, self.locks);
if let Some(t) = t_fwd {
self.profile
.add(&self.profile.fwd_ns, t.elapsed().as_nanos() as u64);
}
let cap = self.adj.capacity();
for &nb in &selected {
let (_guard, wait_ns) = self.locks.lock_timed(nb);
self.profile.add(&self.profile.rev_wait_ns, wait_ns);
let t_work = if prof { Some(Instant::now()) } else { None };
// 惰性剪枝:邻居表未满则直接追加(O(deg)),仅当容量用尽才触发一次完整剪枝。
// 邻接表 stride=m0*2+1 留有 2× headroom,使昂贵的 vamana_select(O(deg²))
// 从"每条反向边都跑"降为"约每 m0 条才跑一次",砍掉构图主成本。
// eager=true 时恢复旧的"每条边全量剪枝"行为,用于 recall A/B 对照。
if self.eager {
let mut current = self.adj.neighbors_raw(nb);
if !current.contains(&idx) {
current.push(idx);
}
let mut nb_candidates: Vec<(u32, u32)> = current
.into_iter()
.filter(|&n| n != nb)
.map(|n| {
(
self.sigs
.distance_in_bounds(nb as usize, n as usize, self.dim),
n,
)
})
.collect();
nb_candidates.sort_unstable_by_key(|&(_, id)| id);
nb_candidates.dedup_by_key(|&mut (_, id)| id);
nb_candidates.sort_unstable_by_key(|&(d, _)| d);
let pruned = QuIVer::vamana_select(
self.sigs,
nb,
&nb_candidates,
self.m0,
self.dim,
self.alpha,
);
self.adj.set_neighbors_raw(nb, &pruned);
} else if !self.adj.contains_raw(nb, idx) {
if self.adj.degree_raw(nb) < cap {
self.adj.push_neighbor_raw(nb, idx);
} else {
let mut current = self.adj.neighbors_raw(nb);
current.push(idx);
let mut nb_candidates: Vec<(u32, u32)> = current
.into_iter()
.filter(|&n| n != nb)
.map(|n| {
(
self.sigs
.distance_in_bounds(nb as usize, n as usize, self.dim),
n,
)
})
.collect();
nb_candidates.sort_unstable_by_key(|&(_, id)| id);
nb_candidates.dedup_by_key(|&mut (_, id)| id);
nb_candidates.sort_unstable_by_key(|&(d, _)| d);
let pruned = QuIVer::vamana_select(
self.sigs,
nb,
&nb_candidates,
self.m0,
self.dim,
self.alpha,
);
self.adj.set_neighbors_raw(nb, &pruned);
}
}
if let Some(t) = t_work {
self.profile
.add(&self.profile.rev_work_ns, t.elapsed().as_nanos() as u64);
}
}
self.profile.nodes.fetch_add(1, Ordering::Relaxed);
}
/// 构图后剪至 m0 个常规近邻,并在原容量内保留碰撞簇的跨签名出口。
/// 每节点最多剪一次,O(n) 单次剪枝,相对原"每边重剪"成本可忽略。
fn final_prune(&self, node: u32) {
let deg = self.adj.degree_raw(node);
if deg <= self.m0 {
return;
}
let current = self.adj.neighbors_raw(node);
let mut cand: Vec<(u32, u32)> = current
.into_iter()
.filter(|&n| n != node)
.map(|n| {
(
self.sigs
.distance_in_bounds(node as usize, n as usize, self.dim),
n,
)
})
.collect();
cand.sort_unstable_by_key(|&(_, id)| id);
cand.dedup_by_key(|&mut (_, id)| id);
cand.sort_unstable_by_key(|&(d, _)| d);
let pruned =
QuIVer::select_diverse_layer0(self.sigs, node, &cand, self.m0, self.dim, self.alpha);
self.adj.set_neighbors_raw(node, &pruned);
}
}
const DEFAULT_PREFILTER_SLOT_CACHE_BYTES: usize = 64 * 1024 * 1024;
type PrefilterSlotPosting = Arc<Vec<(u64, u32)>>;
struct PrefilterSlotCacheEntry {
posting: PrefilterSlotPosting,
bytes: usize,
last_used: u64,
}
struct PrefilterSlotCacheState {
entries: std::collections::HashMap<(u64, u64), PrefilterSlotCacheEntry>,
bytes: usize,
max_bytes: usize,
clock: u64,
}
impl PrefilterSlotCacheState {
fn clear(&mut self) {
self.entries.clear();
self.bytes = 0;
}
fn get(&mut self, key: (u64, u64)) -> Option<PrefilterSlotPosting> {
self.clock = self.clock.wrapping_add(1);
let entry = self.entries.get_mut(&key)?;
entry.last_used = self.clock;
Some(Arc::clone(&entry.posting))
}
fn insert(&mut self, key: (u64, u64), posting: PrefilterSlotPosting) {
let bytes = posting
.len()
.saturating_mul(std::mem::size_of::<(u64, u32)>());
if bytes > self.max_bytes {
return;
}
if let Some(previous) = self.entries.remove(&key) {
self.bytes = self.bytes.saturating_sub(previous.bytes);
}
while self.bytes.saturating_add(bytes) > self.max_bytes {
let Some(oldest) = self
.entries
.iter()
.min_by_key(|(_, entry)| entry.last_used)
.map(|(key, _)| *key)
else {
break;
};
if let Some(removed) = self.entries.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(removed.bytes);
}
}
self.clock = self.clock.wrapping_add(1);
self.entries.insert(
key,
PrefilterSlotCacheEntry {
posting,
bytes,
last_used: self.clock,
},
);
self.bytes = self.bytes.saturating_add(bytes);
}
}
impl Default for PrefilterSlotCacheState {
fn default() -> Self {
Self {
entries: std::collections::HashMap::new(),
bytes: 0,
max_bytes: DEFAULT_PREFILTER_SLOT_CACHE_BYTES,
clock: 0,
}
}
}
type PrefilterSlotCache = Mutex<PrefilterSlotCacheState>;
pub struct QuIVer {
dim: usize,
n: usize,
m: usize,
m0: usize,
ef_construction: usize,
ml: f64,
alpha: f32,
// Hot(常驻内存)
bq_store: Bq2Store,
// 显式安装的查询校正;复用layer0,结构或向量变化后失效。
corrected_sm: Option<corrected_sm::CorrectedSmIndex>,
// 默认无训练SM-L2;增量插入追加位码,删除仅屏蔽精排,旧文件由向量池恢复。
default_sm: Option<corrected_sm::CorrectedSmIndex>,
layer0: FlatAdj,
upper_layers: Vec<Vec<Vec<u32>>>,
upper_bytes: usize,
node_max_layer: Vec<u8>,
// ID 映射