-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsearch.rs
More file actions
3535 lines (3215 loc) · 133 KB
/
Copy pathsearch.rs
File metadata and controls
3535 lines (3215 loc) · 133 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
//! Brute-force top-k vector search over an opened [`crate::VectorIndex`].
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::sync::OnceLock;
use ahash::AHashSet;
use frankensearch_core::config::ZeroSignalReason;
use frankensearch_core::filter::{DocIdHashSet, SearchFilter};
use frankensearch_core::{SearchError, SearchResult, VectorHit};
use rayon::prelude::*;
use crate::simd::dot_i8x4_i8;
use crate::wal::{from_wal_index, is_wal_index, to_wal_index};
use crate::{
PreparedQuery4bit, Quantization, VectorIndex, dot_4bit_prepared, dot_i8_i8, dot_i8_i8_maddubs,
dot_product_f16_bytes_f32, dot_product_f32_bytes_f32, dot_product_f32_f32, maddubs_query_bias,
pack_f16_le_bytes_to_4bit, prepare_4bit_query, quantize_f16_le_bytes_to_i8,
};
/// Record-count threshold where search switches from sequential to Rayon.
pub const PARALLEL_THRESHOLD: usize = 10_000;
/// Chunk size per Rayon task in the parallel scan path.
pub const PARALLEL_CHUNK_SIZE: usize = 1_024;
const INT8_PARALLEL_CHUNK_SIZE: usize = PARALLEL_CHUNK_SIZE * 4;
/// Selectivity threshold for the file-backed gather fast-path. A hash-addressable
/// filter must be smaller than `record_count / GATHER_SELECTIVITY_DIVISOR` before
/// we invert the loop and binary-search/gather the allowed hash ranges. The FSVI
/// crossover is lower than the in-memory gather because each allowed hash pays
/// `log2(N)` record-table probes; the short `filtered_gather` sweep keeps clear of
/// the measured 5% regression.
const GATHER_SELECTIVITY_DIVISOR: usize = 50;
/// Configurable parameters for vector search parallelism.
///
/// Controls when and how the brute-force scan switches from sequential
/// to Rayon-parallel execution. Use [`SearchParams::default()`] for the
/// standard settings (threshold = 10,000, chunk size = 1,024, parallel
/// enabled via `FRANKENSEARCH_PARALLEL_SEARCH` env var).
#[derive(Debug, Clone, Copy)]
pub struct SearchParams {
/// Minimum record count to trigger parallel scanning.
/// Below this threshold, search runs sequentially.
pub parallel_threshold: usize,
/// Number of records processed per Rayon chunk in parallel mode.
pub parallel_chunk_size: usize,
/// Whether parallel scanning is allowed at all. When `false`, search
/// always runs sequentially regardless of record count.
pub parallel_enabled: bool,
}
impl Default for SearchParams {
fn default() -> Self {
Self {
parallel_threshold: PARALLEL_THRESHOLD,
parallel_chunk_size: PARALLEL_CHUNK_SIZE,
parallel_enabled: parallel_search_enabled(),
}
}
}
/// A top-k result plus a typed classification when it is empty.
///
/// The invariant `zero_signal.is_some() == hits.is_empty()` lets callers
/// distinguish a legitimately empty answer (benign request/state outcome)
/// from an unusable semantic lane (availability failure) without inferring
/// anything from bare emptiness.
#[derive(Debug, Clone)]
pub struct ClassifiedHits {
/// Ranked hits, best first. May be empty.
pub hits: Vec<VectorHit>,
/// `Some(reason)` if and only if `hits` is empty.
pub zero_signal: Option<ZeroSignalReason>,
}
impl ClassifiedHits {
/// An empty result with its typed reason.
#[must_use]
pub const fn empty(reason: ZeroSignalReason) -> Self {
Self {
hits: Vec::new(),
zero_signal: Some(reason),
}
}
}
static PARALLEL_SEARCH_ENABLED_CACHE: OnceLock<bool> = OnceLock::new();
#[derive(Debug, Clone, Copy)]
struct HeapEntry {
index: usize,
score: f32,
}
impl HeapEntry {
const fn new(index: usize, score: f32) -> Self {
Self { index, score }
}
}
impl PartialEq for HeapEntry {
fn eq(&self, other: &Self) -> bool {
self.index == other.index && self.score.to_bits() == other.score.to_bits()
}
}
impl Eq for HeapEntry {}
impl PartialOrd for HeapEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for HeapEntry {
fn cmp(&self, other: &Self) -> Ordering {
// BinaryHeap keeps the largest element at the top.
// We define "largest" == "worst" so peek() returns the current cutoff.
match score_key(self.score).total_cmp(&score_key(other.score)) {
Ordering::Less => Ordering::Greater,
Ordering::Greater => Ordering::Less,
Ordering::Equal => self.index.cmp(&other.index),
}
}
}
/// Largest dimension whose entire `[-127 * 127 * dim, 127 * 127 * dim]` integer
/// dot range is exactly representable as f32. The common 384-dimensional path can
/// therefore rank raw i32 values while preserving the shipped i32-to-f32 order.
const MAX_EXACT_I8_DOT_DIM: usize = 1_040;
/// Packed pass-1 ordering key for the int8 two-pass scan. Larger means worse, so
/// `BinaryHeap::peek` remains the cutoff. The high word reverses score order
/// (higher scores become smaller keys); the low word preserves the full `usize`
/// index as the deterministic tiebreak (lower indices are better).
type Int8HeapKey = u128;
#[allow(clippy::inline_always)]
#[inline(always)]
const fn int8_heap_key(index: usize, score: i32) -> Int8HeapKey {
let ascending_score = score.cast_unsigned() ^ 0x8000_0000;
let descending_score = !ascending_score;
((descending_score as u128) << usize::BITS) | index as u128
}
#[allow(clippy::inline_always)]
#[inline(always)]
fn int8_heap_key_from_f32(index: usize, score: i32) -> Int8HeapKey {
let score = score as f32;
let bits = score.to_bits();
let sign_mask = (bits >> 31).wrapping_neg() | 0x8000_0000;
let ascending_score = bits ^ sign_mask;
let descending_score = !ascending_score;
(u128::from(descending_score) << usize::BITS) | index as u128
}
const fn int8_heap_index(key: Int8HeapKey) -> usize {
key as usize
}
#[inline]
fn retain_int8_candidate(
heap: &mut BinaryHeap<Int8HeapKey>,
cutoff: &mut Int8HeapKey,
candidate: Int8HeapKey,
limit: usize,
) {
if heap.len() < limit {
heap.push(candidate);
if heap.len() == limit {
*cutoff = heap.peek().copied().unwrap_or(Int8HeapKey::MAX);
}
} else if candidate < *cutoff {
let _ = heap.pop();
heap.push(candidate);
*cutoff = heap.peek().copied().unwrap_or(Int8HeapKey::MAX);
}
}
impl VectorIndex {
/// Brute-force cosine-similarity top-k search over all records.
///
/// The query is expected to already be normalized for cosine similarity.
/// The result is sorted by descending score with NaN-safe semantics.
///
/// # Errors
///
/// Returns `SearchError::DimensionMismatch` when `query.len()` does not
/// match index dimensionality, and `SearchError::IndexCorrupted` for
/// malformed vector slab contents.
pub fn search_top_k(
&self,
query: &[f32],
limit: usize,
filter: Option<&dyn SearchFilter>,
) -> SearchResult<Vec<VectorHit>> {
self.search_top_k_internal(
query,
limit,
filter,
PARALLEL_THRESHOLD,
PARALLEL_CHUNK_SIZE,
parallel_search_enabled(),
)
}
/// Brute-force top-k with typed zero-signal classification.
///
/// Behaves like [`Self::search_top_k`] with two fail-closed differences
/// that align the exact path with the ANN path:
/// - a query containing NaN or infinite components is rejected with
/// [`SearchError::InvalidConfig`] instead of silently scoring garbage
/// (parity with `HnswIndex`);
/// - an empty result always carries a typed
/// [`ZeroSignalReason`], so a legitimate empty answer is
/// distinguishable from an unusable semantic lane.
///
/// Classification is lazy: the non-empty path costs nothing extra, and
/// an empty result pays one census pass comparable to the scan that
/// just ran.
///
/// # Errors
///
/// Everything [`Self::search_top_k`] returns, plus
/// [`SearchError::InvalidConfig`] for non-finite query vectors.
pub fn search_top_k_classified(
&self,
query: &[f32],
limit: usize,
filter: Option<&dyn SearchFilter>,
) -> SearchResult<ClassifiedHits> {
self.ensure_query_dimension(query)?;
if limit == 0 {
return Ok(ClassifiedHits::empty(
ZeroSignalReason::CallerRequestedZeroK,
));
}
if query.iter().any(|value| !value.is_finite()) {
return Err(SearchError::InvalidConfig {
field: "query".to_owned(),
value: "<contains non-finite values>".to_owned(),
reason: "query vector must be finite".to_owned(),
});
}
if query.iter().all(|&value| value == 0.0) {
return Ok(ClassifiedHits::empty(ZeroSignalReason::ZeroNormQuery));
}
let hits = self.search_top_k(query, limit, filter)?;
if hits.is_empty() {
let reason = self.classify_empty_result(filter.is_some());
return Ok(ClassifiedHits {
hits,
zero_signal: Some(reason),
});
}
Ok(ClassifiedHits {
hits,
zero_signal: None,
})
}
/// Classify why a well-formed search (k > 0, finite non-zero query)
/// returned nothing, following the precedence documented on
/// [`ZeroSignalReason`].
pub(crate) fn classify_empty_result(&self, had_filter: bool) -> ZeroSignalReason {
self.zero_signal_state().empty_result_reason(had_filter)
}
/// Exact top-k over the persisted main slab only.
///
/// HNSW uses this crate-private lane to repair a native underfill with the
/// same quantization decoder, dot-product implementation, tombstone
/// semantics, score ordering, physical row identities, and post-top-k
/// document-ID deduplication as canonical `VectorIndex` search. Resident
/// WAL entries and their supersession rules are deliberately excluded:
/// `TwoTierIndex` merges them exactly once after ANN candidate retrieval.
#[cfg(feature = "ann")]
pub(crate) fn search_main_top_k(
&self,
query: &[f32],
limit: usize,
) -> SearchResult<Vec<VectorHit>> {
let mut hits = self.search_main_top_k_raw(query, limit)?;
let mut seen = AHashSet::with_capacity(hits.len());
hits.retain(|hit| seen.insert(hit.doc_id.clone()));
Ok(hits)
}
/// Raw physical top-k over the persisted main slab only.
///
/// Unlike [`Self::search_main_top_k`], this does not apply document-ID
/// deduplication. Neither main-only lane applies resident-WAL supersession.
/// `TwoTierIndex` uses this raw lane only when an ANN underfill must be
/// repaired before main and WAL candidates are ranked together through the
/// canonical result resolver.
#[cfg(feature = "ann")]
pub(crate) fn search_main_top_k_raw(
&self,
query: &[f32],
limit: usize,
) -> SearchResult<Vec<VectorHit>> {
let heap = self.scan_main_top_k_heap(query, limit)?;
let mut winners = heap.into_vec();
winners.sort_unstable_by(compare_best_first);
winners
.into_iter()
.map(|winner| {
let index =
u32::try_from(winner.index).map_err(|_| SearchError::InvalidConfig {
field: "index".to_owned(),
value: winner.index.to_string(),
reason: "winner index exceeds u32 range for VectorHit".to_owned(),
})?;
Ok(VectorHit {
index,
score: winner.score,
doc_id: self.doc_id_at(winner.index)?.into(),
})
})
.collect()
}
#[cfg(feature = "ann")]
fn scan_main_top_k_heap(
&self,
query: &[f32],
limit: usize,
) -> SearchResult<BinaryHeap<HeapEntry>> {
self.ensure_query_dimension(query)?;
if limit == 0 || self.record_count() == 0 {
return Ok(BinaryHeap::new());
}
if parallel_search_enabled() && self.record_count() >= PARALLEL_THRESHOLD {
self.scan_parallel(query, limit, None, PARALLEL_CHUNK_SIZE)
} else {
self.scan_sequential(query, limit, None)
}
}
/// Brute-force cosine-similarity top-k search with configurable parallelism.
///
/// Behaves identically to [`search_top_k`](Self::search_top_k) but uses the
/// caller-supplied [`SearchParams`] instead of the compiled-in defaults.
///
/// # Errors
///
/// Returns `SearchError::DimensionMismatch` when `query.len()` does not
/// match index dimensionality, and `SearchError::IndexCorrupted` for
/// malformed vector slab contents.
pub fn search_top_k_with_params(
&self,
query: &[f32],
limit: usize,
filter: Option<&dyn SearchFilter>,
params: SearchParams,
) -> SearchResult<Vec<VectorHit>> {
self.search_top_k_internal(
query,
limit,
filter,
params.parallel_threshold,
params.parallel_chunk_size,
params.parallel_enabled,
)
}
/// Bench-only: force the old per-document filtered scan, bypassing the
/// selective-filter gather fast-path.
#[doc(hidden)]
pub fn bench_scan_filtered(
&self,
query: &[f32],
limit: usize,
filter: Option<&dyn SearchFilter>,
) -> SearchResult<Vec<VectorHit>> {
self.ensure_query_dimension(query)?;
let has_main = self.record_count() > 0;
let has_wal = !self.wal_entries.is_empty();
if limit == 0 || (!has_main && !has_wal) {
return Ok(Vec::new());
}
let use_parallel = parallel_search_enabled() && self.record_count() >= PARALLEL_THRESHOLD;
let mut heap = if has_main {
if use_parallel {
self.scan_parallel(query, limit, filter, PARALLEL_CHUNK_SIZE)?
} else {
self.scan_sequential(query, limit, filter)?
}
} else {
BinaryHeap::with_capacity(limit.min(self.wal_entries.len()).saturating_add(1))
};
if has_wal {
self.scan_wal(query, &mut heap, limit, filter)?;
}
self.resolve_hits(heap)
}
/// Bench-only: force the selective-filter gather path, ignoring the production
/// selectivity gate.
#[doc(hidden)]
pub fn bench_gather_filtered(
&self,
query: &[f32],
limit: usize,
filter: &dyn SearchFilter,
) -> SearchResult<Vec<VectorHit>> {
self.ensure_query_dimension(query)?;
if limit == 0 || (self.record_count() == 0 && self.wal_entries.is_empty()) {
return Ok(Vec::new());
}
let Some(allowed) = filter.candidate_hashes() else {
return self.bench_scan_filtered(query, limit, Some(filter));
};
let mut heap = if self.record_count() > 0 {
self.scan_gather_hashes(allowed, query, limit)?
} else {
BinaryHeap::with_capacity(limit.min(self.wal_entries.len()).saturating_add(1))
};
if !self.wal_entries.is_empty() {
self.scan_wal(query, &mut heap, limit, Some(filter))?;
}
self.resolve_hits(heap)
}
fn search_top_k_internal(
&self,
query: &[f32],
limit: usize,
filter: Option<&dyn SearchFilter>,
parallel_threshold: usize,
parallel_chunk_size: usize,
parallel_enabled: bool,
) -> SearchResult<Vec<VectorHit>> {
self.ensure_query_dimension(query)?;
let has_main = self.record_count() > 0;
let has_wal = !self.wal_entries.is_empty();
if limit == 0 || (!has_main && !has_wal) {
return Ok(Vec::new());
}
let chunk_size = parallel_chunk_size.max(1);
let use_parallel = parallel_enabled && self.record_count() >= parallel_threshold;
let total_candidate_upper_bound =
self.record_count().saturating_add(self.wal_entries.len());
// Full-recall requests should avoid top-k heap churn.
// When the caller asks for all available candidates (`k >= total`),
// collect-and-sort is measurably faster than maintaining a size-k heap.
if filter.is_none() && limit >= total_candidate_upper_bound {
let mut winners = if has_main {
if use_parallel {
self.scan_parallel_collect_all(query, chunk_size)?
} else {
self.scan_range_collect_all(0, self.record_count(), query)?
}
} else {
Vec::new()
};
if has_wal {
self.scan_wal_collect_all(query, &mut winners)?;
}
// `limit_all` scan-all path: `winners` can hold every match. Above a
// threshold the final sort dominates, and a parallel sort pays
// (measured ~2.81× at 50k winners, `winners_sort` bench); below it the
// rayon overhead is not worth it, so stay serial. Bit-identical either
// way — `compare_best_first` is a strict total order.
if winners.len() >= PAR_SORT_THRESHOLD {
winners.par_sort_unstable_by(compare_best_first);
} else {
winners.sort_unstable_by(compare_best_first);
}
return self.resolve_sorted_entries(winners);
}
let mut heap = if has_main {
if let Some(gathered) = self.try_gather_filtered(query, limit, filter)? {
gathered
} else if use_parallel {
self.scan_parallel(query, limit, filter, chunk_size)?
} else {
self.scan_sequential(query, limit, filter)?
}
} else {
let max_wal = self.wal_entries.len();
BinaryHeap::with_capacity(limit.min(max_wal).saturating_add(1))
};
// Merge WAL entries into the same heap.
if has_wal {
self.scan_wal(query, &mut heap, limit, filter)?;
}
self.resolve_hits(heap)
}
/// int8 ADC two-pass exact top-k for **standalone** large-N vector search:
/// a fast parallel int8 pass-1 over all main records keeps the top
/// `k·candidate_multiplier` by approximate score, then an exact f16 rescore of
/// just those candidates selects the final top-k. Lossless (recall=1.0) whenever
/// pass-1 retains the true top-k — validated on the in-memory twin; the int8
/// dot is monotonic with the true dot under one corpus max-abs scale.
///
/// Covers the contiguous F16 main-vector region only; falls back to the exact
/// [`VectorIndex::search_top_k`] when a WAL is present or quantization is not F16
/// (so results are always correct, never silently degraded). Not wired into the
/// BOLD hybrid (that gap is not vector-bound — see `docs/NEGATIVE_EVIDENCE.md`);
/// this targets pure vector-search latency at large N.
///
/// # Errors
///
/// Returns `SearchError::DimensionMismatch` when `query.len()` does not
/// match index dimensionality, and `SearchError::IndexCorrupted` for
/// malformed slab data.
pub fn search_top_k_int8_two_pass(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
// Production keeps the EXACT-int8 pass-1. The `vpmaddubs` kernel (bd-b5wl) is 1.23× faster
// in isolation (decidable) and recall-exact, but its **scan-level** win is only ~1.02–1.11×
// (Amdahl-shrunk) and is NOT robustly decidable under fleet contention: two null-controlled
// runs on `hetzner1` disagreed — 0.9023 (median below null p5, a clear win) then 0.9821
// (inside the null floor). Shipping the approximate kernel as default on a marginal,
// contention-dependent effect fails the gate, so it stays behind
// `bench_search_top_k_int8_two_pass_maddubs`. Retry = worker isolation (same as cod's int8
// micro-opt block). See docs/NEGATIVE_EVIDENCE.md 2026-07-10.
self.search_top_k_int8_two_pass_impl::<false, false>(query, k, candidate_multiplier)
}
/// Exact pre-row-block implementation retained only for same-binary
/// performance comparisons. Production callers should use
/// [`Self::search_top_k_int8_two_pass`].
#[doc(hidden)]
pub fn bench_search_top_k_int8_two_pass_orig(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
self.search_top_k_int8_two_pass_impl::<false, false>(query, k, candidate_multiplier)
}
/// Four-row query-decode-reuse candidate retained only so the null-controlled
/// negative measurement stays reproducible. Production callers use
/// [`Self::search_top_k_int8_two_pass`].
#[doc(hidden)]
pub fn bench_search_top_k_int8_two_pass_row_block_candidate(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
self.search_top_k_int8_two_pass_impl::<true, false>(query, k, candidate_multiplier)
}
/// `vpmaddubs` pass-1 kernel candidate (bd-b5wl), retained for the same-binary A/B.
/// Bit-identical *ranking* to [`Self::search_top_k_int8_two_pass`] on realistic quantized data
/// (proven recall in `simd::tests::maddubs_pass1_preserves_f32_recall_under_real_saturation`);
/// the pass-1 int8 dot is the approximate `dot_i8_i8_maddubs` (see its saturation caveat).
#[doc(hidden)]
pub fn bench_search_top_k_int8_two_pass_maddubs(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
self.search_top_k_int8_two_pass_impl::<false, true>(query, k, candidate_multiplier)
}
fn search_top_k_int8_two_pass_impl<const ROW_BLOCKED: bool, const MADDUBS: bool>(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
let count = self.record_count();
// Fall back to the exact scan for anything this fast path does not cover.
if k == 0
|| count == 0
|| !self.wal_entries.is_empty()
|| self.quantization() != Quantization::F16
{
return self.search_top_k(query, k, None);
}
if query.len() != self.dimension() {
return Err(SearchError::DimensionMismatch {
expected: self.dimension(),
found: query.len(),
});
}
let dim = self.dimension();
let candidate_count = k
.saturating_mul(candidate_multiplier.max(1))
.min(count)
.max(k.min(count));
let query_i8 = quantize_i8_query(query);
// Per-query bias `128·Σq` for the `MADDUBS` pass-1 kernel; unused (0) otherwise.
let q_bias128 = if MADDUBS {
maddubs_query_bias(&query_i8, dim)
} else {
0
};
let slab = self.int8_slab();
// Pass 1: bounded-heap int8 scan keeping the top `candidate_count`.
// The int8 dot is cheap enough that exact-scan sized chunks overproduce
// local top-N heaps; larger chunks keep enough Rayon tasks while shrinking
// the post-scan merge fan-in.
let candidate_heap = if count < PARALLEL_THRESHOLD {
if ROW_BLOCKED {
self.int8_scan_range(slab, &query_i8, 0, count, candidate_count)
} else {
self.int8_scan_range_orig::<MADDUBS>(
slab,
&query_i8,
q_bias128,
0,
count,
candidate_count,
)
}
} else {
let chunk_count = count.div_ceil(INT8_PARALLEL_CHUNK_SIZE);
let partials: Vec<BinaryHeap<Int8HeapKey>> = (0..chunk_count)
.into_par_iter()
.map(|chunk_index| {
let start = chunk_index * INT8_PARALLEL_CHUNK_SIZE;
let end = (start + INT8_PARALLEL_CHUNK_SIZE).min(count);
if ROW_BLOCKED {
self.int8_scan_range(slab, &query_i8, start, end, candidate_count)
} else {
self.int8_scan_range_orig::<MADDUBS>(
slab,
&query_i8,
q_bias128,
start,
end,
candidate_count,
)
}
})
.collect();
merge_int8_partial_heaps(partials, candidate_count)
};
// Pass 2: exact f16 rescore of the candidates through the SAME bounded-heap
// selection + tie-break as `search_top_k`, so the final order is identical
// whenever pass-1 retained the true top-k.
let stride = dim * 2;
let mut heap = BinaryHeap::with_capacity(k.saturating_add(1));
for candidate in candidate_heap {
let index = int8_heap_index(candidate);
let vector_offset = self.vectors_offset + index * stride;
let vector_bytes = &self.data[vector_offset..vector_offset + stride];
let score = dot_product_f16_bytes_f32(vector_bytes, query)?;
insert_candidate(&mut heap, HeapEntry::new(index, score), k);
}
self.resolve_hits(heap)
}
fn int8_scan_range_orig<const MADDUBS: bool>(
&self,
slab: &[i8],
query_i8: &[i8],
q_bias128: i32,
start: usize,
end: usize,
limit: usize,
) -> BinaryHeap<Int8HeapKey> {
if limit == 0 {
return BinaryHeap::new();
}
if self.dimension() <= MAX_EXACT_I8_DOT_DIM {
self.int8_scan_range_orig_with_key::<MADDUBS, _>(
slab,
query_i8,
q_bias128,
start,
end,
limit,
int8_heap_key,
)
} else {
self.int8_scan_range_orig_with_key::<MADDUBS, _>(
slab,
query_i8,
q_bias128,
start,
end,
limit,
int8_heap_key_from_f32,
)
}
}
/// Exact `1948a65` per-row scan retained for the in-binary ORIGINAL arm. `MADDUBS` swaps the
/// pass-1 int8 dot to the approximate `vpmaddubs` kernel (bd-b5wl); `q_bias128 = 128·Σq` is then
/// live, else ignored. Production is `MADDUBS = false` → byte-identical to the shipped scan.
fn int8_scan_range_orig_with_key<const MADDUBS: bool, F>(
&self,
slab: &[i8],
query_i8: &[i8],
q_bias128: i32,
start: usize,
end: usize,
limit: usize,
make_key: F,
) -> BinaryHeap<Int8HeapKey>
where
F: Fn(usize, i32) -> Int8HeapKey,
{
let dim = self.dimension();
let mut heap = BinaryHeap::with_capacity(limit.min(end - start).saturating_add(1));
let mut cutoff = Int8HeapKey::MAX;
let mut flags_offset = self.records_offset + start * 16 + 14;
let mut slab_offset = start * dim;
for index in start..end {
let flags_bytes = &self.data[flags_offset..flags_offset + 2];
let flags = u16::from_le_bytes([flags_bytes[0], flags_bytes[1]]);
if (flags & 0x0001) == 0 {
let stored = &slab[slab_offset..slab_offset + dim];
let dot = if MADDUBS {
dot_i8_i8_maddubs(stored, query_i8, q_bias128)
} else {
dot_i8_i8(stored, query_i8)
};
let candidate = make_key(index, dot);
if heap.len() < limit {
heap.push(candidate);
if heap.len() == limit {
cutoff = heap.peek().copied().unwrap_or(Int8HeapKey::MAX);
}
} else if candidate < cutoff {
let _ = heap.pop();
heap.push(candidate);
cutoff = heap.peek().copied().unwrap_or(Int8HeapKey::MAX);
}
}
flags_offset += 16;
slab_offset += dim;
}
heap
}
/// Bounded-heap int8 scan of records `[start, end)` over the int8 `slab`
/// (index-aligned with the record table), skipping tombstoned records via the
/// same flag check + cutoff fast-path as the exact `scan_range_chunk`.
fn int8_scan_range(
&self,
slab: &[i8],
query_i8: &[i8],
start: usize,
end: usize,
limit: usize,
) -> BinaryHeap<Int8HeapKey> {
if limit == 0 {
return BinaryHeap::new();
}
if self.dimension() <= MAX_EXACT_I8_DOT_DIM {
self.int8_scan_range_with_key(slab, query_i8, start, end, limit, int8_heap_key)
} else {
self.int8_scan_range_with_key(slab, query_i8, start, end, limit, int8_heap_key_from_f32)
}
}
fn int8_scan_range_with_key<F>(
&self,
slab: &[i8],
query_i8: &[i8],
start: usize,
end: usize,
limit: usize,
make_key: F,
) -> BinaryHeap<Int8HeapKey>
where
F: Fn(usize, i32) -> Int8HeapKey,
{
let dim = self.dimension();
let mut heap = BinaryHeap::with_capacity(limit.min(end - start).saturating_add(1));
let mut cutoff = Int8HeapKey::MAX;
let mut flags_offset = self.records_offset + start * 16 + 14;
let mut slab_offset = start * dim;
let mut index = start;
while index + 4 <= end {
let flags0 = u16::from_le_bytes([self.data[flags_offset], self.data[flags_offset + 1]]);
let flags1 =
u16::from_le_bytes([self.data[flags_offset + 16], self.data[flags_offset + 17]]);
let flags2 =
u16::from_le_bytes([self.data[flags_offset + 32], self.data[flags_offset + 33]]);
let flags3 =
u16::from_le_bytes([self.data[flags_offset + 48], self.data[flags_offset + 49]]);
let flags = [flags0, flags1, flags2, flags3];
if ((flags0 | flags1 | flags2 | flags3) & 0x0001) == 0 {
let stored_rows = &slab[slab_offset..slab_offset + 4 * dim];
let scores = dot_i8x4_i8(stored_rows, query_i8);
for (lane, score) in scores.into_iter().enumerate() {
retain_int8_candidate(
&mut heap,
&mut cutoff,
make_key(index + lane, score),
limit,
);
}
} else {
for (lane, flags) in flags.into_iter().enumerate() {
if (flags & 0x0001) == 0 {
let row_offset = slab_offset + lane * dim;
let stored = &slab[row_offset..row_offset + dim];
retain_int8_candidate(
&mut heap,
&mut cutoff,
make_key(index + lane, dot_i8_i8(stored, query_i8)),
limit,
);
}
}
}
index += 4;
flags_offset += 64;
slab_offset += 4 * dim;
}
while index < end {
let flags_bytes = &self.data[flags_offset..flags_offset + 2];
let flags = u16::from_le_bytes([flags_bytes[0], flags_bytes[1]]);
if (flags & 0x0001) == 0 {
let stored = &slab[slab_offset..slab_offset + dim];
retain_int8_candidate(
&mut heap,
&mut cutoff,
make_key(index, dot_i8_i8(stored, query_i8)),
limit,
);
}
index += 1;
flags_offset += 16;
slab_offset += dim;
}
heap
}
/// Lazily build (once) the int8 quantization of the contiguous F16 main-vector
/// region. Only called after the F16/no-WAL gate in `search_top_k_int8_two_pass`.
fn int8_slab(&self) -> &[i8] {
self.vectors_i8.get_or_init(|| {
let count = self.record_count();
let dim = self.dimension();
let byte_len = count * dim * 2;
quantize_f16_le_bytes_to_i8(
&self.data[self.vectors_offset..self.vectors_offset + byte_len],
)
})
}
/// 4-bit (16-level) two-pass exact top-k for standalone large-N vector search.
/// A fast parallel pass-1 over a packed signed-4-bit slab (`dim/2` bytes/vector —
/// half the int8 slab, so the bandwidth-bound pass-1 is faster) keeps the top
/// `k·candidate_multiplier` by approximate score (`dot_4bit_prepared`), then
/// an exact f16 rescore of just those candidates selects the final top-k. 16
/// levels stay lossless at mult≈5 on realistic clustered data (see
/// `fsvi_4bit_two_pass` bench); recall rises with `candidate_multiplier`.
/// Falls back to the exact `search_top_k` for WAL/non-F16 indexes. Not wired
/// into the BOLD hybrid.
///
/// # Errors
///
/// Returns `SearchError::DimensionMismatch` when `query.len()` does not
/// match index dimensionality, and `SearchError::IndexCorrupted` for
/// malformed slab data.
pub fn search_top_k_4bit_two_pass(
&self,
query: &[f32],
k: usize,
candidate_multiplier: usize,
) -> SearchResult<Vec<VectorHit>> {
let count = self.record_count();
if k == 0
|| count == 0
|| !self.wal_entries.is_empty()
|| self.quantization() != Quantization::F16
{
return self.search_top_k(query, k, None);
}
if query.len() != self.dimension() {
return Err(SearchError::DimensionMismatch {
expected: self.dimension(),
found: query.len(),
});
}
let dim = self.dimension();
let bytes_per_vector = dim.div_ceil(2);
let candidate_count = k
.saturating_mul(candidate_multiplier.max(1))
.min(count)
.max(k.min(count));
let query_packed = pack_4bit_query(query);
let query_prepared = prepare_4bit_query(&query_packed);
let slab = self.nibbles_slab();
let candidate_heap = if count < PARALLEL_THRESHOLD {
self.nibble_scan_range(
slab,
&query_prepared,
bytes_per_vector,
0,
count,
candidate_count,
)
} else {
let chunk_count = count.div_ceil(PARALLEL_CHUNK_SIZE);
let partials: Vec<BinaryHeap<HeapEntry>> = (0..chunk_count)
.into_par_iter()
.map(|chunk_index| {
let start = chunk_index * PARALLEL_CHUNK_SIZE;
let end = (start + PARALLEL_CHUNK_SIZE).min(count);
self.nibble_scan_range(
slab,
&query_prepared,
bytes_per_vector,
start,
end,
candidate_count,
)
})
.collect();
merge_partial_heaps(partials, candidate_count)
};
// Pass 2: exact f16 rescore (same bounded-heap selection + tie-break).
let stride = dim * 2;
let mut heap = BinaryHeap::with_capacity(k.saturating_add(1));
for candidate in candidate_heap {
let vector_offset = self.vectors_offset + candidate.index * stride;
let vector_bytes = &self.data[vector_offset..vector_offset + stride];
let score = dot_product_f16_bytes_f32(vector_bytes, query)?;
insert_candidate(&mut heap, HeapEntry::new(candidate.index, score), k);
}
self.resolve_hits(heap)
}
/// Bounded-heap 4-bit scan of records `[start, end)` over the packed nibble
/// `slab` (index-aligned with the record table), skipping tombstoned records,
/// with the same cutoff fast-path as the exact scan.
fn nibble_scan_range(
&self,
slab: &[u8],
query_prepared: &PreparedQuery4bit,
bytes_per_vector: usize,
start: usize,
end: usize,
limit: usize,
) -> BinaryHeap<HeapEntry> {
let mut heap = BinaryHeap::with_capacity(limit.min(end - start).saturating_add(1));
let mut cutoff = f32::NEG_INFINITY;
let mut flags_offset = self.records_offset + start * 16 + 14;
let mut slab_offset = start * bytes_per_vector;
for index in start..end {
let flags_bytes = &self.data[flags_offset..flags_offset + 2];
let flags = u16::from_le_bytes([flags_bytes[0], flags_bytes[1]]);
if (flags & 0x0001) == 0 {
let stored = &slab[slab_offset..slab_offset + bytes_per_vector];
let score = dot_4bit_prepared(stored, query_prepared) as f32;
if heap.len() < limit || score_key(score) >= cutoff {
insert_candidate(&mut heap, HeapEntry::new(index, score), limit);
if heap.len() >= limit
&& let Some(&worst) = heap.peek()
{
cutoff = score_key(worst.score);
}
}
}
flags_offset += 16;
slab_offset += bytes_per_vector;
}
heap
}
/// Lazily build (once) the packed signed-4-bit quantization of the contiguous
/// F16 main-vector region. Only called after the F16/no-WAL gate.
fn nibbles_slab(&self) -> &[u8] {
self.vectors_nibbles.get_or_init(|| {
let count = self.record_count();
let dim = self.dimension();
let byte_len = count * dim * 2;
pack_f16_le_bytes_to_4bit(
&self.data[self.vectors_offset..self.vectors_offset + byte_len],
dim,
)
})
}
fn scan_sequential(