This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-vector-index.git
The following commit(s) were added to refs/heads/main by this push:
new 7857f34 perf(rq): accelerate multi-bit scans and improve
high-dimensional encoding (#118)
7857f34 is described below
commit 7857f341f57db76ace01606314f25f361ace1f91
Author: Jingsong Lee <[email protected]>
AuthorDate: Wed Nov 11 16:41:05 2026 +0800
perf(rq): accelerate multi-bit scans and improve high-dimensional encoding
(#118)
---
core/benches/ann_bench.rs | 107 ++++++++++--
core/src/ivfrq_io.rs | 199 ++++++++++++++++++----
core/src/rq.rs | 363 +++++++++++++++++++++++++++++++++++++----
docs/development.html | 2 +
docs/ivf-rq.html | 21 ++-
tools/README.md | 35 ++++
tools/tests/test_tune_ivfrq.py | 205 +++++++++++++++++++++++
tools/tune_ivfrq.py | 253 ++++++++++++++++++++++++++++
8 files changed, 1110 insertions(+), 75 deletions(-)
diff --git a/core/benches/ann_bench.rs b/core/benches/ann_bench.rs
index 91330d3..55defcb 100644
--- a/core/benches/ann_bench.rs
+++ b/core/benches/ann_bench.rs
@@ -34,6 +34,7 @@ use paimon_vindex_core::io::{PosWriter, ReadRequest,
SeekRead, SeekReadCapabilit
use paimon_vindex_core::rq::{is_supported_rq_bits, DEFAULT_RQ_BITS};
use rayon::prelude::*;
use rayon::{ThreadPool, ThreadPoolBuilder};
+use roaring::RoaringTreemap;
use std::env;
use std::fs::{self, File};
use std::io::{self, BufReader, Read, Write};
@@ -113,7 +114,12 @@ fn run_benchmark() -> Result<(), Box<dyn
std::error::Error>> {
config.raw_dataset_bytes()? as f64 / GIB as f64,
dataset_started.elapsed().as_millis()
);
- let ground_truth = if let Some(ground_truth) =
dataset.ground_truth.clone() {
+ let published_truth = config
+ .filter
+ .is_none()
+ .then(|| dataset.ground_truth.clone())
+ .flatten();
+ let ground_truth = if let Some(ground_truth) = published_truth {
eprintln!(
"loaded published ground truth: {} queries, top-{}",
ground_truth.len(),
@@ -122,7 +128,7 @@ fn run_benchmark() -> Result<(), Box<dyn
std::error::Error>> {
ground_truth
} else {
let truth_started = Instant::now();
- let ground_truth = exact_ground_truth(&dataset, config.k);
+ let ground_truth = exact_ground_truth(&dataset, config.k,
config.filter.as_ref());
eprintln!(
"exact ground truth: {} queries in {} ms",
config.nq,
@@ -219,6 +225,8 @@ struct Config {
keep_indexes: bool,
reuse_index_path: Option<PathBuf>,
output_dir: PathBuf,
+ filter: Option<RoaringTreemap>,
+ filter_density: Option<f64>,
}
impl Config {
@@ -279,6 +287,23 @@ impl Config {
64,
)?;
let k = read_env("ANN_K", 10)?;
+ let filter_density: Option<f64> =
read_optional_env("ANN_FILTER_DENSITY")?;
+ let filter = filter_density
+ .map(|density| {
+ if !density.is_finite() || !(0.0..=1.0).contains(&density) {
+ return Err("ANN_FILTER_DENSITY must be finite and in [0,
1]");
+ }
+ let threshold = (density * 1_000_000.0) as u64;
+ Ok((0..n as u64)
+ .filter(|&id| {
+ let mut hash = id.wrapping_add(0x9e3779b97f4a7c15);
+ hash = (hash ^ (hash >>
30)).wrapping_mul(0xbf58476d1ce4e5b9);
+ hash = (hash ^ (hash >>
27)).wrapping_mul(0x94d049bb133111eb);
+ (hash ^ (hash >> 31)) % 1_000_000 < threshold
+ })
+ .collect::<RoaringTreemap>())
+ })
+ .transpose()?;
let nlist = read_env("ANN_NLIST", 64)?;
let nprobe = read_env("ANN_NPROBE", 8)?;
let train_n = match read_optional_env("ANN_TRAIN_N")? {
@@ -423,6 +448,8 @@ impl Config {
keep_indexes,
reuse_index_path,
output_dir,
+ filter,
+ filter_density,
})
}
@@ -827,6 +854,15 @@ fn run_query_case(
search: VectorSearchParams,
storage: StorageCase,
) -> Result<(), Box<dyn std::error::Error>> {
+ let filter_bytes = config
+ .filter
+ .as_ref()
+ .map(|filter| {
+ let mut bytes = Vec::new();
+ filter.serialize_into(&mut bytes).map(|()| bytes)
+ })
+ .transpose()?;
+ let filter = filter_bytes.as_deref();
eprintln!(
"querying {} with storage={} l_search={}",
index.name,
@@ -872,7 +908,7 @@ fn run_query_case(
let first_rounds_before = snapshot_stats(&stats).rounds;
let first_started = Instant::now();
- reader.search(&dataset.queries[..config.d], search)?;
+ benchmark_search(&mut reader, &dataset.queries[..config.d], search,
filter)?;
let first_elapsed = first_started.elapsed();
let first_query_us = if storage.virtualize_sequential_latency {
add_fixed_round_latency(
@@ -901,7 +937,7 @@ fn run_query_case(
for (query_index, query) in
dataset.queries.chunks_exact(config.d).enumerate() {
let rounds_before = snapshot_stats(&stats).rounds;
let started = Instant::now();
- reader.search(query, search).map_err(|error| {
+ benchmark_search(&mut reader, query, search, filter).map_err(|error| {
io::Error::new(
error.kind(),
format!("sequential query {query_index} failed: {error}"),
@@ -953,8 +989,22 @@ fn run_query_case(
batch_latency_enabled.store(true, Ordering::Relaxed);
reset_stats(&batch_stats);
let batch_started = Instant::now();
- let (result_ids, _) = batch_reader.search_batch(&dataset.queries,
config.nq, search)?;
+ let (result_ids, _) = benchmark_search_batch(
+ &mut batch_reader,
+ &dataset.queries,
+ config.nq,
+ search,
+ filter,
+ )?;
let batch_elapsed = batch_started.elapsed();
+ if let Some(filter) = &config.filter {
+ if result_ids
+ .iter()
+ .any(|&id| id >= 0 && !filter.contains(id as u64))
+ {
+ return Err("filtered search returned an ineligible row".into());
+ }
+ }
let rq_stats = batch_reader.ivfrq_search_stats().unwrap_or_default();
let batch_stats = snapshot_stats(&batch_stats);
let rq_refine_ratio = if rq_stats.eligible_vectors == 0 {
@@ -1023,7 +1073,7 @@ fn run_query_case(
while started.elapsed() < minimum {
for query in dataset.queries.chunks_exact(config.d) {
let query_started = Instant::now();
- std::hint::black_box(reader.search(query, search)?);
+ std::hint::black_box(benchmark_search(&mut reader, query,
search, filter)?);
// Keep one complete warm sweep for P95; bound storage to nq
samples.
if steady_sequential_queries == 0 {
steady_latencies.push(query_started.elapsed());
@@ -1034,7 +1084,13 @@ fn run_query_case(
steady_sequential_elapsed = started.elapsed();
let started = Instant::now();
while started.elapsed() < minimum {
- std::hint::black_box(batch_reader.search_batch(&dataset.queries,
config.nq, search)?);
+ std::hint::black_box(benchmark_search_batch(
+ &mut batch_reader,
+ &dataset.queries,
+ config.nq,
+ search,
+ filter,
+ )?);
steady_batch_queries += config.nq;
}
steady_batch_elapsed = started.elapsed();
@@ -1050,7 +1106,7 @@ fn run_query_case(
steady_batch_queries as f64 / steady_batch_elapsed.as_secs_f64()
};
println!(
-
"{dataset},{index},{storage},{n},{train_n},{raw_dataset_bytes},{nq},{d},{k},{nlist},{nprobe},{pq_m},{rq_bits},{build_distance},{raw_vector_encoding},{l_search},{build_ms},{train_ms},{add_ms},{write_ms},{peak_rss_bytes},{optimize_ms},{optimize_rounds},{optimize_ranges},{optimize_bytes},{file_bytes},{recall:.4},{first_us},{p50_us},{p95_us},{sequential_qps:.2},{seq_rounds},{seq_ranges},{seq_bytes},{batch_ms},{batch_qps:.2},{batch_rounds},{batch_ranges},{batch_bytes},{rq_seq_scanned}
[...]
+
"{dataset},{index},{storage},{n},{train_n},{raw_dataset_bytes},{nq},{d},{k},{nlist},{nprobe},{pq_m},{rq_bits},{build_distance},{raw_vector_encoding},{l_search},{build_ms},{train_ms},{add_ms},{write_ms},{peak_rss_bytes},{optimize_ms},{optimize_rounds},{optimize_ranges},{optimize_bytes},{file_bytes},{recall},{first_us},{p50_us},{p95_us},{sequential_qps:.2},{seq_rounds},{seq_ranges},{seq_bytes},{batch_ms},{batch_qps:.2},{batch_rounds},{batch_ranges},{batch_bytes},{rq_seq_scanned},{r
[...]
dataset = config.dataset_name,
index = index.name,
storage = storage.name,
@@ -1068,6 +1124,7 @@ fn run_query_case(
nprobe = search.configured_ivf_nprobe().unwrap_or(0),
pq_m = config.pq_m,
rq_bits = if index.name == "IVF_RQ" { config.rq_bits } else { 0 },
+ filter_density = config.filter_density.map(|density|
density.to_string()).unwrap_or_else(|| "none".to_string()),
build_distance = build_distance,
raw_vector_encoding = raw_vector_encoding,
l_search = search.configured_diskann_l_search().unwrap_or(0),
@@ -1120,11 +1177,40 @@ struct CsvRow;
impl CsvRow {
fn header() -> &'static str {
-
"dataset,index,storage,n,train_n,raw_dataset_bytes,nq,d,k,nlist,nprobe,pq_m,rq_bits,diskann_build_distance,diskann_raw_vector_encoding,l_search,build_ms,train_ms,add_ms,write_ms,peak_rss_bytes,optimize_ms,optimize_pread_rounds,optimize_pread_ranges,optimize_pread_bytes,file_bytes,recall_at_10,first_query_us,p50_query_us,p95_query_us,sequential_qps,sequential_pread_rounds,sequential_pread_ranges,sequential_pread_bytes,batch_ms,batch_qps,batch_pread_rounds,batch_pread_ranges,batch_
[...]
+
"dataset,index,storage,n,train_n,raw_dataset_bytes,nq,d,k,nlist,nprobe,pq_m,rq_bits,diskann_build_distance,diskann_raw_vector_encoding,l_search,build_ms,train_ms,add_ms,write_ms,peak_rss_bytes,optimize_ms,optimize_pread_rounds,optimize_pread_ranges,optimize_pread_bytes,file_bytes,recall_at_10,first_query_us,p50_query_us,p95_query_us,sequential_qps,sequential_pread_rounds,sequential_pread_ranges,sequential_pread_bytes,batch_ms,batch_qps,batch_pread_rounds,batch_pread_ranges,batch_
[...]
}
}
-fn exact_ground_truth(dataset: &Dataset, k: usize) -> Vec<Vec<i64>> {
+fn benchmark_search<R: SeekRead>(
+ reader: &mut VectorIndexReader<R>,
+ query: &[f32],
+ params: VectorSearchParams,
+ filter: Option<&[u8]>,
+) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ match filter {
+ Some(filter) => reader.search_with_roaring_filter(query, params,
filter),
+ None => reader.search(query, params),
+ }
+}
+
+fn benchmark_search_batch<R: SeekRead>(
+ reader: &mut VectorIndexReader<R>,
+ queries: &[f32],
+ nq: usize,
+ params: VectorSearchParams,
+ filter: Option<&[u8]>,
+) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ match filter {
+ Some(filter) => reader.search_batch_with_roaring_filter(queries, nq,
params, filter),
+ None => reader.search_batch(queries, nq, params),
+ }
+}
+
+fn exact_ground_truth(
+ dataset: &Dataset,
+ k: usize,
+ filter: Option<&RoaringTreemap>,
+) -> Vec<Vec<i64>> {
dataset
.queries
.par_chunks_exact(dataset.dimension)
@@ -1133,6 +1219,7 @@ fn exact_ground_truth(dataset: &Dataset, k: usize) ->
Vec<Vec<i64>> {
.data
.chunks_exact(dataset.dimension)
.enumerate()
+ .filter(|(row, _)| filter.is_none_or(|filter|
filter.contains(*row as u64)))
.map(|(row, vector)| (fvec_l2sqr(query, vector), row as i64))
.collect::<Vec<_>>();
let retained = k.min(distances.len());
diff --git a/core/src/ivfrq_io.rs b/core/src/ivfrq_io.rs
index e88b012..c6c7379 100644
--- a/core/src/ivfrq_io.rs
+++ b/core/src/ivfrq_io.rs
@@ -1195,10 +1195,23 @@ fn scan_blocked_list(
let code_block_start = block_start * code_size;
let factor_block_start = block_start * factor_fields;
let mut allowed = [true; RQ_SCAN_BLOCK_SIZE];
+ if let Some(filter) = filter {
+ for lane in 0..lanes {
+ allowed[lane] = filter.contains(list.ids[block_start + lane]);
+ }
+ }
+ let eligible = allowed[..lanes].iter().filter(|&&value| value).count();
+ stats.eligible_vectors =
stats.eligible_vectors.saturating_add(eligible);
+ stats.coarse_distance_evaluations =
+ stats.coarse_distance_evaluations.saturating_add(eligible);
+ if eligible == 0 {
+ block_start += lanes;
+ continue;
+ }
let mut coarse_unsigned = [0.0f32; RQ_SCAN_BLOCK_SIZE];
let used_fastscan = bits > 1
&& quantizer.padded_dimension() >= FASTSCAN_MIN_PADDED_DIMENSION
- && filter.is_none()
+ && eligible >= 8
&& lanes == RQ_SCAN_BLOCK_SIZE;
if used_fastscan {
quantizer.fastscan_coarse_block(
@@ -1208,11 +1221,8 @@ fn scan_blocked_list(
&mut coarse_unsigned,
);
stats.fastscan_blocks = stats.fastscan_blocks.saturating_add(1);
- } else if let Some(filter) = filter {
+ } else if filter.is_some() {
stats.scalar_blocks = stats.scalar_blocks.saturating_add(1);
- for lane in 0..lanes {
- allowed[lane] = filter.contains(list.ids[block_start + lane]);
- }
for byte_idx in 0..plane_size {
let byte_start = code_block_start + byte_idx * lanes;
for lane in 0..lanes {
@@ -1238,11 +1248,6 @@ fn scan_blocked_list(
}
}
}
- let eligible = allowed[..lanes].iter().filter(|&&value| value).count();
- stats.eligible_vectors =
stats.eligible_vectors.saturating_add(eligible);
- stats.coarse_distance_evaluations =
- stats.coarse_distance_evaluations.saturating_add(eligible);
-
let mut refine = [false; RQ_SCAN_BLOCK_SIZE];
if bits == 1 {
for lane in 0..lanes {
@@ -1276,28 +1281,61 @@ fn scan_blocked_list(
);
let mut lower = quantizer.lower_bound(estimate, factors,
query_terms);
if used_fastscan {
- lower -= factors.f_rescale.abs() *
quantizer.fastscan_ip_error(query);
+ lower = quantizer.fastscan_distance_lower_bound(
+ query,
+ coarse_unsigned[lane],
+ factors,
+ query_terms,
+ false,
+ );
}
- refine[lane] = heap.should_consider(lower);
+ refine[lane] = (used_fastscan && lower.is_nan()) ||
heap.should_consider(lower);
}
let refined = refine[..lanes].iter().filter(|&&value| value).count();
stats.refined_vectors = stats.refined_vectors.saturating_add(refined);
- stats.extra_plane_byte_lookups = stats
- .extra_plane_byte_lookups
- .saturating_add(refined.saturating_mul(bits -
1).saturating_mul(plane_size));
+ if refined == 0 {
+ block_start += lanes;
+ continue;
+ }
+ let mut survivors = [0usize; RQ_SCAN_BLOCK_SIZE];
+ let mut survivor_count = 0;
+ for (lane, &keep) in refine[..lanes].iter().enumerate() {
+ if keep {
+ survivors[survivor_count] = lane;
+ survivor_count += 1;
+ }
+ }
let mut full_unsigned = [0.0f32; RQ_SCAN_BLOCK_SIZE];
let sign_weight = (1usize << (bits - 1)) as f32;
for lane in 0..lanes {
full_unsigned[lane] = coarse_unsigned[lane] * sign_weight;
}
- for plane in 1..bits {
- let weight = (1usize << (bits - 1 - plane)) as f32;
- let plane_start = code_block_start + plane * plane_size * lanes;
- for byte_idx in 0..plane_size {
- let byte_start = plane_start + byte_idx * lanes;
- for lane in 0..lanes {
- if refine[lane] {
+ let full_fastscan = used_fastscan && refined >= 4;
+ if full_fastscan {
+ let mut plane_sums = [0.0; RQ_SCAN_BLOCK_SIZE];
+ for plane in 1..bits {
+ let weight = (1usize << (bits - 1 - plane)) as f32;
+ let plane_start = code_block_start + plane * plane_size *
lanes;
+ quantizer.fastscan_coarse_block(
+ query,
+ &blocked_codes[plane_start..plane_start + plane_size *
lanes],
+ &mut plane_sums,
+ );
+ for &lane in &survivors[..survivor_count] {
+ full_unsigned[lane] += weight * plane_sums[lane];
+ }
+ }
+ } else {
+ stats.extra_plane_byte_lookups = stats
+ .extra_plane_byte_lookups
+ .saturating_add(refined.saturating_mul(bits -
1).saturating_mul(plane_size));
+ for plane in 1..bits {
+ let weight = (1usize << (bits - 1 - plane)) as f32;
+ let plane_start = code_block_start + plane * plane_size *
lanes;
+ for byte_idx in 0..plane_size {
+ let byte_start = plane_start + byte_idx * lanes;
+ for &lane in &survivors[..survivor_count] {
full_unsigned[lane] += weight
* quantizer.byte_subset_sum(
query,
@@ -1308,10 +1346,7 @@ fn scan_blocked_list(
}
}
}
- for lane in 0..lanes {
- if !refine[lane] {
- continue;
- }
+ for &lane in &survivors[..survivor_count] {
let factors = read_block_factor(list, factor_block_start, lanes,
3, lane, false);
let mut distance = quantizer.estimate(
full_unsigned[lane] - center * query_sum,
@@ -1319,9 +1354,14 @@ fn scan_blocked_list(
query_terms,
);
if used_fastscan {
- let distance_error =
- factors.f_rescale.abs() * sign_weight *
quantizer.fastscan_ip_error(query);
- if !heap.should_consider(distance - distance_error) {
+ let lower = quantizer.fastscan_distance_lower_bound(
+ query,
+ full_unsigned[lane],
+ factors,
+ query_terms,
+ true,
+ );
+ if !lower.is_nan() && !heap.should_consider(lower) {
continue;
}
let mut exact_coarse = 0.0f32;
@@ -2132,7 +2172,7 @@ mod tests {
assert_eq!(unfiltered, filtered);
assert!(unfiltered_reader.last_search_stats().fastscan_blocks > 0);
- assert_eq!(filtered_reader.last_search_stats().fastscan_blocks, 0);
+ assert!(filtered_reader.last_search_stats().fastscan_blocks > 0);
}
#[test]
@@ -2166,11 +2206,15 @@ mod tests {
assert!(stats.refined_vectors <= stats.eligible_vectors);
assert!(stats.final_distance_evaluations > 0);
assert!(stats.final_distance_evaluations <= stats.refined_vectors);
- assert_eq!(
- stats.extra_plane_byte_lookups,
- (stats.refined_vectors + stats.refined_coarse_byte_lookups /
index.plane_size())
- * (index.bits - 1)
- * index.plane_size()
+ assert!(
+ stats.extra_plane_byte_lookups
+ >= stats.final_distance_evaluations * (index.bits - 1) *
index.plane_size()
+ );
+ assert!(
+ stats.extra_plane_byte_lookups
+ < (stats.refined_vectors + stats.refined_coarse_byte_lookups /
index.plane_size())
+ * (index.bits - 1)
+ * index.plane_size()
);
assert!(stats.heap_admissions > 0);
assert!(stats.fastscan_blocks > 0);
@@ -2181,6 +2225,91 @@ mod tests {
);
}
+ #[test]
+ fn
ivfrq_full_plane_fastscan_matches_scalar_scoring_for_metrics_and_widths() {
+ let d = 960;
+ let n = 259; // Include a partial final block.
+ let nq = 4;
+ let mut state = 42u64;
+ let mut value = || {
+ state ^= state << 13;
+ state ^= state >> 7;
+ state ^= state << 17;
+ (state >> 40) as f32 / (1u32 << 24) as f32 - 0.5
+ };
+ let data = (0..n * d).map(|_| value()).collect::<Vec<_>>();
+ let queries = (0..nq * d).map(|_| value()).collect::<Vec<_>>();
+ let ids = (0..n as i64).collect::<Vec<_>>();
+ let all_rows = ids.iter().copied().collect::<HashSet<_>>();
+ for metric in [MetricType::L2, MetricType::Cosine,
MetricType::InnerProduct] {
+ for bits in [2, 4, 8] {
+ let mut index = IVFRQIndex::with_bits(d, 1, bits, metric);
+ index.set_quantizer_centroids(vec![0.0; d]);
+ index.add(&data, &ids, n);
+ let mut bytes = Vec::new();
+ write_ivfrq_index(&index, &mut PosWriter::new(&mut
bytes)).unwrap();
+ let mut fast =
IVFRQIndexReader::open(Cursor::new(bytes.clone())).unwrap();
+ let mut scalar =
IVFRQIndexReader::open(Cursor::new(bytes)).unwrap();
+ let list = fast.read_inverted_list(0).unwrap();
+ let processed = preprocess_vectors(&queries, nq, d, metric);
+ for query in processed.chunks_exact(d) {
+ let mut rotated = vec![0.0; d];
+ fast.rotation.rotate(query, &mut rotated, &mut vec![0.0;
d]);
+ let context = fast.quantizer.prepare_query(rotated);
+ let terms = fast.quantizer.query_terms(&context,
&vec![0.0; d], metric);
+ for stride in [1, 2, 16] {
+ let filter = ids
+ .iter()
+ .copied()
+ .filter(|id| id % stride == 0)
+ .collect::<HashSet<_>>();
+ let mut oracle = TopKHeap::new(10);
+ // The range scan evaluates every allowed full estimate
+ // without either FastScan or coarse-bound pruning.
+ scan_range_blocked_list(
+ &list,
+ &fast.quantizer,
+ &context,
+ terms,
+ Some(&filter),
+ &mut oracle,
+ )
+ .unwrap();
+ let mut actual = TopKHeap::new(10);
+ scan_blocked_list(
+ &list,
+ &fast.quantizer,
+ &context,
+ terms,
+ Some(&filter),
+ &mut actual,
+ &mut IVFRQSearchStats::default(),
+ usize::MAX,
+ );
+ assert_eq!(
+ actual.into_sorted(),
+ oracle.into_sorted(),
+ "exhaustive oracle: metric={metric:?},
bits={bits}, stride={stride}"
+ );
+ }
+ }
+ for k in [1, 10, 64] {
+ let expected = search_batch_ivfrq_reader_filter(
+ &mut scalar,
+ &queries,
+ nq,
+ k,
+ 1,
+ Some(&all_rows),
+ )
+ .unwrap();
+ let actual = search_batch_ivfrq_reader(&mut fast,
&queries, nq, k, 1).unwrap();
+ assert_eq!(actual, expected, "metric={metric:?},
bits={bits}, k={k}");
+ }
+ }
+ }
+ }
+
#[test]
fn ivfrq_resident_metadata_load_uses_one_read_round() {
let d = 64;
diff --git a/core/src/rq.rs b/core/src/rq.rs
index 2bf8074..eebf2c4 100644
--- a/core/src/rq.rs
+++ b/core/src/rq.rs
@@ -180,6 +180,7 @@ pub struct RQQueryContext {
fastscan_offset: f32,
fastscan_scale: f32,
fastscan_ip_error: f32,
+ fastscan_full_ip_error: f32,
}
#[derive(Debug, Clone, Copy)]
@@ -331,12 +332,12 @@ impl RaBitQuantizer {
let fastscan_scale = max_group_range / u8::MAX as f32;
let mut fastscan_lut = vec![0u8; nibble_subset_sums.len()];
- let mut fastscan_ip_error = 0.0f32;
+ let mut fastscan_ip_error = 0.0f64;
for group in 0..nibble_groups {
let min = group_mins[group];
let exact = &nibble_subset_sums[group * 16..(group + 1) * 16];
let quantized = &mut fastscan_lut[group * 16..(group + 1) * 16];
- let mut group_error = 0.0f32;
+ let mut group_error = 0.0f64;
for (exact, quantized) in exact.iter().zip(quantized) {
let value = if fastscan_scale <= f32::EPSILON {
0
@@ -346,18 +347,49 @@ impl RaBitQuantizer {
.clamp(0.0, u8::MAX as f32) as u8
};
*quantized = value;
- let reconstructed = min + fastscan_scale * value as f32;
- group_error = group_error.max((reconstructed - *exact).abs());
+ let reconstructed = min as f64 + fastscan_scale as f64 * value
as f64;
+ group_error = group_error.max((reconstructed - *exact as
f64).abs());
}
fastscan_ip_error += group_error;
}
let fastscan_offset = group_mins.iter().sum::<f32>();
- let rounding_guard = (fastscan_offset.abs()
- + fastscan_scale * u8::MAX as f32 * nibble_groups as f32
- + rotated_query.iter().map(|value| value.abs()).sum::<f32>())
- * f32::EPSILON
- * 8.0;
- fastscan_ip_error += rounding_guard;
+ let query_abs_sum = rotated_query
+ .iter()
+ .map(|value| value.abs() as f64)
+ .sum::<f64>();
+ let offset_error = (fastscan_offset as f64
+ - group_mins.iter().map(|&value| value as f64).sum::<f64>())
+ .abs();
+ // The reference builds 8-coordinate F32 subset sums and accumulates
+ // their bytes in order. Account for its accumulation, the different
+ // 4-coordinate LUT grouping, and the SIMD integer-to-F32 conversion,
+ // multiply and add. Use a conservative gamma bound and round upwards.
+ let gamma = |operations: usize| {
+ let error = operations as f64 * f32::EPSILON as f64;
+ if error < 0.5 {
+ error / (1.0 - error)
+ } else {
+ f64::INFINITY
+ }
+ };
+ let rounding_guard = gamma(self.plane_size + 16) * query_abs_sum
+ + 4.0
+ * f32::EPSILON as f64
+ * (fastscan_offset.abs() as f64
+ + fastscan_scale as f64 * u8::MAX as f64 * nibble_groups
as f64);
+ let fastscan_ip_error =
+ ((fastscan_ip_error + offset_error + rounding_guard) as
f32).next_up();
+ // Full estimates combine all planes. Include both each plane's LUT
+ // error and a forward-error allowance for the scalar reference's
+ // weighted byte-by-byte accumulation.
+ let max_level = ((1usize << self.bits) - 1) as f32;
+ let full_accumulation_guard = 2.0
+ * gamma(self.plane_size * self.bits + 16)
+ * max_level as f64
+ * (query_abs_sum + fastscan_ip_error as f64);
+ let fastscan_full_ip_error = ((max_level as f64 * fastscan_ip_error as
f64
+ + full_accumulation_guard) as f32)
+ .next_up();
RQQueryContext {
rotated_query,
sum,
@@ -366,6 +398,7 @@ impl RaBitQuantizer {
fastscan_offset,
fastscan_scale,
fastscan_ip_error,
+ fastscan_full_ip_error,
}
}
@@ -442,10 +475,53 @@ impl RaBitQuantizer {
context.byte_subset_sums[byte_idx * 256 + pattern as usize]
}
+ #[cfg(test)]
pub(crate) fn fastscan_ip_error(&self, context: &RQQueryContext) -> f32 {
context.fastscan_ip_error
}
+ #[cfg(test)]
+ pub(crate) fn fastscan_full_ip_error(&self, context: &RQQueryContext) ->
f32 {
+ context.fastscan_full_ip_error
+ }
+
+ pub(crate) fn fastscan_distance_lower_bound(
+ &self,
+ context: &RQQueryContext,
+ unsigned: f32,
+ factors: RQCodeFactors,
+ terms: RQQueryTerms,
+ full: bool,
+ ) -> f32 {
+ let error = if full {
+ context.fastscan_full_ip_error
+ } else {
+ context.fastscan_ip_error
+ };
+ // Evaluate the appropriate endpoint with the exact estimator's F32
+ // operation order. Each operation is monotone, including its rounding;
+ // this also covers cancellation against large additive factors. A
+ // final outward step preserves signed-zero heap comparisons. NaN
+ // endpoints cannot certify pruning and must fall through to
refinement.
+ let endpoint = if factors.f_rescale.is_sign_negative() {
+ (unsigned + error).next_up()
+ } else {
+ (unsigned - error).next_down()
+ };
+ let center = if full {
+ ((1usize << self.bits) - 1) as f32 * 0.5
+ } else {
+ 0.5
+ };
+ let estimate = self.estimate(endpoint - center * context.sum, factors,
terms);
+ (if full {
+ estimate
+ } else {
+ self.lower_bound(estimate, factors, terms)
+ })
+ .next_down()
+ }
+
pub(crate) fn fastscan_coarse_block(
&self,
context: &RQQueryContext,
@@ -688,32 +764,64 @@ fn quantize_centered_levels(
) {
let max_code = (1usize << bits) - 1;
let center = max_code as f32 * 0.5;
- let max_abs = residual
+ let (max_abs, residual_norm_sqr) = residual
.iter()
- .map(|value| value.abs())
- .fold(0.0f32, f32::max);
+ .fold((0.0f32, 0.0f32), |(max, norm), &value| {
+ (max.max(value.abs()), norm + value * value)
+ });
if max_abs <= f32::EPSILON {
levels.fill(0);
centered.fill(-center);
return;
}
- let mut scale = 2.0 * max_abs / max_code as f32;
- for _ in 0..QUANTIZATION_REFINEMENT_ROUNDS {
- let mut dot = 0.0f32;
- let mut norm_sqr = 0.0f32;
- for (dim, &value) in residual.iter().enumerate() {
- let level = (value / scale + center).round().clamp(0.0, max_code
as f32) as u8;
- let centered_level = level as f32 - center;
- levels[dim] = level;
- centered[dim] = centered_level;
- dot += value * centered_level;
- norm_sqr += centered_level * centered_level;
- }
- if dot <= f32::EPSILON || norm_sqr <= f32::EPSILON {
- break;
+ // The estimator corrects the code's length afterwards, so its error
depends
+ // on alignment rather than on the least-squares reconstruction scale. A
+ // max-based start can settle on a poor direction when a few coordinates
are
+ // large. For padded dimensions >= 256, also try a Gaussian clipping start,
+ // retaining the best direction from either trajectory. Public and
synthetic
+ // benchmarks did not establish a recall benefit at lower dimensions, so
+ // those retain the original three-round code exactly.
+ const CLIP_SIGMA: [f32; 8] = [0.8, 1.5, 2.15, 2.51, 2.94, 3.28, 3.6, 3.9];
+ let max_scale = max_abs / center;
+ let rms = (residual_norm_sqr / residual.len() as f32).sqrt();
+ let clipped_scale = (rms * CLIP_SIGMA[bits - 1] / center).min(max_scale);
+ let mut best_scale = max_scale;
+ let mut best_alignment = f64::NEG_INFINITY;
+ let quality_search = residual.len() >= 256 && bits > 1;
+ for initial_scale in [max_scale, clipped_scale]
+ .into_iter()
+ .take(if quality_search { 2 } else { 1 })
+ {
+ let mut scale = initial_scale;
+ for _ in 0..QUANTIZATION_REFINEMENT_ROUNDS {
+ let mut dot = 0.0f32;
+ let mut norm_sqr = 0.0f32;
+ let mut precise_dot = 0.0f64;
+ for &value in residual {
+ let level = (value / scale + center).round().clamp(0.0,
max_code as f32);
+ let centered_level = level - center;
+ dot += value * centered_level;
+ norm_sqr += centered_level * centered_level;
+ precise_dot += value as f64 * centered_level as f64;
+ }
+ if dot <= f32::EPSILON || norm_sqr <= f32::EPSILON {
+ break;
+ }
+ let alignment = precise_dot / (norm_sqr as f64).sqrt();
+ if !quality_search || alignment > best_alignment {
+ best_alignment = alignment;
+ best_scale = scale;
+ }
+ scale = dot / norm_sqr;
}
- scale = dot / norm_sqr;
+ }
+ for (dim, &value) in residual.iter().enumerate() {
+ let level = (value / best_scale + center)
+ .round()
+ .clamp(0.0, max_code as f32) as u8;
+ levels[dim] = level;
+ centered[dim] = level as f32 - center;
}
}
@@ -949,6 +1057,142 @@ mod tests {
}
}
+ #[test]
+ fn fastscan_distance_bound_survives_a_one_ulp_rounding_boundary() {
+ let quantizer = RaBitQuantizer::new(256, 4);
+ let mut context = quantizer.prepare_query(vec![0.0; 256]);
+ let boundary = 0.25 * f32::EPSILON;
+ let approximate_ip = boundary.next_down();
+ let exact_ip = boundary.next_up();
+ // A valid IP interval that straddles a rounding boundary after adding
+ // the large constant. Subtracting abs(scale)*IP_error from the rounded
+ // distance would round back to 1 and wrongly reject the exact winner.
+ context.fastscan_full_ip_error = (exact_ip - approximate_ip).next_up();
+ let factors = RQCodeFactors {
+ f_add: 1.0,
+ f_rescale: -1.0,
+ f_error: 0.0,
+ };
+ let terms = RQQueryTerms {
+ g_add: 0.0,
+ g_error: 0.0,
+ };
+ let approximate_distance = quantizer.estimate(approximate_ip, factors,
terms);
+ let exact_distance = quantizer.estimate(exact_ip, factors, terms);
+ assert_eq!(approximate_distance, 1.0);
+ assert!(exact_distance < 1.0);
+ assert_eq!(approximate_distance - context.fastscan_full_ip_error, 1.0);
+ let lower =
+ quantizer.fastscan_distance_lower_bound(&context, approximate_ip,
factors, terms, true);
+ assert!(lower <= exact_distance);
+ }
+
+ #[test]
+ fn
fastscan_distance_bounds_cover_mixed_scales_and_nonzero_additive_terms() {
+ let quantizer = RaBitQuantizer::new(960, 4);
+ for amplitude in [1e-10, 1e-4, 1.0, 1e8] {
+ let query = (0..960)
+ .map(|i| ((i * 31 % 101) as f32 - 50.0) * amplitude)
+ .collect();
+ let context = quantizer.prepare_query(query);
+ for add in [-1e20, -1e8, 0.0, 1e8, 1e20] {
+ for scale in [-1e10, -1.0, -1e-10, 0.0, 1e-10, 1.0, 1e10] {
+ let factors = RQCodeFactors {
+ f_add: add,
+ f_rescale: scale,
+ f_error: 0.3,
+ };
+ let terms = RQQueryTerms {
+ g_add: -0.25 * add,
+ g_error: amplitude,
+ };
+ for full in [false, true] {
+ let error = if full {
+ context.fastscan_full_ip_error
+ } else {
+ context.fastscan_ip_error
+ };
+ for unsigned in [-2.0 * amplitude, 0.0, 3.0 *
amplitude] {
+ let lower =
quantizer.fastscan_distance_lower_bound(
+ &context, unsigned, factors, terms, full,
+ );
+ for exact in [unsigned - error, unsigned, unsigned
+ error] {
+ let center = if full { 7.5 } else { 0.5 };
+ let estimate = quantizer.estimate(
+ exact - center * context.sum,
+ factors,
+ terms,
+ );
+ let reference = if full {
+ estimate
+ } else {
+ quantizer.lower_bound(estimate, factors,
terms)
+ };
+ assert!(lower.is_nan() ||
lower.total_cmp(&reference).is_le(),
+ "amplitude={amplitude}, add={add},
scale={scale}, full={full}, lower={lower}, reference={reference}");
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn full_fastscan_error_covers_weighted_planes_and_accumulation() {
+ for d in [64, 256, 960, 2048] {
+ for bits in [2, 4, 8] {
+ for amplitude in [1e-10, 0.013, 1e8] {
+ let quantizer = RaBitQuantizer::new(d, bits);
+ let query = (0..d)
+ .map(|i| ((i * 31 % 101) as f32 - 50.0) * amplitude)
+ .collect();
+ let context = quantizer.prepare_query(query);
+ let codes = (0..quantizer.code_size() * RQ_SCAN_BLOCK_SIZE)
+ .map(|i| (i * 37 + i / 13 + 11) as u8)
+ .collect::<Vec<_>>();
+ let mut approximate = [0.0; RQ_SCAN_BLOCK_SIZE];
+ let mut exact = [0.0; RQ_SCAN_BLOCK_SIZE];
+ for plane in 0..bits {
+ let start = plane * quantizer.plane_size() *
RQ_SCAN_BLOCK_SIZE;
+ let weight = (1usize << (bits - 1 - plane)) as f32;
+ let mut plane_sums = [0.0; RQ_SCAN_BLOCK_SIZE];
+ quantizer.fastscan_coarse_block(&context,
&codes[start..], &mut plane_sums);
+ for lane in 0..RQ_SCAN_BLOCK_SIZE {
+ approximate[lane] += weight * plane_sums[lane];
+ if plane == 0 {
+ for byte in 0..quantizer.plane_size() {
+ exact[lane] += quantizer.byte_subset_sum(
+ &context,
+ byte,
+ codes[start + byte *
RQ_SCAN_BLOCK_SIZE + lane],
+ );
+ }
+ exact[lane] *= weight;
+ } else {
+ for byte in 0..quantizer.plane_size() {
+ exact[lane] += weight
+ * quantizer.byte_subset_sum(
+ &context,
+ byte,
+ codes[start + byte *
RQ_SCAN_BLOCK_SIZE + lane],
+ );
+ }
+ }
+ }
+ }
+ for lane in 0..RQ_SCAN_BLOCK_SIZE {
+ assert!(
+ (approximate[lane] - exact[lane]).abs()
+ <= quantizer.fastscan_full_ip_error(&context),
+ "d={d} bits={bits} lane={lane}"
+ );
+ }
+ }
+ }
+ }
+ }
+
#[test]
fn four_bit_estimator_is_exact_for_the_encoded_vector() {
let d = 64;
@@ -975,6 +1219,69 @@ mod tests {
assert!(estimate.abs() < 1e-4, "self distance was {estimate}");
}
+ #[test]
+ fn scale_search_preserves_or_improves_original_encoder_alignment() {
+ let mut improved = 0;
+ for d in [64, 128, 960] {
+ let rotation = RQRotation::new(d, 42, DEFAULT_RQ_ROTATION_ROUNDS);
+ let mut scratch = vec![0.0; d];
+ for sample in 0..12 {
+ let input = (0..d)
+ .map(|i| {
+ if sample == 0 {
+ if i == 0 {
+ 8.0
+ } else {
+ 1.0
+ }
+ } else {
+ ((i * 31 + sample * 17) % 103) as f32 * 0.03 - 1.5
+ }
+ })
+ .collect::<Vec<_>>();
+ let mut residual = vec![0.0; d];
+ rotation.rotate(&input, &mut residual, &mut scratch);
+ for bits in 1..=8 {
+ let max_code = (1usize << bits) - 1;
+ let center = max_code as f32 * 0.5;
+ let max_abs = residual.iter().map(|value|
value.abs()).fold(0.0, f32::max);
+ let mut scale = max_abs / center;
+ let mut original = vec![0.0; d];
+ for _ in 0..3 {
+ for (&value, code) in residual.iter().zip(&mut
original) {
+ *code = (value / scale +
center).round().clamp(0.0, max_code as f32)
+ - center;
+ }
+ let dot: f32 = residual.iter().zip(&original).map(|(x,
c)| x * c).sum();
+ scale = dot / original.iter().map(|c| c *
c).sum::<f32>();
+ }
+ let mut levels = vec![0; d];
+ let mut actual = vec![0.0; d];
+ quantize_centered_levels(&residual, bits, &mut levels,
&mut actual);
+ let error = |codes: &[f32]| {
+ compute_factors(&residual, &vec![0.0; d], codes,
MetricType::L2).f_error
+ };
+ assert!(
+ error(&actual) <= error(&original) + 1e-4,
+ "alignment regressed: d={d}, sample={sample},
bits={bits}, actual={}, original={}", error(&actual), error(&original)
+ );
+ if d < 256 {
+ assert_eq!(
+ actual, original,
+ "low-dimensional codes must remain unchanged"
+ );
+ } else if error(&actual) + 1e-4 < error(&original) {
+ improved += 1;
+ }
+ }
+ }
+ }
+ assert!(
+ improved > 0,
+ "high-dimensional search must improve actual reconstruction bounds"
+ );
+ }
+
#[test]
fn more_stored_bits_reduce_reconstruction_error() {
let d = 64;
diff --git a/docs/development.html b/docs/development.html
index fe357a2..8b89eca 100644
--- a/docs/development.html
+++ b/docs/development.html
@@ -104,6 +104,8 @@ cargo bench -p paimon-vindex-core --bench
ann_bench</code></pre></div>
<div
class="table-wrap"><table><thead><tr><th>Variable</th><th>Meaning</th></tr></thead><tbody><tr><td><code>ANN_DATASET_NAME</code></td><td>Comma-free
label written to every CSV row</td></tr><tr><td><code>ANN_BASE_FVECS /
ANN_QUERY_FVECS / ANN_GROUND_TRUTH_IVECS</code></td><td>Optional public-data
files; set all three together. Their vector count, query count, dimension, and
ground-truth width are inspected before the full payload is
loaded.</td></tr><tr><td><code>ANN_N / ANN_ [...]
<div class="callout warning"><strong>Large-run memory
boundary</strong>The current public writer API accepts an in-memory vector
slice and each index writer retains its encoded or raw build state. A raw 10
GiB DiskANN run therefore needs roughly the 10 GiB source allocation plus
DiskANN's separately budgeted build state. On a 48 GiB machine, use a 32 GiB
DiskANN budget and run one index per process. This benchmark validates large
immutable builds; it is not a streaming-ingest b [...]
<p>The benchmark executes three serving cases by default.
<code>local_ssd_warm_cache</code> uses the real index file with no artificial
delay. <code>remote_cache_2ms</code> adds a fixed 2 ms delay per
<code>pread</code> call while reading all ranges in that call concurrently.
<code>object_store_20ms</code> uses the <code>ObjectStore</code> read plan:
open/optimization and sequential-query latency are the measured CPU/I/O time
plus 20 ms for every observed dependent read round, [...]
+ <p><code>ANN_FILTER_DENSITY</code> optionally supplies a
deterministic hash-based Roaring allow-list with a fraction in
<code>[0,1]</code>. Unset means no filter; <code>1</code> exercises an explicit
all-row filter. Filtered runs independently recompute exact L2 ground truth
from allowed source vectors, outside query timing, and check result eligibility
outside batch timing. The CSV records the configured
<code>filter_density</code>. Keep the same density, data, and label for b [...]
+ <p>For measured IVF-RQ tuning, <code>tools/tune_ivfrq.py</code>
sweeps persisted bit widths and probe widths with <code>ann_bench</code>,
reuses each built file, and verifies the selected configuration on disjoint
held-out queries. It saves raw CSVs, logs, environments, and
<code>recommendation.json</code>; see <code>tools/README.md</code> for the
complete command. The tool leaves defaults in place when held-out measurements
do not justify a change.</p>
</section>
<section class="article-section" id="ivfsq-bench">
diff --git a/docs/ivf-rq.html b/docs/ivf-rq.html
index a4a3fd3..4914511 100644
--- a/docs/ivf-rq.html
+++ b/docs/ivf-rq.html
@@ -24,7 +24,7 @@
<section class="article-section" id="design">
<h2>Design and distance estimation</h2>
- <div class="pipeline"><div class="pipeline-item"><span
class="pipeline-index">1</span><div><h3>Train and assign IVF</h3><p>Learn
<code>nlist</code> coarse centroids and form <code>r = x −
c</code>.</p></div></div><div class="pipeline-item"><span
class="pipeline-index">2</span><div><h3>Rotate deterministically</h3><p>Pad to
a multiple of 64, then apply four rounds of random signs, 64-wide normalized
FHT, and seeded permutation. The transform is orthogonal and reconstructed from
[...]
+ <div class="pipeline"><div class="pipeline-item"><span
class="pipeline-index">1</span><div><h3>Train and assign IVF</h3><p>Learn
<code>nlist</code> coarse centroids and form <code>r = x −
c</code>.</p></div></div><div class="pipeline-item"><span
class="pipeline-index">2</span><div><h3>Rotate deterministically</h3><p>Pad to
a multiple of 64, then apply four rounds of random signs, 64-wide normalized
FHT, and seeded permutation. The transform is orthogonal and reconstructed from
[...]
<p>The full estimator is exact for a query equal to the encoded
source vector, while ranking other vectors through the scaled reconstruction.
L2, inner product, and cosine have metric-specific additive/rescale factors;
cosine inputs are normalized before IVF assignment.</p>
</section>
@@ -79,6 +79,23 @@ let params = VectorSearchParams::new(10,
64);</code></pre></div>
<section class="article-section" id="benchmarks">
<h2>Public-corpus measurements</h2>
+ <h3>11 November 2026: benchmark-gated optimization</h3>
+ <p>Release builds with Rust 1.95 on Apple M4 Pro (48 GiB, 12 Rayon
workers), full public corpora, 1,000 held-out queries, Top-10,
<code>nlist=1024</code>, <code>nprobe=64</code>, four stored bits, and warm
APFS pages. Each value below is a three-process median from alternating
baseline/candidate runs against baseline <code>b083416</code>. QPS and P95 use
the benchmark's warm timing phase. SIFT and GIST contain one million rows;
normalized GloVe-100 contains 1,183,514. GIST quer [...]
+ <div
class="table-wrap"><table><thead><tr><th>Dataset</th><th>Recall@10, before →
after</th><th>Batch QPS, before → after</th><th>Batch gain</th><th>Sequential
P95, before → after</th></tr></thead><tbody><tr><td>SIFT1M, 128d</td><td>0.9148
→ 0.9148</td><td>2,857 → 4,078</td><td>42.7%</td><td>1.048 → 1.004
ms</td></tr><tr><td>GIST1M, 960d</td><td>0.9039 → 0.9153</td><td>421 →
2,765</td><td>6.57× throughput</td><td>4.943 → 2.545
ms</td></tr><tr><td>GloVe-100, 100d</td><td>0.8203 [...]
+ <p>The high-dimensional encoder has a build trade-off: an
independent three-build GIST A/B raised recall by 1.14 percentage points at
unchanged file size, with median add time increasing from 5.339 to 5.797
seconds. Below 256 padded dimensions, the new scale search was removed because
recall gains were small or inconsistent; original codes are retained. The scan
changes preserve the original full F32 estimate of each stored row.</p>
+ <p>Filtered same-file A/B runs used 100 public queries and
independently recomputed filtered ground truth, again with three-process
medians. At 1% allow-list density, batch throughput improved by 14.7% / 41.8% /
16.0% on SIFT/GIST/GloVe. At 50%, GIST improved from 451 to 1,616 QPS (3.58×),
while SIFT and GloVe were effectively unchanged. Every paired filtered recall
was unchanged. Dense filtering does not establish a speedup for the
low-dimensional path.</p>
+ <p>Two experiments were removed. SIMD lower-bound arithmetic did not
improve throughput consistently across all three shapes. A v1 staged sign/ex
read prototype was verified query-by-query on 100 SIFT and GloVe queries but
changed one read round into three: SIFT local P95 rose from 1.012 to 12.320 ms
while bytes fell only 0.07%; fixed-2-ms P95 rose from 5.247 to 19.804 ms, and
fixed-20-ms P95 from 20.979 to 72.315 ms. These remote cases are latency
models, not live object-store [...]
+ <p>Offline calibration also has a concrete cost trade-off. With the
first 200 SIFT queries selecting parameters and the remaining 800 used only for
three-run validation, <code>tools/tune_ivfrq.py</code> selected 5 bits / 32
probes for a 0.90 recall target. Held-out recall improved from 0.9161 to
0.9365, batch QPS from 3,866 to 5,758, and P95 from 1.009 to 0.707 ms; file
size grew from 86.3 to 102.3 MB. This does not change library defaults. Compare
options at the application's [...]
+ <h3>Combined build, storage-model and compatibility recheck</h3>
+ <p>The combined three-optimization version was rebuilt against the
same <code>ann_bench</code> source as baseline <code>b083416</code>, with both
dependency graphs pinned to the repository lock file. Three alternating process
pairs each built a complete index, then queried that same file under local warm
disk, injected 2 ms latency and the 20 ms object-store model. Settings remained
four stored bits, <code>nlist=1024</code>, <code>nprobe=64</code>, 65,536
training vectors, 1,00 [...]
+ <div
class="table-wrap"><table><thead><tr><th>Dataset</th><th>Recall@10, before →
after</th><th>Total build</th><th>Train</th><th>Add / encode</th><th>Write +
sync</th></tr></thead><tbody><tr><td>SIFT1M</td><td>0.9148 →
0.9148</td><td>1.092 → 1.117 s</td><td>204 → 207 ms</td><td>751 → 784
ms</td><td>118 → 134 ms</td></tr><tr><td>GIST1M</td><td>0.9039 →
0.9153</td><td>8.151 → 7.602 s</td><td>1442 → 1423 ms</td><td>5836 → 5604
ms</td><td>590 → 573 ms</td></tr><tr><td>GloVe-100</t [...]
+ <p>Each column is medianed independently, so stage medians need not
add to the total median. Build times remain of the same order; their
overlapping sample ranges do not establish a consistent construction speedup.
Recall is identical across all three storage models within each version.</p>
+ <div
class="table-wrap"><table><thead><tr><th>Dataset</th><th>Storage
model</th><th>Single-query P95, before → after</th><th>Batch QPS, before →
after</th></tr></thead><tbody><tr><td>SIFT1M</td><td>Local warm
disk</td><td>1.056 → 3.138 ms</td><td>2,885 →
3,804</td></tr><tr><td>SIFT1M</td><td>2 ms injected</td><td>5.168 → 4.809
ms</td><td>2,743 → 3,499</td></tr><tr><td>SIFT1M</td><td>20 ms
model</td><td>21.066 → 21.923 ms</td><td>2,496 →
3,319</td></tr><tr><td>GIST1M</td><td>Loc [...]
+ <p>These are the first complete sequential sweep and one 1,000-query
batch, rather than the optional steady timing phase reported above. SIFT
optimized local P95 varied from 1.013 to 4.426 ms across the original three
runs; the 3.138 ms median is retained in the table. A separate three-pair,
same-file warm control measured 1.200 → 1.061 ms for sustained sequential P95
and did not reproduce a stable regression. Low-dimensional tail latency is
therefore less conclusive than throu [...]
+ <p>The 2 ms case actually sleeps per positional-read call and
includes operating-system timer and scheduling overhead. The 20 ms case
computes sequential latency as measured CPU/I/O time plus 20 ms per dependent
round; batch timing injects the sleep. Neither models live object storage,
bandwidth, retries or throttling.</p>
+ <p><strong>Storage compatibility verified in both
directions.</strong> Header, write, metadata-read and payload-decode code is
unchanged; v1 retains its 64-byte header, required flags, rotation type 2 and
factor layout 3. Both versions passed the existing golden fixtures. A separate
old/new writer-reader matrix generated 144 files covering bits 1–8,
L2/IP/cosine, dimensions 70/256/960, signed row IDs, partial 32-row blocks and
zero queries. All 288 reader/file checks matched To [...]
+ <p>Actual million-row GIST cross-reading also passed: the old Reader
reading the new file retained Recall@10 0.9153, and the new Reader reading the
old file retained 0.9039. Existing v1 indexes need no migration to obtain
scan/filter improvements. The new high-dimensional scale search affects newly
built codes, so its recall improvement requires rebuilding; the resulting file
remains readable by the old Reader.</p>
+ <h3>25 July 2026 historical measurements</h3>
<p>Apple M4 Pro, 12 Rayon workers, one million base vectors, 1,000
published queries, <code>nlist=1024</code>, <code>nprobe=64</code>, Top-10,
warm APFS pages. Times are release-build measurements from 25 July 2026.</p>
<div
class="table-wrap"><table><thead><tr><th>Dataset</th><th>Build</th><th>File</th><th>Recall@10</th><th>Local
P95</th><th>Local batch QPS</th><th>Read /
query</th></tr></thead><tbody><tr><td>SIFT1M, 128d</td><td>3.92 s</td><td>86.3
MB</td><td>0.9148</td><td>1.20 ms</td><td>3,074</td><td>5.81
MB</td></tr><tr><td>GIST1M, 960d</td><td>23.5 s</td><td>505.8
MB</td><td>0.9039</td><td>4.41 ms</td><td>444</td><td>38.81
MB</td></tr><tr><td>GloVe-100, 100d</td><td>4.03 s</td><td>102.1 [...]
<p>On SIFT1M, a controlled bit sweep produced Recall@10 0.7233 /
0.8365 / 0.9149 / 0.9530 / 0.9731 for 2 / 3 / 4 / 5 / 6 bits. The compact v1
factor layout removes four unused bytes per row, reducing the corresponding
files from 58.3 / 74.3 / 90.3 / 106.3 / 122.3 MB to approximately 54.3 / 70.3 /
86.3 / 102.3 / 118.3 MB without changing the distance estimator. Four bits is
the first point above 0.90 and is therefore the default.</p>
@@ -92,7 +109,7 @@ let params = VectorSearchParams::new(10,
64);</code></pre></div>
<div class="storage-map" aria-label="IVF-RQ file layout"><div
class="storage-block primary"><strong>64 B header</strong>Shape, bits,
transform, layout</div><div class="storage-block"><strong>IVF
centers</strong><code>nlist × d × f32</code></div><div
class="storage-block"><strong>Offset table</strong><code>nlist × 16
B</code></div><div class="storage-block"><strong>Lists</strong>IDs + blocked
planes + blocked factors</div></div>
<p>The header records logical and padded dimensions, metric,
required layout flags, persisted <code>rq.bits</code>, total vectors, rotation
seed/rounds, plane bytes, rotation type 2, and compact factor layout 3. Every
non-empty list begins with <code>base_id</code>, encoded-ID length, and code
length, followed by sorted delta-varint IDs.</p>
<p>Within each 32-vector block, bytes are ordered by plane, byte
position, then lane. For more than one bit, the five structure-of-arrays fields
are coarse <code>(f_add, f_rescale, f_error)</code> followed by full
<code>(f_add, f_rescale)</code>. The omitted full error was never read: the
full estimate is the final ranking stage and does not produce another lower
bound. Readers reject the old pre-release layouts rather than guessing their
meaning.</p>
- <div class="callout"><strong>Open-source cross-check</strong><a
href="https://github.com/facebookresearch/faiss/blob/main/faiss/IndexIVFRaBitQFastScan.h">Faiss
IVFRaBitQ FastScan</a> also groups database vectors in 32-lane blocks and
separates RaBitQ correction factors from packed codes. <a
href="https://github.com/lancedb/lance/blob/main/rust/lance-index/src/vector/bq/ex_dot.rs">Lance's
RaBitQ kernels</a> likewise use blocked multi-bit codes and
architecture-specific dot produ [...]
+ <div class="callout"><strong>Open-source cross-check</strong><a
href="https://github.com/facebookresearch/faiss/blob/main/faiss/IndexIVFRaBitQFastScan.h">Faiss
IVFRaBitQ FastScan</a> also groups database vectors in 32-lane blocks and
separates RaBitQ correction factors from packed codes. <a
href="https://github.com/lancedb/lance/blob/main/rust/lance-index/src/vector/bq/ex_dot.rs">Lance's
RaBitQ kernels</a> likewise use blocked multi-bit codes and
architecture-specific dot produ [...]
<div class="callout"><strong>Why the remaining factors stay
F32</strong><a
href="https://github.com/facebookresearch/faiss/wiki/Additive-quantizers">Faiss
additive quantizers</a> can encode norms with qint8 or qint4. IVF-RQ cannot
apply that choice blindly to its coarse factors: their error term makes the
first-stage lower bound conservative, and inward rounding could incorrectly
prune a true Top-K candidate. v1 takes the lossless 4-byte saving by deleting
only the unused final [...]
<div class="callout"><strong>I/O contract</strong>Open reads the
64-byte header once. Resident initialization reads centroids plus the offset
table in one contiguous round. Search groups selected list payloads into at
most 64 MiB per round and also honors
<code>SeekReadCapabilities.max_ranges_per_pread</code>. Each returned payload
remains the backing allocation for its blocked codes, so the reader decodes
only IDs and factors instead of copying the usually much larger code reg [...]
</section>
diff --git a/tools/README.md b/tools/README.md
index 3937502..93796c6 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -21,6 +21,41 @@
This directory contains helper scripts used by release managers and committers.
+## IVF-RQ calibration
+
+`tune_ivfrq.py` runs the project's release `ann_bench` executable to choose a
+measured `rq.bits`/`nprobe` combination for an L2 recall target. It builds one
+index per bit width and reuses that file across probe widths. By default the
+first 200 published queries select the candidate; the remaining queries verify
+it against the default 4-bit/64-probe configuration in three alternating runs.
+The source corpus and query files are never modified.
+
+```bash
+cargo bench -p paimon-vindex-core --bench ann_bench --no-run
+python3 tools/tune_ivfrq.py \
+ --benchmark-executable /absolute/path/to/target/release/deps/ann_bench-HASH \
+ --base-fvecs /data/sift/sift_base.fvecs \
+ --query-fvecs /data/sift/sift_query.fvecs \
+ --ground-truth-ivecs /data/sift/sift_ground_truth.ivecs \
+ --target-recall 0.90 --bits 3,4,5 --nprobes 16,32,64 \
+ --output-dir /data/rq-calibration
+```
+
+Use the executable path printed by Cargo. `--max-bytes-per-vector` optionally
+constrains actual serialized bytes, including IDs and metadata. Raw CSVs,
+environments, logs, retained indexes, calibration measurements, and validation
+samples are saved in a fresh `run-*` subdirectory for each invocation,
preserving
+previous run artifacts. Before replacing the top-level `recommendation.json`,
+the tool checks it against all input paths, including symlink and hardlink
aliases. It includes
+explicit options only when held-out recall and storage meet the targets. When
+the default also meets them, a candidate needs at least 3% more batch QPS, or a
+smaller file at comparable throughput; otherwise the tool keeps the default.
+`--min-qps-gain` controls that comparison margin. Identical configurations are
+reported as A/A, never as a performance improvement. If neither configuration
+meets the targets, the tool returns exit status 2. This is offline
calibration, not a production
+recall guarantee or a change to the library's automatic-width policy. Run one
+benchmark process at a time without concurrent compilation.
+
## PR / base benchmark
The `PR benchmark` workflow compares the exact PR base SHA with GitHub's PR
merge
diff --git a/tools/tests/test_tune_ivfrq.py b/tools/tests/test_tune_ivfrq.py
new file mode 100644
index 0000000..eb2b57b
--- /dev/null
+++ b/tools/tests/test_tune_ivfrq.py
@@ -0,0 +1,205 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+
+import importlib.util
+import json
+import os
+from pathlib import Path
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location("tune_ivfrq",
Path(__file__).parents[1] / "tune_ivfrq.py")
+tune = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(tune)
+
+
+def candidate(bits, recall, qps, size=1000):
+ return dict(rq_bits=bits, recall_at_10=recall, steady_batch_qps=qps,
+ file_bytes=size, n=100, nprobe=32)
+
+
+class TuneIvfRqTests(unittest.TestCase):
+ def input_files(self, root):
+ inputs = {option: root / option
+ for option in ["base-fvecs", "query-fvecs",
"ground-truth-ivecs"]}
+ for value, path in enumerate(inputs.values()):
+ path.write_bytes(struct.pack("<if", 1, float(value)) * 4)
+ return inputs
+
+ def calibration_command(self, root, output, inputs):
+ benchmark = root / "fake_benchmark"
+ benchmark.write_text(f"#!{sys.executable}\n" + '''
+import csv, os, pathlib, sys
+if "ANN_REUSE_INDEX_PATH" not in os.environ:
+ path = pathlib.Path(os.environ["ANN_OUTPUT_DIR"]) / str(os.getpid())
+ path.mkdir()
+ (path / "ivf_rq.index").write_bytes(b"fixture")
+row = dict(n=4, rq_bits=int(os.environ["ANN_RQ_BITS"]),
nprobe=int(os.environ["ANN_NPROBE"]),
+ file_bytes=64, recall_at_10=0.5, steady_batch_qps=100,
+ steady_sequential_qps=90, steady_sequential_p95_us=10)
+writer = csv.DictWriter(sys.stdout, fieldnames=row.keys())
+writer.writeheader()
+writer.writerow(row)
+''')
+ benchmark.chmod(0o755)
+ command = [sys.executable, str(Path(tune.__file__)),
+ "--benchmark-executable", str(benchmark), "--output-dir",
str(output),
+ "--bits", "3", "--nprobes", "16,32", "--nlist", "64",
+ "--calibration-queries", "2", "--repetitions", "1"]
+ for option, path in inputs.items():
+ command.extend(["--" + option, str(path)])
+ return command
+
+ def test_fastest_configuration_must_meet_both_targets(self):
+ low_recall = candidate(3, 0.8999, 900)
+ oversized = candidate(6, 0.99, 800, size=2000)
+ valid = candidate(4, 0.9, 700)
+ self.assertEqual(tune.select_candidate([low_recall, oversized, valid],
0.9, 10), valid)
+ with self.assertRaisesRegex(ValueError, "no measured configuration"):
+ tune.select_candidate([low_recall, oversized], 0.9, 10)
+
+ def test_nonfinite_or_zero_throughput_cannot_win(self):
+ valid = candidate(4, 0.91, 100)
+ invalid = [candidate(3, 0.99, float("nan")), candidate(3, 0.99, 0),
+ candidate(3, float("nan"), 1000)]
+ self.assertEqual(tune.select_candidate(invalid + [valid], 0.9), valid)
+
+ def
test_recall_just_below_target_cannot_pass_calibration_or_validation(self):
+ below = candidate(3, 88199 / 98000, 200)
+ adequate = candidate(4, 0.9, 100)
+ self.assertEqual(tune.select_candidate([below, adequate], 0.9),
adequate)
+ selected, verification = tune.select_verified_configuration(adequate,
below, 0.9)
+ self.assertIs(selected, adequate)
+ self.assertFalse(verification["candidate_recall_validated"])
+
+ def test_query_splits_are_disjoint_and_do_not_modify_source(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source = root / "queries.fvecs"
+ records = [struct.pack("<if", 1, float(row)) for row in range(7)]
+ source.write_bytes(b"".join(records))
+ calibration, validation = root / "calibration.fvecs", root /
"validation.fvecs"
+ tune.copy_records(source, calibration, 0, 2)
+ tune.copy_records(source, validation, 2, 5)
+ self.assertEqual(calibration.read_bytes(), b"".join(records[:2]))
+ self.assertEqual(validation.read_bytes(), b"".join(records[2:]))
+ with self.assertRaises(ValueError):
+ tune.copy_records(source, source, 0, 2)
+ self.assertEqual(source.read_bytes(), b"".join(records))
+
+ def test_query_split_rejects_a_hardlink_to_its_source(self):
+ with tempfile.TemporaryDirectory() as directory:
+ source, alias = Path(directory) / "source", Path(directory) /
"alias"
+ data = struct.pack("<if", 1, 1.0) * 4
+ source.write_bytes(data)
+ os.link(source, alias)
+ with self.assertRaises(ValueError):
+ tune.copy_records(source, alias, 0, 2)
+ self.assertEqual(source.read_bytes(), data)
+
+ def test_cli_preserves_inputs_named_like_previous_run_outputs(self):
+ destinations = ["calibration.fvecs", "calibration.ivecs",
"validation.fvecs",
+ "validation.ivecs", "calibration.csv",
"calibration-b3-p16-r0/stderr.log"]
+ for option in ["base-fvecs", "query-fvecs", "ground-truth-ivecs"]:
+ for destination in destinations:
+ with self.subTest(option=option, destination=destination),
tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ output = root / "results"
+ inputs = self.input_files(root)
+ colliding = output / destination
+ colliding.parent.mkdir(parents=True, exist_ok=True)
+ colliding.write_bytes(inputs[option].read_bytes())
+ inputs[option] = colliding
+ before = {path: path.read_bytes() for path in
inputs.values()}
+ result = subprocess.run(self.calibration_command(root,
output, inputs)
+ + ["--target-recall", "0.4"], capture_output=True,
text=True)
+ self.assertEqual({path: path.read_bytes() for path in
before}, before, result.stderr)
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_cli_rejects_report_aliases_before_modifying_any_input(self):
+ for alias in ["direct", "symlink", "hardlink"]:
+ for option in ["base-fvecs", "query-fvecs", "ground-truth-ivecs"]:
+ with self.subTest(alias=alias, option=option),
tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ output = root / "results"
+ output.mkdir()
+ inputs = self.input_files(root)
+ report = output / "recommendation.json"
+ if alias == "direct":
+ report.write_bytes(inputs[option].read_bytes())
+ inputs[option] = report
+ elif alias == "symlink":
+ report.symlink_to(inputs[option])
+ else:
+ os.link(inputs[option], report)
+ before = {path: path.read_bytes() for path in
inputs.values()}
+ result = subprocess.run(self.calibration_command(root,
output, inputs)
+ + ["--target-recall", "0.4"], capture_output=True,
text=True)
+ self.assertEqual({path: path.read_bytes() for path in
before}, before, result.stderr)
+ self.assertEqual(report.read_bytes(),
before[inputs[option]])
+ self.assertEqual(result.returncode, 2, result.stderr)
+ self.assertIn("must not overwrite an input", result.stderr)
+ self.assertEqual(list(output.iterdir()), [report])
+
+ def
test_validation_keeps_default_when_calibration_gain_does_not_repeat(self):
+ default = candidate(4, 0.91, 100)
+ slower = candidate(5, 0.92, 99, size=1200)
+ selected, verification = tune.select_verified_configuration(default,
slower, 0.9)
+ self.assertIs(selected, default)
+ self.assertTrue(verification["candidate_recall_validated"])
+ self.assertFalse(verification["performance_validated"])
+ faster = candidate(5, 0.92, 110, size=1200)
+ self.assertIs(tune.select_verified_configuration(default, faster,
0.9)[0], faster)
+
+ def test_validation_requires_a_configuration_that_meets_the_targets(self):
+ default = candidate(4, 0.88, 100)
+ adequate = candidate(5, 0.93, 80)
+ self.assertIs(tune.select_verified_configuration(default, adequate,
0.9)[0], adequate)
+ self.assertIsNone(tune.select_verified_configuration(default,
candidate(3, 0.8, 200), 0.9)[0])
+
+ def test_same_configuration_is_aa_noise_and_cannot_claim_a_gain(self):
+ default = candidate(4, 0.91, 100)
+ same = candidate(4, 0.91, 120)
+ selected, verification = tune.select_verified_configuration(default,
same, 0.9)
+ self.assertIs(selected, default)
+ self.assertTrue(verification["same_configuration"])
+ self.assertFalse(verification["performance_validated"])
+
+ def
test_failed_rerun_replaces_the_previous_successful_recommendation(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ vectors = root / "vectors.fvecs"
+ vectors.write_bytes(struct.pack("<if", 1, 1.0) * 4)
+ output = root / "results"
+ command = self.calibration_command(root, output,
+ dict.fromkeys(["base-fvecs", "query-fvecs",
"ground-truth-ivecs"], vectors))
+ successful = subprocess.run(command + ["--target-recall", "0.4"],
capture_output=True, text=True)
+ self.assertEqual(successful.returncode, 0, successful.stderr)
+ self.assertTrue(json.loads((output /
"recommendation.json").read_text())["validated"])
+ failed = subprocess.run(command + ["--target-recall", "0.9"],
capture_output=True, text=True)
+ self.assertEqual(failed.returncode, 2, failed.stderr)
+ report = json.loads((output / "recommendation.json").read_text())
+ self.assertFalse(report["validated"])
+ self.assertIsNone(report["options"])
+ self.assertEqual(report["status"], "no_calibration_candidate")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/tune_ivfrq.py b/tools/tune_ivfrq.py
new file mode 100644
index 0000000..a197733
--- /dev/null
+++ b/tools/tune_ivfrq.py
@@ -0,0 +1,253 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+
+"""Calibrate IVF-RQ with ann_bench, then verify on disjoint held-out queries.
+
+This is an offline L2 benchmark tool. It prints an explicit build/search
+configuration and never changes application configuration or production data.
+"""
+
+import argparse
+import csv
+import io
+import json
+import math
+import os
+from pathlib import Path
+import statistics
+import struct
+import subprocess
+import tempfile
+
+
+def select_candidate(rows, target_recall, max_bytes_per_vector=None):
+ eligible = [row for row in rows
+ if math.isfinite(row["recall_at_10"])
+ and row["recall_at_10"] >= target_recall
+ and math.isfinite(row["steady_batch_qps"])
+ and row["steady_batch_qps"] > 0
+ and (max_bytes_per_vector is None
+ or row["file_bytes"] / row["n"] <= max_bytes_per_vector)]
+ if not eligible:
+ raise ValueError("no measured configuration meets the recall and
storage targets")
+ return min(eligible, key=lambda row: (-row["steady_batch_qps"],
row["file_bytes"],
+ row["nprobe"], row["rq_bits"]))
+
+
+def select_verified_configuration(default, candidate, target, budget=None,
min_qps_gain=0.03):
+ def meets(row):
+ try:
+ select_candidate([row], target, budget)
+ return True
+ except ValueError:
+ return False
+ candidate_valid, default_valid = meets(candidate), meets(default)
+ same_configuration = all(default[key] == candidate[key] for key in
["rq_bits", "nprobe"])
+ base_qps, candidate_qps = default["steady_batch_qps"],
candidate["steady_batch_qps"]
+ gain = candidate_qps / base_qps - 1.0 if (base_qps > 0 and
math.isfinite(base_qps)
+ and math.isfinite(candidate_qps)) else None
+ performance_valid = (candidate_valid and not same_configuration and gain
is not None
+ and gain >= min_qps_gain)
+ smaller_at_same_speed = (candidate_valid and
+ candidate["file_bytes"] < default["file_bytes"] * (1.0 - min_qps_gain)
and
+ gain is not None and gain >= -min_qps_gain)
+ if same_configuration:
+ selected = default if default_valid else None
+ elif candidate_valid and (not default_valid or performance_valid or
smaller_at_same_speed):
+ selected = candidate
+ elif default_valid:
+ selected = default
+ else:
+ selected = None
+ return selected, dict(candidate_recall_validated=candidate_valid,
+ default_meets_targets=default_valid,
performance_validated=performance_valid,
+ validation_qps_gain=gain, min_qps_gain=min_qps_gain,
+ kept_default=selected is default,
same_configuration=same_configuration)
+
+
+def record_shape(path):
+ with path.open("rb") as source:
+ header = source.read(4)
+ if len(header) != 4:
+ raise ValueError(f"empty or truncated vector file: {path}")
+ width, = struct.unpack("<i", header)
+ stride = 4 * (width + 1)
+ if width <= 0 or path.stat().st_size % stride:
+ raise ValueError(f"invalid fixed-width vector file: {path}")
+ return path.stat().st_size // stride, stride
+
+
+def same_file(left, right):
+ return (left.resolve() == right.resolve()
+ or (left.exists() and right.exists() and left.samefile(right)))
+
+
+def copy_records(source, destination, start, count):
+ if same_file(source, destination):
+ raise ValueError("query split must not overwrite its source")
+ rows, stride = record_shape(source)
+ if start < 0 or count <= 0 or start + count > rows:
+ raise ValueError(f"invalid query split for {source}")
+ with source.open("rb") as src, destination.open("wb") as dst:
+ src.seek(start * stride)
+ remaining = count * stride
+ while remaining:
+ chunk = src.read(min(remaining, 1024 * 1024))
+ if not chunk:
+ raise ValueError(f"truncated vector file: {source}")
+ dst.write(chunk)
+ remaining -= len(chunk)
+
+
+def write_csv(path, rows):
+ with path.open("w", newline="") as output:
+ writer = csv.DictWriter(output, fieldnames=rows[0].keys())
+ writer.writeheader()
+ writer.writerows(rows)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--benchmark-executable", type=Path, required=True)
+ parser.add_argument("--base-fvecs", type=Path, required=True)
+ parser.add_argument("--query-fvecs", type=Path, required=True)
+ parser.add_argument("--ground-truth-ivecs", type=Path, required=True)
+ parser.add_argument("--output-dir", type=Path, required=True)
+ parser.add_argument("--bits", default="3,4,5,6")
+ parser.add_argument("--nprobes", default="16,32,64,128")
+ parser.add_argument("--target-recall", type=float, default=0.9)
+ parser.add_argument("--min-qps-gain", type=float, default=0.03)
+ parser.add_argument("--max-bytes-per-vector", type=float)
+ parser.add_argument("--calibration-queries", type=int, default=200)
+ parser.add_argument("--repetitions", type=int, default=3)
+ parser.add_argument("--nlist", type=int, default=1024)
+ parser.add_argument("--train-n", type=int, default=65536)
+ parser.add_argument("--threads", type=int, default=12)
+ args = parser.parse_args()
+ bits = sorted(set(int(value) for value in args.bits.split(",")))
+ probes = sorted(set(int(value) for value in args.nprobes.split(",")))
+ if (not math.isfinite(args.target_recall) or not 0 <= args.target_recall
<= 1
+ or any(not 1 <= value <= 8 for value in bits)
+ or any(not 1 <= value <= args.nlist for value in probes)
+ or args.repetitions <= 0 or args.threads <= 0 or args.train_n <= 0
+ or not math.isfinite(args.min_qps_gain) or not 0 <=
args.min_qps_gain < 1
+ or (args.max_bytes_per_vector is not None and
+ (not math.isfinite(args.max_bytes_per_vector) or
args.max_bytes_per_vector <= 0))):
+ parser.error("invalid recall, width, memory, or repetition setting")
+ query_count, _ = record_shape(args.query_fvecs)
+ truth_count, _ = record_shape(args.ground_truth_ivecs)
+ if query_count != truth_count or not 0 < args.calibration_queries <
query_count:
+ parser.error("query/truth counts must match and leave a nonempty
validation split")
+ output = args.output_dir.resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ report_path = output / "recommendation.json"
+ if any(same_file(report_path, source) for source in
+ [args.base_fvecs, args.query_fvecs, args.ground_truth_ivecs]):
+ parser.error("output report must not overwrite an input dataset")
+ # Exclusive creation keeps every split, CSV, log and retained index away
+ # from inputs and symlinks left in the output directory by earlier runs.
+ run_output = Path(tempfile.mkdtemp(prefix="run-", dir=output))
+ # A failed rerun must not leave a successful recommendation from an older
+ # target or dataset looking like the result of this invocation.
+ report_path.write_text(json.dumps(dict(target_recall=args.target_recall,
+ validated=False, status="running", options=None), indent=2) + "\n")
+ files = {}
+ for phase, start, count in [("calibration", 0, args.calibration_queries),
+ ("validation", args.calibration_queries,
+ query_count - args.calibration_queries)]:
+ query = run_output / f"{phase}.fvecs"
+ truth = run_output / f"{phase}.ivecs"
+ copy_records(args.query_fvecs, query, start, count)
+ copy_records(args.ground_truth_ivecs, truth, start, count)
+ files[phase] = query, truth
+ indexes = {}
+
+ def measure(bits, nprobe, phase, repetition=0):
+ label = f"{phase}-b{bits}-p{nprobe}-r{repetition}"
+ directory = run_output / label
+ directory.mkdir(exist_ok=True)
+ env = {key: value for key, value in os.environ.items() if not
key.startswith("ANN_")}
+ env.update(ANN_INDEXES="IVF_RQ", ANN_DATASET_NAME=label,
+ ANN_BASE_FVECS=str(args.base_fvecs.resolve()),
+ ANN_QUERY_FVECS=str(files[phase][0]),
ANN_GROUND_TRUTH_IVECS=str(files[phase][1]),
+ ANN_RQ_BITS=str(bits), ANN_NLIST=str(args.nlist),
ANN_NPROBE=str(nprobe),
+ ANN_TRAIN_N=str(args.train_n), ANN_K="10",
ANN_KEEP_INDEXES="1",
+ ANN_STORAGE_CASES="local_ssd_warm_cache",
ANN_STEADY_MIN_MS="1000",
+ ANN_OUTPUT_DIR=str(directory),
RAYON_NUM_THREADS=str(args.threads))
+ if bits in indexes:
+ env["ANN_REUSE_INDEX_PATH"] = str(indexes[bits])
+ existing_indexes = set(directory.rglob("*.index"))
+ with (directory / "stderr.log").open("w") as stderr:
+ result =
subprocess.run([str(args.benchmark_executable.resolve())], env=env,
+ text=True, stdout=subprocess.PIPE,
stderr=stderr, check=True)
+ (directory / "result.csv").write_text(result.stdout)
+ (directory / "environment.json").write_text(json.dumps(
+ {key: value for key, value in env.items()
+ if key.startswith("ANN_") or key == "RAYON_NUM_THREADS"},
indent=2) + "\n")
+ parsed = list(csv.DictReader(io.StringIO(result.stdout)))
+ if len(parsed) != 1:
+ raise ValueError("expected exactly one ann_bench CSV result")
+ row = {key: float(parsed[0][key]) for key in ["n", "rq_bits",
"nprobe", "file_bytes",
+ "recall_at_10", "steady_batch_qps", "steady_sequential_qps",
"steady_sequential_p95_us"]}
+ if bits not in indexes:
+ paths = [path for path in directory.rglob("*.index") if path not
in existing_indexes]
+ if len(paths) != 1:
+ raise ValueError(f"expected one retained index in {directory}")
+ indexes[bits] = paths[0]
+ print(json.dumps(dict(phase=phase, repetition=repetition, **row)),
flush=True)
+ return row
+
+ rows = [measure(bits, nprobe, "calibration") for bits in bits for nprobe
in probes]
+ write_csv(run_output / "calibration.csv", rows)
+ try:
+ chosen = select_candidate(rows, args.target_recall,
args.max_bytes_per_vector)
+ except ValueError as error:
+
report_path.write_text(json.dumps(dict(target_recall=args.target_recall,
+ validated=False, status="no_calibration_candidate", options=None,
+ reason=str(error)), indent=2) + "\n")
+ raise SystemExit(2) from error
+ chosen_bits, chosen_probe = int(chosen["rq_bits"]), int(chosen["nprobe"])
+ # Alternate order to reduce thermal/order bias. Validation queries were not
+ # used to select the candidate or construct its index.
+ validation = {"default": [], "candidate": []}
+ for repetition in range(args.repetitions):
+ order = ["default", "candidate"] if repetition % 2 == 0 else
["candidate", "default"]
+ for name in order:
+ b, p = (4, min(64, args.nlist)) if name == "default" else
(chosen_bits, chosen_probe)
+ row = measure(b, p, "validation", repetition * 2 + (name ==
"candidate"))
+ validation[name].append(row)
+ medians = {name: {key: statistics.median(row[key] for row in samples)
+ for key in samples[0]} for name, samples in
validation.items()}
+ selected, verification = select_verified_configuration(medians["default"],
medians["candidate"],
+ args.target_recall, args.max_bytes_per_vector, args.min_qps_gain)
+ accepted = selected is not None
+ report = dict(target_recall=args.target_recall, validated=accepted,
+ status="validated" if accepted else "validation_failed",
**verification,
+ calibration_queries=args.calibration_queries,
+ validation_queries=query_count - args.calibration_queries,
+ options={"index.type": "ivf_rq", "rq.bits":
int(selected["rq_bits"]),
+ "nlist": args.nlist, "nprobe":
int(selected["nprobe"])} if accepted else None,
+ medians=medians, samples=validation)
+ report_path.write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+ if not accepted:
+ raise SystemExit(2)
+
+
+if __name__ == "__main__":
+ main()