Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 38 additions & 64 deletions core/benches/ann_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -113,27 +114,21 @@ fn run_benchmark() -> Result<(), Box<dyn std::error::Error>> {
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() {
Expand All @@ -145,6 +140,7 @@ fn run_benchmark() -> Result<(), Box<dyn std::error::Error>> {
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(),
Expand All @@ -156,7 +152,7 @@ fn run_benchmark() -> Result<(), Box<dyn std::error::Error>> {
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)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate the metric of a reused benchmark index

With ANN_REUSE_INDEX_PATH, search uses the metric stored in the file and ground truth uses the metric selected by ANN_INDEXES. In a small fixture, swapping same-dimension L2 and cosine IVF-FLAT files still produced a successful run and printed the selected case label, but recall dropped from 1 to 0. Please check the file's metric against the selected case before computing recall.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 89facfd. ANN_REUSE_INDEX_PATH now reads the persisted index metadata and validates its metric, index type and dimension against the selected benchmark case before computing ground truth. The regression writes an L2 and a cosine IVF-FLAT index of the same dimension and checks both directions of the mismatch.

return Ok(());
}

Expand All @@ -174,7 +170,7 @@ fn run_benchmark() -> Result<(), Box<dyn std::error::Error>> {
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)?;
}
Expand All @@ -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 {
Expand Down Expand Up @@ -663,18 +658,20 @@ struct IndexSpec {

fn index_specs(config: &Config) -> Vec<IndexSpec> {
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 {
Expand Down Expand Up @@ -1200,6 +1197,7 @@ fn exact_ground_truth(
dataset: &Dataset,
k: usize,
filter: Option<&RoaringTreemap>,
metric: MetricType,
) -> Vec<Vec<i64>> {
dataset
.queries
Expand All @@ -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::<Vec<_>>();
let retained = k.min(distances.len());
if retained != 0 {
Expand Down Expand Up @@ -1485,31 +1483,7 @@ fn read_usize_list_env(
}

fn selected_indexes() -> Result<Vec<String>, Box<dyn std::error::Error>> {
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<Vec<StorageCase>, Box<dyn std::error::Error>> {
Expand Down
67 changes: 67 additions & 0 deletions core/benches/support/ann_bench_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Vec<String>, Box<dyn std::error::Error>> {
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(())
}
Loading