diff --git a/core/benches/ann_bench.rs b/core/benches/ann_bench.rs index dd232c54..18d80b42 100644 --- a/core/benches/ann_bench.rs +++ b/core/benches/ann_bench.rs @@ -19,13 +19,14 @@ mod ann_bench_support; use ann_bench_support::{ - add_fixed_round_latency, default_training_vector_count, inspect_i32_records, - inspect_public_dataset, parse_storage_case_names, resolve_shape_value, should_isolate_indexes, + add_fixed_round_latency, benchmark_metric, default_training_vector_count, inspect_i32_records, + inspect_public_dataset, parse_index_names, parse_storage_case_names, resolve_shape_value, + should_isolate_indexes, validate_reused_index, }; use paimon_vindex_core::diskann::{ DiskAnnBuildDistance, DiskAnnBuildParams, DiskAnnRawVectorEncoding, }; -use paimon_vindex_core::distance::{fvec_l2sqr, MetricType}; +use paimon_vindex_core::distance::{fvec_distance, MetricType}; use paimon_vindex_core::index::{ infer_pq_m, VectorIndexConfig, VectorIndexReader, VectorIndexReaderOptions, VectorIndexTrainer, VectorIndexWriter, VectorSearchParams, DEFAULT_PQ_CODE_RATIO, @@ -113,27 +114,21 @@ fn run_benchmark() -> Result<(), Box> { config.raw_dataset_bytes()? as f64 / GIB as f64, dataset_started.elapsed().as_millis() ); - 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(), - ground_truth.first().map_or(0, Vec::len) - ); - ground_truth - } else { - let truth_started = Instant::now(); - let ground_truth = exact_ground_truth(&dataset, config.k, config.filter.as_ref()); - eprintln!( - "exact ground truth: {} queries in {} ms", - config.nq, - truth_started.elapsed().as_millis() - ); - ground_truth + let l2_truth = std::sync::OnceLock::new(); + let cosine_truth = std::sync::OnceLock::new(); + let ground_truth = |index: &str| { + let metric = benchmark_metric(index); + if metric == MetricType::L2 && config.filter.is_none() { + if let Some(truth) = &dataset.ground_truth { + return truth; + } + } + let cache = if metric == MetricType::Cosine { + &cosine_truth + } else { + &l2_truth + }; + cache.get_or_init(|| exact_ground_truth(&dataset, config.k, config.filter.as_ref(), metric)) }; if env::var_os(SUPPRESS_CSV_HEADER_ENV).is_none() { @@ -145,6 +140,7 @@ fn run_benchmark() -> Result<(), Box> { return Err("ANN_REUSE_INDEX_PATH requires exactly one ANN_INDEXES value".into()); } let spec = specs.pop().expect("validated one ANN index specification"); + validate_reused_index(path, spec.name, spec.config.index_type(), config.d)?; let built = BuiltIndex { name: spec.name, path: path.clone(), @@ -156,7 +152,7 @@ fn run_benchmark() -> Result<(), Box> { file_bytes: fs::metadata(path)?.len(), peak_rss_bytes: peak_resident_set_bytes()?, }; - run_built_index(&config, &dataset, &ground_truth, &built)?; + run_built_index(&config, &dataset, ground_truth(built.name), &built)?; return Ok(()); } @@ -174,7 +170,7 @@ fn run_benchmark() -> Result<(), Box> { built.file_bytes, built.peak_rss_bytes ); - run_built_index(&config, &dataset, &ground_truth, &built)?; + run_built_index(&config, &dataset, ground_truth(built.name), &built)?; if !config.keep_indexes { fs::remove_file(&built.path)?; } @@ -197,7 +193,6 @@ fn run_built_index( } const GIB: u64 = 1024 * 1024 * 1024; -const ALL_INDEX_NAMES: [&str; 5] = ["IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "DISKANN"]; #[derive(Clone)] struct Config { @@ -663,18 +658,20 @@ struct IndexSpec { fn index_specs(config: &Config) -> Vec { let ivf_search = VectorSearchParams::new(config.k, config.nprobe); - vec![ - IndexSpec { - name: "IVF_FLAT", - config: VectorIndexConfig::IvfFlat { - dimension: config.d, - nlist: config.nlist, - metric: MetricType::L2, - use_approximate_coarse_assignment: true, - ivf_train_max_points_per_centroid: 256, - }, - searches: vec![ivf_search], + let flat_spec = |name, metric| IndexSpec { + name, + config: VectorIndexConfig::IvfFlat { + dimension: config.d, + nlist: config.nlist, + metric, + use_approximate_coarse_assignment: true, + ivf_train_max_points_per_centroid: 256, }, + searches: vec![ivf_search], + }; + vec![ + flat_spec("IVF_FLAT", MetricType::L2), + flat_spec("IVF_FLAT_COSINE", MetricType::Cosine), IndexSpec { name: "IVF_SQ", config: VectorIndexConfig::IvfSq { @@ -1200,6 +1197,7 @@ fn exact_ground_truth( dataset: &Dataset, k: usize, filter: Option<&RoaringTreemap>, + metric: MetricType, ) -> Vec> { dataset .queries @@ -1210,7 +1208,7 @@ fn exact_ground_truth( .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)) + .map(|(row, vector)| (fvec_distance(query, vector, metric), row as i64)) .collect::>(); let retained = k.min(distances.len()); if retained != 0 { @@ -1485,31 +1483,7 @@ fn read_usize_list_env( } fn selected_indexes() -> Result, Box> { - let value = env::var("ANN_INDEXES").unwrap_or_else(|_| "all".to_string()); - if value.trim().eq_ignore_ascii_case("all") { - return Ok(ALL_INDEX_NAMES - .iter() - .map(|name| (*name).to_string()) - .collect()); - } - let mut selected = Vec::new(); - for value in value.split(',') { - let normalized = value.trim().to_ascii_uppercase().replace('-', "_"); - if !ALL_INDEX_NAMES.contains(&normalized.as_str()) { - return Err(format!( - "unknown ANN_INDEXES value '{value}'; expected all or a comma-separated subset of {}", - ALL_INDEX_NAMES.join(",") - ) - .into()); - } - if !selected.contains(&normalized) { - selected.push(normalized); - } - } - if selected.is_empty() { - return Err("ANN_INDEXES must select at least one index".into()); - } - Ok(selected) + parse_index_names(env::var("ANN_INDEXES").ok().as_deref()) } fn selected_storage_cases() -> Result, Box> { diff --git a/core/benches/support/ann_bench_support.rs b/core/benches/support/ann_bench_support.rs index 649f3c45..1ae2b317 100644 --- a/core/benches/support/ann_bench_support.rs +++ b/core/benches/support/ann_bench_support.rs @@ -17,6 +17,8 @@ //! Shared support for the public ANN benchmark and its focused tests. +use paimon_vindex_core::distance::MetricType; +use paimon_vindex_core::index::{IndexType, VectorIndexReader}; use std::fs::File; use std::io::{self, BufReader, Read}; use std::path::Path; @@ -178,3 +180,68 @@ pub(crate) fn inspect_i32_records(path: &Path) -> io::Result<(usize, usize)> { .map_err(|_| io::Error::other("record count exceeds usize"))?; Ok((rows, width as usize)) } + +const ALL_INDEX_NAMES: [&str; 6] = [ + "IVF_FLAT", + "IVF_FLAT_COSINE", + "IVF_SQ", + "IVF_PQ", + "IVF_RQ", + "DISKANN", +]; + +pub(crate) fn benchmark_metric(index: &str) -> MetricType { + if index == "IVF_FLAT_COSINE" { + MetricType::Cosine + } else { + MetricType::L2 + } +} + +pub(crate) fn parse_index_names( + value: Option<&str>, +) -> Result, Box> { + let value = value.unwrap_or("all"); + if value.trim().eq_ignore_ascii_case("all") { + return Ok(ALL_INDEX_NAMES + .iter() + .filter(|&&name| name != "IVF_FLAT_COSINE") + .map(|name| (*name).to_string()) + .collect()); + } + let mut selected = Vec::new(); + for value in value.split(',') { + let normalized = value.trim().to_ascii_uppercase().replace('-', "_"); + if !ALL_INDEX_NAMES.contains(&normalized.as_str()) { + return Err(format!( + "unknown ANN_INDEXES value '{value}'; expected all or a comma-separated subset of {}", + ALL_INDEX_NAMES.join(",") + ) + .into()); + } + if !selected.contains(&normalized) { + selected.push(normalized); + } + } + if selected.is_empty() { + return Err("ANN_INDEXES must select at least one index".into()); + } + Ok(selected) +} + +pub(crate) fn validate_reused_index( + path: &Path, + name: &str, + kind: IndexType, + dimension: usize, +) -> io::Result<()> { + let metadata = VectorIndexReader::open(File::open(path)?)?.metadata(); + let metric = benchmark_metric(name); + if metadata.index_type != kind || metadata.dimension != dimension || metadata.metric != metric { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!( + "ANN_REUSE_INDEX_PATH {} contains {:?} d={} metric={:?}; {name} requires {kind:?} d={dimension} metric={metric:?}", + path.display(), metadata.index_type, metadata.dimension, metadata.metric, + ))); + } + Ok(()) +} diff --git a/core/src/distance.rs b/core/src/distance.rs index cbce25f2..bff911d7 100644 --- a/core/src/distance.rs +++ b/core/src/distance.rs @@ -809,6 +809,52 @@ unsafe fn fvec_inner_product_avx2(a: &[f32], b: &[f32]) -> f32 { result } +/// Four candidates share query loads while each preserves the scalar-call SIMD +/// accumulation and reduction order. No FMA or reassociation is introduced. +#[inline] +fn fvec_inner_product_four(a: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] { + for candidate in candidates { + assert_eq!(a.len(), candidate.len()); + } + #[cfg(target_arch = "x86_64")] + if is_x86_feature_detected!("avx2") && a.len() >= 8 { + return unsafe { fvec_inner_product_four_avx2(a, candidates) }; + } + candidates.map(|candidate| fvec_inner_product(a, candidate)) +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn fvec_inner_product_four_avx2(a: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] { + use std::arch::x86_64::*; + let mut sums = [_mm256_setzero_ps(); 4]; + let mut i = 0; + while i + 8 <= a.len() { + let query = unsafe { _mm256_loadu_ps(a.as_ptr().add(i)) }; + for candidate in 0..4 { + let vector = unsafe { _mm256_loadu_ps(candidates[candidate].as_ptr().add(i)) }; + sums[candidate] = _mm256_add_ps(sums[candidate], _mm256_mul_ps(query, vector)); + } + i += 8; + } + let mut results = sums.map(|sum| { + let hi = _mm256_extractf128_ps::<1>(sum); + let lo = _mm256_castps256_ps128(sum); + let sum128 = _mm_add_ps(lo, hi); + let sum64 = _mm_add_ps(sum128, _mm_movehl_ps(sum128, sum128)); + let sum32 = _mm_add_ss(sum64, _mm_shuffle_ps::<1>(sum64, sum64)); + _mm_cvtss_f32(sum32) + }); + while i < a.len() { + let query = unsafe { *a.get_unchecked(i) }; + for candidate in 0..4 { + results[candidate] += query * unsafe { *candidates[candidate].get_unchecked(i) }; + } + i += 1; + } + results +} + #[cfg(target_arch = "aarch64")] #[target_feature(enable = "neon")] unsafe fn fvec_inner_product_neon(a: &[f32], b: &[f32]) -> f32 { @@ -980,6 +1026,24 @@ impl<'a> QueryDistance<'a> { } } + #[inline] + pub(crate) fn cosine_distances_to_four( + &self, + vectors: [&[f32]; 4], + norms: [f32; 4], + ) -> [f32; 4] { + debug_assert_eq!(self.metric, MetricType::Cosine); + let dots = fvec_inner_product_four(self.query, vectors); + std::array::from_fn(|i| { + let denom = self.query_norm * norms[i]; + if denom > 0.0 { + 1.0 - dots[i] / denom + } else { + 1.0 + } + }) + } + #[inline] pub(crate) fn distance_to(&self, vector: &[f32], vector_norm: Option) -> f32 { match self.metric { @@ -1749,3 +1813,118 @@ mod tests { assert_eq!(fvec_l2sqr_unless_exceeds(&a, &a, 0.0), Some(0.0)); } } + +#[cfg(test)] +mod batch4_tests { + use super::*; + + fn values(n: usize, mut seed: u32) -> Vec { + (0..n) + .map(|_| { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + ((seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 19.7 + }) + .collect() + } + + #[test] + fn batch4_matches_individual_score_bits_at_simd_boundaries() { + let dimensions = (0..40).chain([63, 64, 65, 127, 128, 129, 767, 768, 769, 1024]); + for d in dimensions { + for seed in 0..13 { + let query = values(d + 1, seed); + let mut data: [Vec; 4] = + std::array::from_fn(|i| values(d + i + 1, seed + i as u32 + 101)); + if seed == 0 { + data[1].fill(0.0); + } + let vectors: [&[f32]; 4] = std::array::from_fn(|i| &data[i][i + 1..]); + let q = &query[1..]; + let dots = fvec_inner_product_four(q, vectors); + for i in 0..4 { + assert_eq!( + dots[i].to_bits(), + fvec_inner_product(q, vectors[i]).to_bits(), + "dot d={d} seed={seed} i={i}" + ); + } + let context = QueryDistance::new(q, MetricType::Cosine); + let norms = vectors.map(|v| fvec_norm_l2sqr(v).sqrt()); + let distances = context.cosine_distances_to_four(vectors, norms); + for i in 0..4 { + assert_eq!( + distances[i].to_bits(), + context.distance_to(vectors[i], Some(norms[i])).to_bits(), + "cosine d={d} seed={seed} i={i}" + ); + } + } + } + } + + #[test] + fn batch4_zero_query_preserves_zero_denominator_behavior() { + let data = values(4 * 768, 45); + let vectors = std::array::from_fn(|i| &data[i * 768..(i + 1) * 768]); + let query = vec![0.0; 768]; + let context = QueryDistance::new(&query, MetricType::Cosine); + assert_eq!( + context.cosine_distances_to_four(vectors, vectors.map(|v| fvec_norm_l2sqr(v).sqrt())), + [1.0; 4] + ); + } + + #[test] + #[should_panic] + fn batch4_rejects_short_candidate() { + fvec_inner_product_four(&[1.0; 8], [&[1.0; 8], &[1.0; 8], &[1.0; 7], &[1.0; 8]]); + } + + #[test] + #[ignore = "isolated kernel experiment; run separately from end-to-end benchmarks"] + fn batch4_microbenchmark() { + use std::hint::black_box; + use std::time::Instant; + let d = 768; + let rows = 32768; + let data = values(rows * d, 19); + let query = values(d, 43); + let mut sums = [0.0f64; 2]; + for round in 0..4 { + for batched in if round % 2 == 0 { + [false, true] + } else { + [true, false] + } { + let start = Instant::now(); + let mut checksum = 0.0f64; + for _ in 0..12 { + let q = black_box(query.as_slice()); + if batched { + for row in (0..rows).step_by(4) { + let vectors = + std::array::from_fn(|i| &data[(row + i) * d..(row + i + 1) * d]); + for value in fvec_inner_product_four(q, vectors) { + checksum += value as f64; + } + } + } else { + for vector in data.chunks_exact(d) { + checksum += fvec_inner_product(q, vector) as f64; + } + } + } + black_box(checksum); + sums[batched as usize] = checksum; + println!( + "batch4_kernel round={} batched={} seconds={:.6} checksum={}", + round, + batched, + start.elapsed().as_secs_f64(), + checksum + ); + } + assert_eq!(sums[0].to_bits(), sums[1].to_bits()); + } + } +} diff --git a/core/src/ivfflat_io.rs b/core/src/ivfflat_io.rs index 46baec9e..7043df9e 100644 --- a/core/src/ivfflat_io.rs +++ b/core/src/ivfflat_io.rs @@ -17,7 +17,8 @@ use crate::collect::{Collector, RangeCollector}; use crate::distance::{ - fvec_l2sqr_four, fvec_l2sqr_unless_exceeds, fvec_normalize, MetricType, QueryDistance, + fvec_l2sqr_four, fvec_l2sqr_unless_exceeds, fvec_norm_l2sqr, fvec_normalize, MetricType, + QueryDistance, }; use crate::index::{validate_queries, VectorIndexReaderOptions}; use crate::index_io_util::{ @@ -38,7 +39,7 @@ use roaring::RoaringTreemap; use std::borrow::Cow; use std::collections::VecDeque; use std::io; -use std::mem::{align_of, size_of}; +use std::mem::{align_of, size_of, size_of_val}; use std::sync::{Arc, Mutex}; pub const IVFFLAT_MAGIC: u32 = 0x4956464C; // "IVFL" @@ -666,6 +667,7 @@ impl IVFFlatIndexReader { id_bytes_len: self.list_id_bytes_lens[list_id], d: self.d, list: Arc::clone(&list), + cosine_norms: None, }); results[position] = Some(list); } @@ -832,6 +834,20 @@ impl IVFFlatIndexReader { let count = self.batch_read_end(&probe_indices[batch_start..])?.max(1); let batch_end = (batch_start + count).min(probe_indices.len()); let (lists, _) = self.read_scan_lists(&probe_indices[batch_start..batch_end])?; + let cosine_cache = self + .list_cache + .as_mut() + .filter(|_| self.metric == MetricType::Cosine) + .map(|cache| { + cache.prepare_cosine_norms(&lists, self.d); + &*cache + }); + let norms = |list: &FlatListData| { + cosine_cache?.entries[list.list_id] + .as_ref()? + .cosine_norms + .as_deref() + }; let scan_components = lists .iter() .map(|list| list.ids.len()) @@ -842,7 +858,15 @@ impl IVFFlatIndexReader { .par_iter() .map(|list| { let mut local_heap = ReaderTopKHeap::new(k); - scan_flat_list(&q, list, self.d, self.metric, filter, &mut local_heap)?; + scan_flat_list( + &q, + list, + self.d, + self.metric, + filter, + &mut local_heap, + norms(list), + )?; Ok(local_heap.into_sorted()) }) .collect::>>()?; @@ -851,7 +875,15 @@ impl IVFFlatIndexReader { } } else { for list in &lists { - scan_flat_list(&q, list, self.d, self.metric, filter, &mut heap)?; + scan_flat_list( + &q, + list, + self.d, + self.metric, + filter, + &mut heap, + norms(list), + )?; } } batch_start = batch_end; @@ -1103,7 +1135,7 @@ impl IVFFlatIndexReader { let scan_one = |list: &FlatListData, qi: usize| -> io::Result<()> { let q = &queries[qi * d..(qi + 1) * d]; let mut collector = RangeCollector::with_output(band, qi, output.clone()); - scan_flat_list(q, list, d, metric, filter, &mut collector)?; + scan_flat_list(q, list, d, metric, filter, &mut collector, None)?; merge_collector(qi, collector)?; Ok(()) }; @@ -1439,16 +1471,16 @@ struct CachedFlatList { id_bytes_len: i32, d: usize, list: Arc, + cosine_norms: Option>, } -impl CachedFlatList { +impl FlatListData { fn retained_bytes(&self) -> usize { size_of::() + 2 * size_of::() - + self.list.ids.capacity() * size_of::() - + self.list.payload.storage.capacity() * size_of::() + + self.ids.capacity() * size_of::() + + self.payload.storage.capacity() * size_of::() + self - .list .payload .decoded_vectors .as_ref() @@ -1464,6 +1496,7 @@ struct FlatListCache { order: VecDeque, capacity_bytes: usize, retained_bytes: usize, + norm_bytes: usize, } impl FlatListCache { @@ -1487,21 +1520,62 @@ impl FlatListCache { order, capacity_bytes: budget - fixed, retained_bytes: 0, + norm_bytes: 0, }) } fn remove(&mut self, list_id: usize) { if let Some(entry) = self.entries[list_id].take() { - self.retained_bytes -= entry.retained_bytes(); + let norms = entry.cosine_norms.as_deref().map_or(0, size_of_val); + self.norm_bytes -= norms; + self.retained_bytes -= entry.list.retained_bytes() + norms; + } + } + + fn prepare_cosine_norms(&mut self, lists: &[Arc], d: usize) { + for list in lists { + let Some(entry) = &mut self.entries[list.list_id] else { + continue; + }; + let bytes = list.ids.len().saturating_mul(size_of::()); + if entry.cosine_norms.is_none() + && bytes != 0 + && bytes <= self.capacity_bytes - self.retained_bytes + { + entry.cosine_norms = Some( + list.vectors() + .chunks_exact(d) + .map(|vector| fvec_norm_l2sqr(vector).sqrt()) + .collect(), + ); + self.retained_bytes += bytes; + self.norm_bytes += bytes; + } } } fn insert(&mut self, entry: CachedFlatList) { - let bytes = entry.retained_bytes(); + let bytes = entry.list.retained_bytes(); let list_id = entry.list.list_id; if bytes > self.capacity_bytes || self.entries[list_id].is_some() { return; } + // Drop optional norms before evicting decoded posting lists. + if bytes > self.capacity_bytes - self.retained_bytes && self.norm_bytes > 0 { + for &id in &self.order { + if let Some(norms) = self.entries[id] + .as_mut() + .and_then(|e| e.cosine_norms.take()) + { + let freed = size_of_val(norms.as_ref()); + self.norm_bytes -= freed; + self.retained_bytes -= freed; + if bytes <= self.capacity_bytes - self.retained_bytes || self.norm_bytes == 0 { + break; + } + } + } + } while bytes > self.capacity_bytes - self.retained_bytes { let oldest = self.order.pop_front().expect("nonempty cache over budget"); self.remove(oldest); @@ -1587,8 +1661,9 @@ fn scan_flat_list( metric: MetricType, filter: Option<&dyn RowIdFilter>, collector: &mut C, + norms: Option<&[f32]>, ) -> io::Result<()> { - scan_flat_rows( + scan_flat_rows_with_norms( query, &list.ids, list.vectors(), @@ -1596,6 +1671,7 @@ fn scan_flat_list( metric, filter, collector, + norms, ) } @@ -1608,6 +1684,49 @@ fn scan_flat_rows( filter: Option<&dyn RowIdFilter>, collector: &mut C, ) -> io::Result<()> { + scan_flat_rows_with_norms(query, ids, vectors, d, metric, filter, collector, None) +} + +#[allow(clippy::too_many_arguments)] +fn scan_flat_rows_with_norms( + query: &[f32], + ids: &[i64], + vectors: &[f32], + d: usize, + metric: MetricType, + filter: Option<&dyn RowIdFilter>, + collector: &mut C, + vector_norms: Option<&[f32]>, +) -> io::Result<()> { + debug_assert!(vector_norms.is_none_or(|norms| norms.len() == ids.len())); + // In cosine mode this caches the query norm once per list instead of + // recomputing it for every candidate vector. + let distance_context = QueryDistance::new(query, metric); + // Cached cosine lists can share query loads across four candidates. Keep + // heap insertion in row order, including ties, and retain the filtered and + // streaming paths so sparse predicates do not compute rejected vectors. + if !C::VALIDATE_COSINE_INPUTS && metric == MetricType::Cosine && filter.is_none() { + if let Some(norms) = vector_norms { + let mut row = 0; + while row + 4 <= ids.len() { + let batch = std::array::from_fn(|i| &vectors[(row + i) * d..(row + i + 1) * d]); + let distances = distance_context + .cosine_distances_to_four(batch, std::array::from_fn(|i| norms[row + i])); + for (i, distance) in distances.into_iter().enumerate() { + collector.push(ids[row + i], distance)?; + } + row += 4; + } + for local_idx in row..ids.len() { + let vector = &vectors[local_idx * d..(local_idx + 1) * d]; + collector.push( + ids[local_idx], + distance_context.distance_to(vector, Some(norms[local_idx])), + )?; + } + return Ok(()); + } + } // A short vector cannot stop before the first 128-component L2 probe. // Score four rows together to share query loads and independent SIMD // accumulators; preserve the scalar kernel's bits and row admission order. @@ -1631,9 +1750,6 @@ fn scan_flat_rows( start += 4; } } - // In cosine mode this caches the query norm once per list instead of - // recomputing it for every candidate vector. - let distance_context = QueryDistance::new(query, metric); for (local_idx, &id) in ids.iter().enumerate().skip(start) { if filter.is_some_and(|value| !value.contains(id)) { continue; @@ -1659,7 +1775,10 @@ fn scan_flat_rows( } } } else { - distance_context.distance_to(vector, vector_norm) + distance_context.distance_to( + vector, + vector_norm.or_else(|| vector_norms.map(|norms| norms[local_idx])), + ) }; collector.push(id, distance)?; } @@ -2013,6 +2132,47 @@ mod tests { } } + #[test] + fn cached_cosine_preserves_parallel_cutoff_ties() { + let d = 16; + let mut index = balanced_flat_index(d, 2, 32768); + index.metric = MetricType::Cosine; + for list in &mut index.vectors { + for vector in list.chunks_exact_mut(d) { + vector.fill(0.0); + vector[1] = 1.0; + } + } + index.vectors[1][d] = 1.0; + index.vectors[1][d + 1] = 0.0; + let bytes = serialized_flat_index(&index); + let mut baseline = IVFFlatIndexReader::open(Cursor::new(bytes.clone())).unwrap(); + let mut cached = IVFFlatIndexReader::open_with_options( + Cursor::new(bytes), + VectorIndexReaderOptions::new(16 << 20), + ) + .unwrap(); + let mut query = [0.0; 16]; + query[0] = 1.0; + let expected = baseline.search(&query, 2, 2).unwrap(); + assert_eq!(expected.1, [0.0, 1.0]); + for _ in 0..2 { + assert_eq!(cached.search(&query, 2, 2).unwrap(), expected); + } + let (lists, reads) = cached.read_scan_lists(&[0, 1]).unwrap(); + assert_eq!(reads, 0); + assert!(lists.iter().all( + |list| cached.list_cache.as_ref().unwrap().entries[list.list_id] + .as_ref() + .unwrap() + .cosine_norms + .as_ref() + .unwrap() + .len() + == list.ids.len() + )); + } + #[test] fn ivfflat_chunked_writer_preserves_format_and_bounds() { const TEST_BUDGET: usize = 64; @@ -2544,7 +2704,7 @@ mod tests { assert_eq!(reads, 0); assert!(Arc::ptr_eq(&first[0], &again[1])); let cache = reader.list_cache.as_mut().unwrap(); - let bytes_per_list = cache.entries[0].as_ref().unwrap().retained_bytes(); + let bytes_per_list = cache.entries[0].as_ref().unwrap().list.retained_bytes(); cache.capacity_bytes = bytes_per_list * 2; reader.read_scan_lists(&[2]).unwrap(); let cache = reader.list_cache.as_ref().unwrap(); @@ -2587,6 +2747,51 @@ mod tests { ); } + #[test] + fn cosine_norms_yield_to_posting_lists_for_batch_and_range() { + use crate::range::{Bound, DistanceBand}; + + let mut index = balanced_flat_index(16, 4, 37); + index.metric = MetricType::Cosine; + let mut reader = IVFFlatIndexReader::open_with_options( + Cursor::new(serialized_flat_index(&index)), + VectorIndexReaderOptions::new(1 << 20), + ) + .unwrap(); + let list_ids = [0, 1, 2, 3]; + let payload_bytes = reader + .read_inverted_lists(&list_ids) + .unwrap() + .iter() + .map(FlatListData::retained_bytes) + .sum(); + reader.list_cache.as_mut().unwrap().capacity_bytes = payload_bytes; + let q = &index.vectors[0][..16]; + let params = VectorRangeSearchParams::new( + DistanceBand::from_raw(Bound::Unbounded, Bound::Unbounded, MetricType::Cosine).unwrap(), + 4, + ); + reader.search(q, 2, 1).unwrap(); + assert!(reader.list_cache.as_ref().unwrap().norm_bytes > 0); + search_batch_ivfflat_reader(&mut reader, q, 1, 2, 4).unwrap(); + assert_eq!(reader.list_cache.as_ref().unwrap().norm_bytes, 0); + assert_eq!( + reader + .range_search(q, params) + .unwrap() + .call_stats() + .list_reads(), + 0 + ); + + // Even with spare capacity, batch and range scans never request cached norms. + reader.list_cache = FlatListCache::new(4, 1 << 20); + reader.range_search(q, params).unwrap(); + search_batch_ivfflat_reader(&mut reader, q, 1, 2, 4).unwrap(); + assert_eq!(reader.list_cache.as_ref().unwrap().norm_bytes, 0); + assert_eq!(reader.read_scan_lists(&list_ids).unwrap().1, 0); + } + #[test] fn ivfflat_cache_retries_io_failures_and_invalidates_edited_metadata() { let index = balanced_flat_index(16, 4, 37); diff --git a/core/tests/ann_bench_support.rs b/core/tests/ann_bench_support.rs index 0085e09f..256db5d1 100644 --- a/core/tests/ann_bench_support.rs +++ b/core/tests/ann_bench_support.rs @@ -178,3 +178,46 @@ fn fixed_round_latency_adds_the_idealized_dependency_cost() { Duration::MAX ); } + +#[test] +fn cosine_benchmark_requires_explicit_selection() { + use ann_bench_support::parse_index_names; + for selection in [None, Some("all")] { + let names = parse_index_names(selection).unwrap(); + assert_eq!(names.len(), 5); + assert!(!names.iter().any(|name| name == "IVF_FLAT_COSINE")); + } + assert_eq!( + parse_index_names(Some("ivf-flat-cosine")).unwrap(), + ["IVF_FLAT_COSINE"] + ); +} + +#[test] +fn reused_flat_index_must_match_the_benchmark_metric() { + use ann_bench_support::validate_reused_index; + use paimon_vindex_core::{ + distance::MetricType, index::IndexType, io::PosWriter, ivfflat::IVFFlatIndex, + ivfflat_io::write_ivfflat_index, + }; + + let directory = TestDirectory::new(); + let path = directory.0.join("flat.idx"); + for (metric, valid, wrong) in [ + (MetricType::L2, "IVF_FLAT", "IVF_FLAT_COSINE"), + (MetricType::Cosine, "IVF_FLAT_COSINE", "IVF_FLAT"), + ] { + let mut index = IVFFlatIndex::new(2, 1, metric); + index.set_quantizer_centroids(vec![1.0, 0.0]); + index.ids[0] = vec![0]; + index.vectors[0] = vec![1.0, 0.0]; + write_ivfflat_index(&index, &mut PosWriter::new(File::create(&path).unwrap())).unwrap(); + validate_reused_index(&path, valid, IndexType::IvfFlat, 2).unwrap(); + assert_eq!( + validate_reused_index(&path, wrong, IndexType::IvfFlat, 2) + .unwrap_err() + .kind(), + std::io::ErrorKind::InvalidInput + ); + } +} diff --git a/docs/api.html b/docs/api.html index a06b6342..4471825b 100644 --- a/docs/api.html +++ b/docs/api.html @@ -115,8 +115,8 @@

Range search parameters and results

-

Reader options for DiskANN and IVF-SQ

-

Reader options are accepted by every binding. The memory budget controls DiskANN resident state and caches, and IVF-SQ's decoded-partition cache. The latency hint and read-plan inspection described below are DiskANN-specific.

+

Reader memory and I/O options

+

Reader options are accepted by every binding. The memory budget controls DiskANN resident state and caches, and the decoded-partition caches for IVF-SQ and IVF-FLAT. On IVF-FLAT cosine indexes, a probed list can retain one f32 norm per vector within the same cache budget. Single-query, batch and range searches share the cache. The latency hint and read-plan inspection described below are DiskANN-specific.

diff --git a/docs/development.html b/docs/development.html index 3db8e866..9f8542ec 100644 --- a/docs/development.html +++ b/docs/development.html @@ -101,7 +101,7 @@

Public SIFT1M, GIST1M, and GloVe-100 data

The benchmark infers ANN_N, ANN_NQ, and ANN_D from the public files, chooses ANN_TRAIN_N=min(N, max(65,536, 64 × nlist)), and automatically starts one child process per selected index so each peak-RSS value is independent. Explicit shape variables remain available as assertions. For GIST1M, download and convert gist-960-euclidean.hdf5; for GloVe-100, use the command above. Unit-normalized L2 has the same neighbor ordering as cosine for non-zero vectors; that equivalence was used by the recorded GloVe run. DiskANN now also accepts native cosine and inner-product metrics, which should be benchmarked against ground truth generated with the same production metric. Keep the other recorded settings unchanged. The default ANN_PQ_CODE_RATIO=0.0625 resolves automatically to m=32, m=240, and m=25 for SIFT, GIST, and GloVe respectively. Set ANN_PQ_M only to benchmark an explicit expert override.

At 1024 dimensions, ANN_DATA_GIB=10 derives exactly 2,621,440 vectors. Run large comparisons one index per process by changing ANN_INDEXES; this isolates process peak RSS and, unless ANN_KEEP_INDEXES=1, deletes that index after all selected serving cases. A comma-separated subset or all is convenient for smaller workloads. The benchmark retains only the selected training prefix, then adds the entire data set. The clustered generator is round-robin by cluster, so a prefix still covers every cluster when ANN_TRAIN_N ≥ ANN_CLUSTERS.

Physical versus intrinsic dimensionANN_NOISE_DIMENSIONS=64 spreads independent per-vector noise evenly over 64 of the 1024 stored dimensions; the other dimensions retain cluster-center signal. This creates a repeatable storage/compute scale workload without pretending that 1024 independent uniform-noise dimensions resemble production embeddings. With all 1024 dimensions independently noisy, same-cluster distances concentrate so strongly that exact Top-10 membership is nearly arbitrary: a 65k diagnostic produced local Recall@10 of 0.0125 at l_search=200 and only 0.178 at l_search=5000. Use a public or production corpus for an algorithm-quality claim.
-
ConceptRust / PythonC / C++ / JavaDefault
Random-read latency hintInput capability estimated_random_read_latency_nanosC/C++ field / Java estimatedRandomReadLatencyNanos()0: reuse the mandatory header read's elapsed time; positive values bypass measurement
Total Reader memorymemory_budget_bytesmemory_budget_bytes / constructor argument4 GiB; DiskANN divides it among resident state and adjacency/raw-vector caches. IVF-SQ reserves resident metadata first and uses the remainder for a bounded decoded-partition FIFO cache; zero disables that cache.
VariableMeaning
ANN_DATASET_NAMEComma-free label written to every CSV row
ANN_BASE_FVECS / ANN_QUERY_FVECS / ANN_GROUND_TRUTH_IVECSOptional 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.
ANN_N / ANN_NQ / ANN_DInferred for public files; an explicit value is validated as a shape assertion. Generated workloads retain defaults of 20,000 / 64 / 64.
ANN_DATA_GIBGenerated-workload raw float-vector GiB; derives n = floor(bytes / (4d)) and cannot be combined with public file paths.
ANN_TRAIN_NOptional training-sample override; omitted values resolve to min(N, max(65,536, 64 × nlist)).
ANN_KTop K
ANN_INDEXESall or a comma-separated subset of the five index names. Public multi-index runs automatically isolate each index in a child process.
ANN_STORAGE_CASESall or a comma-separated subset of local_ssd_warm_cache, remote_cache_2ms, and object_store_20ms. The default runs all three.
ANN_NLIST / ANN_NPROBEIVF list count / probed lists
ANN_PQ_CODE_RATIOIVF-PQ and DiskANN PQ-code/raw-vector byte ratio; default 0.0625 and automatically resolves a valid m
ANN_PQ_MOptional explicit subquantizer-count override; takes precedence over automatic sizing
ANN_RQ_BITSPersisted IVF-RQ bit width, 1–8; default 4
ANN_DISKANN_L_SEARCH / ANN_DISKANN_L_SEARCHESOne DiskANN search-list size, or a comma-separated sweep over one built index
ANN_DISKANN_BUILD_DISTANCEproduct_quantized by default; use full_precision as a graph-quality control
ANN_DISKANN_RAW_VECTOR_ENCODINGf16 by default; use f32 as an exact-distance and numeric-range control. The resolved value is written to every CSV row.
ANN_DISKANN_MEMORY_BUDGET_BYTESDiskANN's internal preflight build budget; default 8 GiB and excludes the benchmark's source-vector allocation
ANN_NOISE_DIMENSIONS / ANN_CLUSTERS / ANN_SEEDGenerated-workload distribution and reproducibility controls; ignored by public file loading.
ANN_OUTPUT_DIRDirectory whose filesystem supplies the local-storage path
ANN_KEEP_INDEXES1 retains generated index files; the default deletes each index after all selected serving cases
ANN_REUSE_INDEX_PATHSkips training/build and queries one retained index; requires a single ANN_INDEXES value
+
VariableMeaning
ANN_DATASET_NAMEComma-free label written to every CSV row
ANN_BASE_FVECS / ANN_QUERY_FVECS / ANN_GROUND_TRUTH_IVECSOptional 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.
ANN_N / ANN_NQ / ANN_DInferred for public files; an explicit value is validated as a shape assertion. Generated workloads retain defaults of 20,000 / 64 / 64.
ANN_DATA_GIBGenerated-workload raw float-vector GiB; derives n = floor(bytes / (4d)) and cannot be combined with public file paths.
ANN_TRAIN_NOptional training-sample override; omitted values resolve to min(N, max(65,536, 64 × nlist)).
ANN_KTop K
ANN_INDEXESThe default and all run the five L2 cases. Supply a comma-separated list to select cases, including IVF_FLAT_COSINE to benchmark cosine search with cosine ground truth. Public multi-index runs automatically isolate each index in a child process.
ANN_STORAGE_CASESall or a comma-separated subset of local_ssd_warm_cache, remote_cache_2ms, and object_store_20ms. The default runs all three.
ANN_NLIST / ANN_NPROBEIVF list count / probed lists
ANN_PQ_CODE_RATIOIVF-PQ and DiskANN PQ-code/raw-vector byte ratio; default 0.0625 and automatically resolves a valid m
ANN_PQ_MOptional explicit subquantizer-count override; takes precedence over automatic sizing
ANN_RQ_BITSPersisted IVF-RQ bit width, 1–8; default 4
ANN_DISKANN_L_SEARCH / ANN_DISKANN_L_SEARCHESOne DiskANN search-list size, or a comma-separated sweep over one built index
ANN_DISKANN_BUILD_DISTANCEproduct_quantized by default; use full_precision as a graph-quality control
ANN_DISKANN_RAW_VECTOR_ENCODINGf16 by default; use f32 as an exact-distance and numeric-range control. The resolved value is written to every CSV row.
ANN_DISKANN_MEMORY_BUDGET_BYTESDiskANN's internal preflight build budget; default 8 GiB and excludes the benchmark's source-vector allocation
ANN_NOISE_DIMENSIONS / ANN_CLUSTERS / ANN_SEEDGenerated-workload distribution and reproducibility controls; ignored by public file loading.
ANN_OUTPUT_DIRDirectory whose filesystem supplies the local-storage path
ANN_KEEP_INDEXES1 retains generated index files; the default deletes each index after all selected serving cases
ANN_REUSE_INDEX_PATHSkips training/build and queries one retained index; requires a single ANN_INDEXES value
Large-run memory boundaryThe 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 benchmark.

The benchmark executes three serving cases by default. local_ssd_warm_cache uses the real index file with no artificial delay. remote_cache_2ms adds a fixed 2 ms delay per pread call; one call represents a single read round containing all requested ranges. object_store_20ms uses the ObjectStore read plan: open/optimization and sequential-query latency are the measured CPU/I/O time plus 20 ms for every observed dependent read round, avoiding hours of idle wall-clock sleep while retaining the exact fixed-latency model; batch QPS still injects the real 20 ms sleep so concurrent-client overlap is measured rather than inferred. These models do not include bandwidth or operating-system cache misses. The DiskANN benchmark adapter completes positional reads synchronously, avoiding nested Rayon dispatch or cross-pool install while shared-cache loads are in flight; IVF retains parallel range reads. The local DiskANN case supplies a stable 100 µs capability hint for read-plan selection; this hint does not inject delay. The unified IVF Reader reuses the 64-byte type-dispatch header and loads resident metadata in one further contiguous read, reducing initialization from three rounds to two without changing any format. DiskANN is opened explicitly as LocalStorage, RemoteStorage, or ObjectStore with the default 4 GiB Reader budget, which is automatically partitioned into resident state and caches. The sequential sweep and batch call use separate opened-and-optimized Readers, preventing all benchmark queries from prewarming their own batch measurement. IVF-SQ now uses the default reader budget for a partition cache: sequential queries can reuse prior partitions, while the first batch includes payload reads and cache insertion. Simulated remote delay applies only to actual positional-read calls; cache hits issue none. CSV output records optimization rounds, ranges, and bytes separately from query I/O. Use ANN_STORAGE_CASES for a focused rerun against a retained index. See the recorded public-corpus results and interpretation.

ANN_FILTER_DENSITY optionally supplies a deterministic hash-based Roaring allow-list with a fraction in [0,1]. Unset means no filter; 1 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 filter_density. Keep the same density, data, and label for both sides of an A/B comparison.

diff --git a/tools/benchmark_pr.py b/tools/benchmark_pr.py index a052b2d2..949f719e 100644 --- a/tools/benchmark_pr.py +++ b/tools/benchmark_pr.py @@ -33,7 +33,7 @@ import time -INDEXES = ("IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "DISKANN") +INDEXES = ("IVF_FLAT", "IVF_FLAT_COSINE", "IVF_SQ", "IVF_PQ", "IVF_RQ", "DISKANN") WORKLOAD = { "ANN_DATASET_NAME": "ci-clustered-v1", "ANN_N": "10000",