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-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 96b8deb8 [core] Preserve cosine Top-K for finite scaled vectors (#1486)
96b8deb8 is described below
commit 96b8deb8f39a9c079d92e6ea25d291f6fb4774ca
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 22 20:15:46 2026 +0800
[core] Preserve cosine Top-K for finite scaled vectors (#1486)
---
Cargo.lock | 10 +-
DEPENDENCIES.rust.tsv | 4 +-
benchmarks/tpcds/DEPENDENCIES.rust.tsv | 4 +-
bindings/c/DEPENDENCIES.rust.tsv | 4 +-
bindings/go/DEPENDENCIES.rust.tsv | 4 +-
bindings/python/DEPENDENCIES.rust.tsv | 4 +-
crates/integration_tests/DEPENDENCIES.rust.tsv | 4 +-
.../integrations/datafusion/DEPENDENCIES.rust.tsv | 4 +-
crates/paimon-rest-server/DEPENDENCIES.rust.tsv | 4 +-
crates/paimon/Cargo.toml | 3 +
crates/paimon/DEPENDENCIES.rust.tsv | 4 +-
crates/paimon/src/common/number.rs | 56 ++
crates/paimon/src/table/de_vector_read.rs | 518 +++++++++++++----
.../src/table/de_vector_read/multi_vector.rs | 47 +-
crates/paimon/src/table/de_vector_read/tests.rs | 463 ++++++++++++++-
crates/paimon/src/table/hybrid_search_builder.rs | 212 ++++++-
crates/paimon/src/table/pk_search_position.rs | 41 +-
crates/paimon/src/table/pk_search_ranker.rs | 149 ++++-
.../paimon/src/table/pk_vector_data_file_reader.rs | 8 +-
crates/paimon/src/table/pk_vector_read.rs | 43 +-
crates/paimon/src/table/vector_read.rs | 58 +-
crates/paimon/src/vindex/multi_vector.rs | 21 +-
crates/paimon/src/vindex/pkvector/exact.rs | 19 +-
crates/paimon/src/vindex/pkvector/metric.rs | 622 +++++++++++++++++++--
docs/src/sql.md | 13 +
25 files changed, 2016 insertions(+), 303 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index d69d178c..c9e6cf34 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2824,9 +2824,9 @@ checksum =
"00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
-version = "1.2.2"
+version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -4945,8 +4945,10 @@ dependencies = [
"lru 0.18.2",
"lz4_flex 0.14.0",
"lzokay-native",
+ "matrixmultiply",
"md-5 0.10.6",
"num-bigint 0.4.8",
+ "num-rational",
"num-traits",
"opendal-core",
"opendal-http-transport-reqwest",
@@ -7734,9 +7736,9 @@ checksum =
"8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
-version = "2.5.8"
+version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
diff --git a/DEPENDENCIES.rust.tsv b/DEPENDENCIES.rust.tsv
index ec7b959f..22271225 100644
--- a/DEPENDENCIES.rust.tsv
+++ b/DEPENDENCIES.rust.tsv
@@ -227,7 +227,7 @@ [email protected]
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X X
X
[email protected] X
X
[email protected]
X
@@ -653,7 +653,7 @@ [email protected] X
X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
index eee47426..ddbb27bc 100644
--- a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
+++ b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
@@ -167,7 +167,7 @@ [email protected]
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X X
X
[email protected] X
X
[email protected]
X
@@ -493,7 +493,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/c/DEPENDENCIES.rust.tsv b/bindings/c/DEPENDENCIES.rust.tsv
index 50dfcf3c..bb00f4b5 100644
--- a/bindings/c/DEPENDENCIES.rust.tsv
+++ b/bindings/c/DEPENDENCIES.rust.tsv
@@ -120,7 +120,7 @@ [email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
@@ -441,7 +441,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/go/DEPENDENCIES.rust.tsv
b/bindings/go/DEPENDENCIES.rust.tsv
index 50dfcf3c..bb00f4b5 100644
--- a/bindings/go/DEPENDENCIES.rust.tsv
+++ b/bindings/go/DEPENDENCIES.rust.tsv
@@ -120,7 +120,7 @@ [email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
@@ -441,7 +441,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/python/DEPENDENCIES.rust.tsv
b/bindings/python/DEPENDENCIES.rust.tsv
index 134479f2..f590f570 100644
--- a/bindings/python/DEPENDENCIES.rust.tsv
+++ b/bindings/python/DEPENDENCIES.rust.tsv
@@ -181,7 +181,7 @@ [email protected]
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X X
X
[email protected] X
X
[email protected]
X
@@ -560,7 +560,7 @@ [email protected] X
X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/crates/integration_tests/DEPENDENCIES.rust.tsv
b/crates/integration_tests/DEPENDENCIES.rust.tsv
index 49767b97..6c120d09 100644
--- a/crates/integration_tests/DEPENDENCIES.rust.tsv
+++ b/crates/integration_tests/DEPENDENCIES.rust.tsv
@@ -112,7 +112,7 @@ [email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
@@ -405,7 +405,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
index ffe3957c..21aa7d64 100644
--- a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
+++ b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
@@ -190,7 +190,7 @@ [email protected]
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X X
X
[email protected] X
X
[email protected]
X
@@ -555,7 +555,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
index 0cd87e93..d22c457a 100644
--- a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
+++ b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
@@ -115,7 +115,7 @@ [email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
@@ -411,7 +411,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon/Cargo.toml b/crates/paimon/Cargo.toml
index 25d0f8f8..55bddfe6 100644
--- a/crates/paimon/Cargo.toml
+++ b/crates/paimon/Cargo.toml
@@ -115,6 +115,7 @@ lru = "0.18.2"
roaring = "0.11"
datasketches = "0.2"
num-bigint = "0.4"
+num-rational = "0.4"
num-traits = "0.2"
# Already in the Arrow dependency tree; shortest decimals use ties-to-even.
ryu = "1"
@@ -160,6 +161,8 @@ paimon-mosaic-core = "0.3.0"
paimon-ftindex-core = "0.2.0"
tempfile = "3"
paimon-vindex-core = "0.5.0"
+# Also used by paimon-vindex-core for the single-precision matrix multiply.
+matrixmultiply = "0.3.11"
vortex = { version = "0.90.0", features = ["tokio"], optional = true }
libloading = "0.9"
log = "0.4"
diff --git a/crates/paimon/DEPENDENCIES.rust.tsv
b/crates/paimon/DEPENDENCIES.rust.tsv
index a148bd21..c03bf34a 100644
--- a/crates/paimon/DEPENDENCIES.rust.tsv
+++ b/crates/paimon/DEPENDENCIES.rust.tsv
@@ -165,7 +165,7 @@ [email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
@@ -547,7 +547,7 @@ [email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected]
X X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon/src/common/number.rs
b/crates/paimon/src/common/number.rs
index efd648c6..46e39d05 100644
--- a/crates/paimon/src/common/number.rs
+++ b/crates/paimon/src/common/number.rs
@@ -25,6 +25,62 @@ use num_traits::ToPrimitive;
mod floating;
pub(crate) use floating::parse_java_float;
+/// Accumulate finite terms as nonoverlapping partial sums, retaining roundoff
+/// that can survive cancellation in a later term.
+pub(crate) fn accumulate_f64_partials(
+ terms: impl IntoIterator<Item = f64>,
+ partials: &mut Vec<f64>,
+) {
+ partials.clear();
+ for mut term in terms {
+ let mut kept = 0;
+ for i in 0..partials.len() {
+ let mut part = partials[i];
+ if term.abs() < part.abs() {
+ std::mem::swap(&mut term, &mut part);
+ }
+ // With |term| >= |part|, FastTwoSum gives an exact residual.
+ let sum = term + part;
+ let residual = part - (sum - term);
+ if residual != 0.0 {
+ partials[kept] = residual;
+ kept += 1;
+ }
+ term = sum;
+ }
+ partials.truncate(kept);
+ if term != 0.0 {
+ partials.push(term);
+ }
+ }
+}
+
+/// Round a nonoverlapping sum once, including when a smaller part resolves a
+/// midpoint between two `f64` values.
+pub(crate) fn round_f64_partials(partials: &[f64]) -> f64 {
+ let mut parts = partials.iter().rev().copied();
+ let mut total = parts.next().unwrap_or(0.0);
+ while let Some(part) = parts.next() {
+ let sum = total + part;
+ let residual = part - (sum - total);
+ total = sum;
+ if residual != 0.0 {
+ if parts
+ .next()
+ .is_some_and(|next| next.is_sign_negative() ==
residual.is_sign_negative())
+ {
+ let twice = 2.0 * residual;
+ let adjusted = total + twice;
+ if adjusted - total == twice {
+ total = adjusted;
+ }
+ }
+ break;
+ }
+ }
+ total
+}
+
/// Character.digit for decimal BMP digits (Java scans UTF-16 chars).
pub(crate) fn java_decimal_digit(ch: char) -> Option<u8> {
const ZEROES: &[u32] = &[
diff --git a/crates/paimon/src/table/de_vector_read.rs
b/crates/paimon/src/table/de_vector_read.rs
index e72eaa2e..06d67ee5 100644
--- a/crates/paimon/src/table/de_vector_read.rs
+++ b/crates/paimon/src/table/de_vector_read.rs
@@ -50,6 +50,7 @@ use crate::vindex::executor::{
acquire_process_global_search_permit, drain_indexed_jobs,
ensure_global_index_executor_capacity, execute_global_index_with_guard,
};
+use crate::vindex::pkvector::metric::{cosine_norm, cosine_similarity,
CosineDot, CosineOutput};
use crate::vindex::range_reader::{RangeReadLimiter, VindexFileReader};
use crate::vindex::reader::VindexVectorGlobalIndexReader;
use crate::vindex::{is_vindex_index_type, vector_search_timing_enabled};
@@ -62,8 +63,9 @@ use paimon_vindex_core::io::SeekRead;
use roaring::RoaringTreemap;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
+use std::cell::OnceCell;
use std::cmp::Ordering;
-use std::collections::{HashMap, HashSet};
+use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Cursor;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -604,6 +606,8 @@ async fn execute_vector_file_probes(
const RAW_SCORE_MATRIX_MIN_QUERY_COUNT: usize = 4;
const RAW_SCORE_MATRIX_TARGET_ELEMENTS: usize = 1 << 20;
+const RAW_COSINE_ABSOLUTE_BLOCK_VECTORS: usize = 256;
+const RAW_COSINE_ABSOLUTE_BLOCK_VALUES: usize = 384 * 1024;
const RAW_TOP_K_MIN_PARTITION_SIZE: usize = 1 << 12;
@@ -2677,9 +2681,9 @@ struct RawScoringPlan {
all_query_indices: Vec<usize>,
shared_filter_groups: Vec<SharedRawFilterGroup>,
candidate_query_indices: HashMap<u64, Vec<usize>>,
- query_l2_squared_norms: Vec<f32>,
+ query_norms: RawVectorNorms,
dense_query_dimension: Option<usize>,
- dense_query_matrix: Option<Vec<f32>>,
+ dense_query_matrix: Option<DenseVectorMatrix>,
}
struct SharedRawFilterGroup {
@@ -2687,22 +2691,62 @@ struct SharedRawFilterGroup {
query_indices: Vec<usize>,
}
+#[derive(Default)]
+struct RawVectorNorms {
+ l2_squared: Vec<f32>,
+ cosine: Vec<f64>,
+}
+
+impl RawVectorNorms {
+ fn new<'a>(vectors: impl Iterator<Item = &'a [f32]>, metric:
RawVectorMetric) -> Self {
+ let mut norms = Self::default();
+ match metric {
+ RawVectorMetric::L2 => {
+ norms.l2_squared = vectors
+ .map(|vector| vector.iter().map(|value| value *
value).sum())
+ .collect();
+ }
+ RawVectorMetric::Cosine => {
+ norms.cosine = vectors.map(cosine_norm).collect();
+ }
+ RawVectorMetric::InnerProduct => {}
+ }
+ norms
+ }
+}
+
+enum DenseVectorMatrix {
+ F32(Vec<f32>),
+ F64(Vec<f64>),
+}
+
+impl DenseVectorMatrix {
+ fn with_capacity(metric: RawVectorMetric, len: usize) -> Self {
+ match metric {
+ RawVectorMetric::Cosine => Self::F64(Vec::with_capacity(len)),
+ _ => Self::F32(Vec::with_capacity(len)),
+ }
+ }
+
+ fn append(&mut self, vector: &[f32]) {
+ match self {
+ Self::F32(matrix) => matrix.extend_from_slice(vector),
+ Self::F64(matrix) =>
matrix.extend(vector.iter().copied().map(f64::from)),
+ }
+ }
+}
+
impl RawScoringPlan {
fn new(vector_searches: &[VectorSearch], metric: RawVectorMetric) -> Self {
let mut all_query_indices = Vec::new();
let mut shared_filter_groups = Vec::new();
let mut candidate_query_indices: HashMap<u64, Vec<usize>> =
HashMap::new();
- let query_l2_squared_norms = vector_searches
- .iter()
- .map(|vector_search| match metric {
- RawVectorMetric::L2 | RawVectorMetric::Cosine => vector_search
- .vector
- .iter()
- .map(|value| value * value)
- .sum::<f32>(),
- RawVectorMetric::InnerProduct => 0.0,
- })
- .collect();
+ let query_norms = RawVectorNorms::new(
+ vector_searches
+ .iter()
+ .map(|search| search.vector.as_slice()),
+ metric,
+ );
if let Some(include_row_ids) =
shared_batch_include_row_ids(vector_searches) {
shared_filter_groups.push(SharedRawFilterGroup {
@@ -2732,10 +2776,12 @@ impl RawScoringPlan {
.iter()
.all(|&query_index| vector_searches[query_index].vector.len()
== dimension)
.then(|| {
- let mut matrix =
-
Vec::with_capacity(all_query_indices.len().saturating_mul(dimension));
+ let mut matrix = DenseVectorMatrix::with_capacity(
+ metric,
+ all_query_indices.len().saturating_mul(dimension),
+ );
for &query_index in &all_query_indices {
-
matrix.extend_from_slice(&vector_searches[query_index].vector);
+ matrix.append(&vector_searches[query_index].vector);
}
matrix
})
@@ -2745,7 +2791,7 @@ impl RawScoringPlan {
all_query_indices,
shared_filter_groups,
candidate_query_indices,
- query_l2_squared_norms,
+ query_norms,
dense_query_dimension,
dense_query_matrix,
}
@@ -2926,7 +2972,8 @@ fn collect_raw_batch_vector_batch(
.then_some(scoring_plan.dense_query_dimension)
.flatten();
let mut dense_row_ids = Vec::with_capacity(batch.num_rows());
- let mut dense_vectors = Vec::with_capacity(
+ let mut dense_vectors = DenseVectorMatrix::with_capacity(
+ metric,
batch
.num_rows()
.saturating_mul(dense_dimension.unwrap_or_default()),
@@ -2989,7 +3036,7 @@ fn collect_raw_batch_vector_batch(
ensure_raw_vector_dimension(dimension,
vector_searches[query_index].vector.len())?;
}
dense_row_ids.push(row_id);
- dense_vectors.extend_from_slice(&values.values()[start..end]);
+ dense_vectors.append(&values.values()[start..end]);
} else {
for &query_index in &scoring_plan.all_query_indices {
offer_raw_vector_score(
@@ -3031,9 +3078,16 @@ fn collect_raw_batch_vector_batch(
if !dense_row_ids.is_empty() {
let query_matrix = scoring_plan
.dense_query_matrix
- .as_deref()
+ .as_ref()
.expect("dense query dimensions were validated above");
let dimension = dense_dimension.expect("dense rows require dense
queries");
+ let stored_cosine_norms: Vec<_> = match &dense_vectors {
+ DenseVectorMatrix::F32(_) => Vec::new(),
+ DenseVectorMatrix::F64(rows) => rows
+ .chunks_exact(dimension)
+ .map(DenseCosineNorm::new)
+ .collect(),
+ };
let queries_per_chunk = (RAW_SCORE_MATRIX_TARGET_ELEMENTS /
dense_row_ids.len())
.max(1)
.min(scoring_plan.all_query_indices.len());
@@ -3044,16 +3098,31 @@ fn collect_raw_batch_vector_batch(
{
let query_start = query_chunk_index * queries_per_chunk *
dimension;
let query_end = query_start + query_indices.len() * dimension;
- let scores = compute_raw_vector_score_matrix(
- &dense_vectors,
- dense_row_ids.len(),
- &query_matrix[query_start..query_end],
- query_indices.len(),
- dimension,
- &scoring_plan.query_l2_squared_norms,
- query_indices,
- metric,
- )?;
+ let scores = match (&dense_vectors, query_matrix) {
+ (DenseVectorMatrix::F32(rows),
DenseVectorMatrix::F32(queries)) => {
+ compute_raw_vector_score_matrix(
+ rows,
+ dense_row_ids.len(),
+ &queries[query_start..query_end],
+ query_indices.len(),
+ dimension,
+ &scoring_plan.query_norms,
+ query_indices,
+ metric,
+ )?
+ }
+ (DenseVectorMatrix::F64(rows),
DenseVectorMatrix::F64(queries)) => {
+ compute_raw_cosine_score_matrix(
+ rows,
+ &stored_cosine_norms,
+ &queries[query_start..query_end],
+ &scoring_plan.query_norms.cosine,
+ query_indices,
+ dimension,
+ )?
+ }
+ _ => unreachable!("stored and query matrices use the same
metric"),
+ };
for (matrix_query_index, &query_index) in
query_indices.iter().enumerate() {
let query_scores = &scores[matrix_query_index *
dense_row_ids.len()
..(matrix_query_index + 1) * dense_row_ids.len()];
@@ -3090,17 +3159,11 @@ fn compute_raw_vector_score_matrix(
query_vectors: &[f32],
query_count: usize,
dimension: usize,
- query_l2_squared_norms: &[f32],
+ query_norms: &RawVectorNorms,
query_indices: &[usize],
metric: RawVectorMetric,
) -> crate::Result<Vec<f32>> {
- let score_count =
- row_count
- .checked_mul(query_count)
- .ok_or_else(|| crate::Error::DataInvalid {
- message: "Vector raw search score matrix is too
large".to_string(),
- source: None,
- })?;
+ let score_count = raw_score_matrix_size(row_count, query_count)?;
debug_assert_eq!(stored_vectors.len(), row_count * dimension);
debug_assert_eq!(query_vectors.len(), query_count * dimension);
debug_assert_eq!(query_indices.len(), query_count);
@@ -3122,52 +3185,316 @@ fn compute_raw_vector_score_matrix(
return Ok(scores);
}
- let stored_l2_squared_norms = stored_vectors
- .chunks_exact(dimension)
- .map(|vector| vector.iter().map(|value| value * value).sum::<f32>())
- .collect::<Vec<_>>();
+ debug_assert_eq!(metric, RawVectorMetric::L2);
+ let stored_norms =
RawVectorNorms::new(stored_vectors.chunks_exact(dimension), metric);
for (matrix_query_index, &query_index) in query_indices.iter().enumerate()
{
- for (row_index, &stored_l2_squared_norm) in
stored_l2_squared_norms.iter().enumerate() {
+ let query_l2_squared_norm = query_norms.l2_squared[query_index];
+ for (row_index, &stored_l2_squared_norm) in
stored_norms.l2_squared.iter().enumerate() {
let score = &mut scores[matrix_query_index * row_count +
row_index];
- let query_l2_squared_norm = query_l2_squared_norms[query_index];
- *score = match metric {
- RawVectorMetric::L2 => {
- let squared_distance =
- stored_l2_squared_norm + query_l2_squared_norm - 2.0 *
*score;
- // The norm/dot reconstruction loses the low-order
difference when two
- // large vectors are close. Estimate a conservative
accumulation-error
- // bound and preserve the former scalar semantics inside
that region.
- let roundoff_bound = (stored_l2_squared_norm.abs()
- + query_l2_squared_norm.abs()
- + 2.0 * score.abs())
- * f32::EPSILON
- * (dimension as f32 + 2.0)
- * 4.0;
- if !squared_distance.is_finite() || squared_distance <=
roundoff_bound {
- let stored =
- &stored_vectors[row_index * dimension..(row_index
+ 1) * dimension];
- let query = &query_vectors
- [matrix_query_index *
dimension..(matrix_query_index + 1) * dimension];
- compute_raw_vector_l2_score(query, stored)
- } else {
- 1.0 / (1.0 + squared_distance)
- }
+ let squared_distance = stored_l2_squared_norm +
query_l2_squared_norm - 2.0 * *score;
+ // The norm/dot reconstruction loses the low-order difference when
two
+ // large vectors are close. Estimate a conservative
accumulation-error
+ // bound and preserve the former scalar semantics inside that
region.
+ let roundoff_bound =
+ (stored_l2_squared_norm.abs() + query_l2_squared_norm.abs() +
2.0 * score.abs())
+ * f32::EPSILON
+ * (dimension as f32 + 2.0)
+ * 4.0;
+ *score = if !squared_distance.is_finite() || squared_distance <=
roundoff_bound {
+ let stored = &stored_vectors[row_index * dimension..(row_index
+ 1) * dimension];
+ let query = &query_vectors
+ [matrix_query_index * dimension..(matrix_query_index + 1)
* dimension];
+ compute_raw_vector_l2_score(query, stored)
+ } else {
+ 1.0 / (1.0 + squared_distance)
+ };
+ }
+ }
+ Ok(scores)
+}
+
+struct DenseCosineNorm {
+ length: f64,
+ mixed_signs: bool,
+ at_most_one_nonzero: bool,
+ scaled_integer_max: OnceCell<Option<f64>>,
+}
+
+impl DenseCosineNorm {
+ fn new(vector: &[f64]) -> Self {
+ Self {
+ length: cosine_norm(vector),
+ mixed_signs: has_mixed_signs(vector),
+ at_most_one_nonzero: has_at_most_one_nonzero(vector),
+ scaled_integer_max: OnceCell::new(),
+ }
+ }
+}
+
+fn has_mixed_signs(vector: &[f64]) -> bool {
+ vector.iter().any(|&value| value < 0.0) && vector.iter().any(|&value|
value > 0.0)
+}
+
+fn has_at_most_one_nonzero(vector: &[f64]) -> bool {
+ vector
+ .iter()
+ .filter(|&&value| value != 0.0)
+ .nth(1)
+ .is_none()
+}
+
+/// Largest absolute coefficient after dividing a vector by the common power
+/// of two at its least significant set bit.
+fn scaled_integer_max(vector: &[f64]) -> Option<f64> {
+ const FRACTION_BITS: u32 = f64::MANTISSA_DIGITS - 1;
+ const FRACTION_MASK: u64 = (1 << FRACTION_BITS) - 1;
+ const EXPONENT_BIAS: i32 = 1023;
+ let mut maximum = 0_u64;
+ let mut least_exponent = i32::MAX;
+ for &value in vector {
+ let magnitude = value.abs().to_bits();
+ if magnitude == 0 {
+ continue;
+ }
+ let exponent = (magnitude >> FRACTION_BITS) as i32;
+ // Nonzero finite f32 coordinates are normal after widening to f64.
+ if exponent == 0 || exponent == 0x7ff {
+ return None;
+ }
+ let low_bit = magnitude.trailing_zeros().min(FRACTION_BITS);
+ least_exponent =
+ least_exponent.min(exponent - EXPONENT_BIAS - (FRACTION_BITS -
low_bit) as i32);
+ maximum = maximum.max(magnitude);
+ }
+ if maximum == 0 {
+ return Some(0.0);
+ }
+ let scaled_exponent = (maximum >> FRACTION_BITS) as i32 - least_exponent;
+ if scaled_exponent >= EXPONENT_BIAS + f64::MANTISSA_DIGITS as i32 {
+ return None;
+ }
+ Some(f64::from_bits(
+ ((scaled_exponent as u64) << FRACTION_BITS) | (maximum &
FRACTION_MASK),
+ ))
+}
+
+fn integer_dot_is_exact(query_max: Option<f64>, stored_max: Option<f64>,
dimension: usize) -> bool {
+ // All products share a power-of-two scale. Every partial sum of their
+ // integer coefficients fits in f64 when the absolute sum is below 2^53.
+ const F64_INTEGER_LIMIT: f64 = (1_u64 << f64::MANTISSA_DIGITS) as f64;
+ query_max
+ .zip(stored_max)
+ .is_some_and(|(q, s)| q * s * (dimension as f64) < F64_INTEGER_LIMIT)
+}
+
+fn compute_raw_cosine_score_matrix(
+ stored_vectors: &[f64],
+ stored_norms: &[DenseCosineNorm],
+ query_vectors: &[f64],
+ query_norms: &[f64],
+ query_indices: &[usize],
+ dimension: usize,
+) -> crate::Result<Vec<f32>> {
+ let row_count = stored_vectors.len() / dimension;
+ let query_count = query_vectors.len() / dimension;
+ debug_assert_eq!(stored_norms.len(), row_count);
+ debug_assert_eq!(query_indices.len(), query_count);
+ let dots = compute_raw_cosine_dot_matrix(query_vectors, stored_vectors,
dimension)?;
+ if dots.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let similarity = CosineOutput::Similarity;
+ let mut scores = Vec::with_capacity(dots.len());
+ let mut partials = Vec::new();
+ let mut needs_tighter_bound = Vec::new();
+ for ((query, &query_index), query_dots) in query_vectors
+ .chunks_exact(dimension)
+ .zip(query_indices)
+ .zip(dots.chunks_exact(row_count))
+ {
+ let query_norm = query_norms[query_index];
+ let query_mixed_signs = has_mixed_signs(query);
+ let query_at_most_one_nonzero = has_at_most_one_nonzero(query);
+ let query_scaled_integer_max = OnceCell::new();
+ for ((stored, stored_norm), &dot) in stored_vectors
+ .chunks_exact(dimension)
+ .zip(stored_norms)
+ .zip(query_dots)
+ {
+ let norm_product = query_norm * stored_norm.length;
+ // A single product is exact.
+ // With uniform product signs, estimate the absolute sum from the
+ // dot. Otherwise use the norm product (Cauchy-Schwarz).
+ let exact = query_at_most_one_nonzero ||
stored_norm.at_most_one_nonzero;
+ let may_cancel = !exact && (query_mixed_signs ||
stored_norm.mixed_signs);
+ let dot_product = if exact {
+ CosineDot::Exact(dot)
+ } else {
+ CosineDot::Approximate {
+ value: dot,
+ absolute_sum_bound: if may_cancel { norm_product } else {
dot.abs() },
}
- RawVectorMetric::Cosine => {
- let denominator = stored_l2_squared_norm.sqrt() *
query_l2_squared_norm.sqrt();
- if denominator == 0.0 {
- 0.0
- } else {
- *score / denominator
- }
+ };
+ let score = match similarity.try_round_from_dot(dot_product,
norm_product, dimension) {
+ Ok(score) => score,
+ Err(_)
+ if !exact
+ && integer_dot_is_exact(
+ *query_scaled_integer_max.get_or_init(||
scaled_integer_max(query)),
+ *stored_norm
+ .scaled_integer_max
+ .get_or_init(|| scaled_integer_max(stored)),
+ dimension,
+ ) =>
+ {
+ similarity.round_from_dot(
+ CosineDot::Exact(dot),
+ norm_product,
+ query,
+ stored,
+ &mut partials,
+ )
}
- RawVectorMetric::InnerProduct => unreachable!(),
+ Err(_) if may_cancel => {
+ needs_tighter_bound.push(scores.len());
+ 0.0
+ }
+ Err(bounds) => similarity.round_exact(
+ dot_product,
+ norm_product,
+ query,
+ stored,
+ bounds,
+ &mut partials,
+ ),
};
+ scores.push(score);
+ }
+ }
+
+ let mut refine = |position: usize, absolute_sum: Option<f64>| {
+ let query_index = position / row_count;
+ let row_index = position % row_count;
+ let query = &query_vectors[query_index * dimension..][..dimension];
+ let stored = &stored_vectors[row_index * dimension..][..dimension];
+ let absolute_sum_bound = absolute_sum
+ .unwrap_or_else(|| query.iter().zip(stored).map(|(q, s)| (q *
s).abs()).sum());
+ let norm_product = query_norms[query_indices[query_index]] *
stored_norms[row_index].length;
+ scores[position] = similarity.round_from_dot(
+ CosineDot::Approximate {
+ value: dots[position],
+ absolute_sum_bound,
+ },
+ norm_product,
+ query,
+ stored,
+ &mut partials,
+ );
+ };
+
+ // Refine a few uncertain pairs directly. Limit each temporary coordinate
+ // copy to a block of queries or rows when batching their refinement.
+ if needs_tighter_bound.len() >= dots.len().div_ceil(8).max(32) {
+ let block_size = (RAW_COSINE_ABSOLUTE_BLOCK_VALUES / dimension)
+ .clamp(1, RAW_COSINE_ABSOLUTE_BLOCK_VECTORS);
+ let mut blocks = BTreeMap::<(usize, usize), Vec<usize>>::new();
+ for position in needs_tighter_bound {
+ let query_block = position / row_count / block_size;
+ let row_block = (position % row_count) / block_size;
+ blocks
+ .entry((query_block, row_block))
+ .or_default()
+ .push(position);
+ }
+ let mut absolute_queries =
Vec::with_capacity(block_size.min(query_count) * dimension);
+ let mut absolute_rows = Vec::with_capacity(block_size.min(row_count) *
dimension);
+ let mut previous_query_block = None;
+ for ((query_block, row_block), positions) in blocks {
+ let query_start = query_block * block_size;
+ let row_start = row_block * block_size;
+ let row_end = (row_start + block_size).min(row_count);
+ if previous_query_block != Some(query_block) {
+ let query_end = (query_start + block_size).min(query_count);
+ absolute_queries.clear();
+ absolute_queries.extend(
+ query_vectors[query_start * dimension..query_end *
dimension]
+ .iter()
+ .map(|value| value.abs()),
+ );
+ previous_query_block = Some(query_block);
+ }
+ absolute_rows.clear();
+ absolute_rows.extend(
+ stored_vectors[row_start * dimension..row_end * dimension]
+ .iter()
+ .map(|value| value.abs()),
+ );
+ let absolute_dots =
+ compute_raw_cosine_dot_matrix(&absolute_queries,
&absolute_rows, dimension)?;
+ for position in positions {
+ let local_query = position / row_count - query_start;
+ let local_row = position % row_count - row_start;
+ refine(
+ position,
+ Some(absolute_dots[local_query * (row_end - row_start) +
local_row]),
+ );
+ }
+ }
+ } else {
+ for position in needs_tighter_bound {
+ refine(position, None);
}
}
Ok(scores)
}
+fn compute_raw_cosine_dot_matrix(
+ query_vectors: &[f64],
+ stored_vectors: &[f64],
+ dimension: usize,
+) -> crate::Result<Vec<f64>> {
+ let row_count = stored_vectors.len() / dimension;
+ let query_count = query_vectors.len() / dimension;
+ let mut dots = vec![0.0; raw_score_matrix_size(row_count, query_count)?];
+ if dots.is_empty() {
+ return Ok(dots);
+ }
+
+ // Queries index rows of the output and stored vectors index columns.
+ // SAFETY: Each dimension is derived from the backing slices, so the input
+ // strides stay within the respective buffers and the output strides are
+ // disjoint within the checked query_count * row_count allocation.
+ unsafe {
+ matrixmultiply::dgemm(
+ query_count,
+ dimension,
+ row_count,
+ 1.0,
+ query_vectors.as_ptr(),
+ dimension as isize,
+ 1,
+ stored_vectors.as_ptr(),
+ 1,
+ dimension as isize,
+ 0.0,
+ dots.as_mut_ptr(),
+ row_count as isize,
+ 1,
+ );
+ }
+ Ok(dots)
+}
+
+fn raw_score_matrix_size(row_count: usize, query_count: usize) ->
crate::Result<usize> {
+ row_count
+ .checked_mul(query_count)
+ .ok_or_else(|| crate::Error::DataInvalid {
+ message: "Vector raw search score matrix is too large".to_string(),
+ source: None,
+ })
+}
+
fn ensure_raw_vector_values_not_null(
values: &Float32Array,
start: usize,
@@ -3208,7 +3535,7 @@ fn offer_raw_vector_score(
ensure_raw_vector_dimension(stored_len, vector_search.vector.len())?;
let score = compute_raw_vector_score_from_values(
&vector_search.vector,
- scoring_plan.query_l2_squared_norms[query_index],
+ scoring_plan.query_norms.cosine.get(query_index).copied(),
row.values,
row.start,
row.end,
@@ -3220,7 +3547,7 @@ fn offer_raw_vector_score(
fn compute_raw_vector_score_from_values(
query: &[f32],
- query_l2_squared_norm: f32,
+ query_cosine_norm: Option<f64>,
values: &Float32Array,
start: usize,
end: usize,
@@ -3229,21 +3556,11 @@ fn compute_raw_vector_score_from_values(
debug_assert_eq!(query.len(), end - start);
match metric {
RawVectorMetric::L2 => compute_raw_vector_l2_score(query,
&values.values()[start..end]),
- RawVectorMetric::Cosine => {
- let mut dot = 0.0;
- let mut norm_b = 0.0;
- for (q, value_index) in query.iter().zip(start..end) {
- let stored = values.value(value_index);
- dot += q * stored;
- norm_b += stored * stored;
- }
- let denominator = query_l2_squared_norm.sqrt() * norm_b.sqrt();
- if denominator == 0.0 {
- 0.0
- } else {
- dot / denominator
- }
- }
+ RawVectorMetric::Cosine => cosine_similarity(
+ query,
+ query_cosine_norm.expect("cosine searches have a query norm"),
+ &values.values()[start..end],
+ ),
RawVectorMetric::InnerProduct => query
.iter()
.zip(start..end)
@@ -3275,22 +3592,7 @@ fn row_id_to_u64(row_id: i64) -> crate::Result<u64> {
fn compute_raw_vector_score(query: &[f32], stored: &[f32], metric:
RawVectorMetric) -> f32 {
match metric {
RawVectorMetric::L2 => compute_raw_vector_l2_score(query, stored),
- RawVectorMetric::Cosine => {
- let mut dot = 0.0;
- let mut norm_a = 0.0;
- let mut norm_b = 0.0;
- for (q, s) in query.iter().zip(stored.iter()) {
- dot += q * s;
- norm_a += q * q;
- norm_b += s * s;
- }
- let denominator = norm_a.sqrt() * norm_b.sqrt();
- if denominator == 0.0 {
- 0.0
- } else {
- dot / denominator
- }
- }
+ RawVectorMetric::Cosine => cosine_similarity(query,
cosine_norm(query), stored),
RawVectorMetric::InnerProduct =>
query.iter().zip(stored.iter()).map(|(q, s)| q * s).sum(),
}
}
diff --git a/crates/paimon/src/table/de_vector_read/multi_vector.rs
b/crates/paimon/src/table/de_vector_read/multi_vector.rs
index 23b46435..f09d44df 100644
--- a/crates/paimon/src/table/de_vector_read/multi_vector.rs
+++ b/crates/paimon/src/table/de_vector_read/multi_vector.rs
@@ -16,8 +16,12 @@
// under the License.
use super::{RawScoreTopK, VectorSearch};
+use crate::common::number::{accumulate_f64_partials, round_f64_partials};
use crate::spec::ROW_ID_FIELD_NAME;
-use crate::vindex::multi_vector::{cosine, invalid, norm, validate_queries,
MultiVectorArray};
+use crate::vindex::multi_vector::{invalid, validate_queries, MultiVectorArray};
+use crate::vindex::pkvector::metric::{
+ cosine_norm, cosine_similarity_f64, cosine_similarity_with_norms,
+};
use crate::Result;
use arrow_array::{Array, Int64Array, RecordBatch};
use serde::{Deserialize, Serialize};
@@ -51,7 +55,7 @@ impl ListScorer {
validate_queries(&queries, None)?;
Ok(Self {
mode,
- query_norms: queries.into_iter().map(norm).collect(),
+ query_norms: queries.into_iter().map(cosine_norm).collect(),
})
}
@@ -74,6 +78,8 @@ impl ListScorer {
.ok_or_else(|| invalid("MultiVector scoring requires non-null
Int64 _ROW_ID"))?;
let mut selected = Vec::with_capacity(searches.len());
let mut maxima = vec![f64::NEG_INFINITY; searches.len()];
+ let mut partials = Vec::new();
+ let aggregate_queries = matches!(self.mode, ListScoring::MaxSim) &&
searches.len() > 1;
let shared_filter = searches[0].effective_include_row_ids();
for (row, &id) in row_ids.values().iter().enumerate() {
let id = u64::try_from(id).map_err(|_| invalid("Negative
MultiVector row ID"))?;
@@ -102,19 +108,40 @@ impl ListScorer {
for embedding in column.row(row, dimension) {
let embedding = embedding?;
found = true;
- let vector_norm = norm(embedding);
+ let vector_norm = cosine_norm(embedding);
for &i in &selected {
- maxima[i] = maxima[i].max(cosine(
- &searches[i].vector,
- self.query_norms[i],
- embedding,
- vector_norm,
- ));
+ let query = &searches[i].vector;
+ let query_norm = self.query_norms[i];
+ let similarity = if aggregate_queries {
+ cosine_similarity_f64(
+ query,
+ embedding,
+ query_norm * vector_norm,
+ &mut partials,
+ )
+ } else {
+ f64::from(cosine_similarity_with_norms(
+ query,
+ query_norm,
+ embedding,
+ vector_norm,
+ &mut partials,
+ ))
+ };
+ maxima[i] = maxima[i].max(similarity);
}
}
if found {
match self.mode {
- ListScoring::MaxSim => top_k[0].offer(id,
maxima.iter().sum::<f64>() as f32),
+ ListScoring::MaxSim => {
+ let score = if aggregate_queries {
+ accumulate_f64_partials(maxima.iter().copied(),
&mut partials);
+ round_f64_partials(&partials)
+ } else {
+ maxima[0]
+ };
+ top_k[0].offer(id, score as f32);
+ }
ListScoring::Independent => {
for &i in &selected {
top_k[i].offer(id, maxima[i] as f32);
diff --git a/crates/paimon/src/table/de_vector_read/tests.rs
b/crates/paimon/src/table/de_vector_read/tests.rs
index 78cb16d8..b1546898 100644
--- a/crates/paimon/src/table/de_vector_read/tests.rs
+++ b/crates/paimon/src/table/de_vector_read/tests.rs
@@ -31,7 +31,7 @@ use crate::table::{find_field_id_by_name, RowRange};
use crate::vector_search::{ScoredRowIds, VectorSearch};
use crate::vindex::pkvector::metric::VectorSearchMetric;
use crate::vindex::IVF_FLAT_IDENTIFIER;
-use arrow_array::builder::{FixedSizeListBuilder, Float32Builder};
+use arrow_array::builder::{FixedSizeListBuilder, Float32Builder, ListBuilder};
use arrow_array::{Array, ArrayRef, Float32Array, Int32Array, Int64Array,
RecordBatch};
use arrow_schema::{DataType as ArrowDataType, Field as ArrowField, Schema as
ArrowSchema};
use futures::TryStreamExt;
@@ -318,29 +318,48 @@ fn test_raw_vector_score_matches_java_metric_semantics() {
#[test]
fn test_raw_vector_score_matrix_matches_scalar_metrics() {
- let stored = vec![1.0, 2.0, 3.0, 4.0, 0.0, 0.0];
- let queries = vec![1.0, 1.0, -1.0, 2.0];
- let query_indices = vec![0, 1];
- let query_l2_squared_norms = vec![2.0, 5.0];
+ let stored = [1.0, 2.0, 3.0, 4.0, 0.0, 0.0];
+ let queries = [[1.0, 1.0], [-1.0, 2.0], [0.0, 0.0]];
+ let query_indices = vec![0, 1, 2];
for metric in [
RawVectorMetric::L2,
RawVectorMetric::Cosine,
RawVectorMetric::InnerProduct,
] {
- let matrix_scores = compute_raw_vector_score_matrix(
- &stored,
- 3,
- &queries,
- 2,
- 2,
- &query_l2_squared_norms,
- &query_indices,
- metric,
- )
+ let matrix_scores = if metric == RawVectorMetric::Cosine {
+ let stored = stored.map(f64::from);
+ let queries = queries.map(|query| query.map(f64::from));
+ let stored_norms: Vec<_> = stored
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|row| DenseCosineNorm::new(row))
+ .collect();
+ let query_norms = queries.map(|query| cosine_norm(&query));
+ compute_raw_cosine_score_matrix(
+ &stored,
+ &stored_norms,
+ queries.as_flattened(),
+ &query_norms,
+ &query_indices,
+ 2,
+ )
+ } else {
+ compute_raw_vector_score_matrix(
+ &stored,
+ 3,
+ queries.as_flattened(),
+ 3,
+ 2,
+ &RawVectorNorms::new(queries.iter().map(<[_; 2]>::as_slice),
metric),
+ &query_indices,
+ metric,
+ )
+ }
.unwrap();
for (row_index, stored_vector) in
stored.as_chunks::<2>().0.iter().enumerate() {
- for (query_index, query) in
queries.as_chunks::<2>().0.iter().enumerate() {
+ for (query_index, query) in queries.iter().enumerate() {
let expected = compute_raw_vector_score(query, stored_vector,
metric);
let actual = matrix_scores[query_index * 3 + row_index];
assert!(
@@ -357,7 +376,7 @@ fn test_raw_vector_score_matrix_matches_scalar_metrics() {
&[1.0, 0.0],
1,
2,
- &[1.0],
+ &RawVectorNorms::new(std::iter::once(&[1.0, 0.0][..]),
RawVectorMetric::L2),
&[0],
RawVectorMetric::L2,
)
@@ -365,6 +384,142 @@ fn test_raw_vector_score_matrix_matches_scalar_metrics() {
assert_eq!(non_finite_score, 0.0);
}
+#[test]
+fn test_raw_cosine_matrix_refines_mixed_sign_rounding_bounds() {
+ let dimension = 256;
+ let epsilon = 2.0_f32.powi(-22);
+ let mut query = vec![epsilon; dimension];
+ query[..128].fill(1.0);
+ query[0] = 2.0;
+ let mut other_query = query.clone();
+ other_query[0] = 3.0;
+ let mut row = vec![epsilon; dimension];
+ row[128..192].fill(1.0);
+ row[192..].fill(-1.0);
+ let mut other_row = row.clone();
+ other_row[0] = -epsilon;
+ let queries = [&query, &other_query];
+ let query_norms = queries.map(|query| cosine_norm(query));
+ let norm_product = query_norms[0] * cosine_norm(&row);
+ let dot = 129.0 * f64::from(epsilon);
+ assert!(CosineOutput::Similarity
+ .try_round_from_dot(
+ CosineDot::Approximate {
+ value: dot,
+ absolute_sum_bound: norm_product,
+ },
+ norm_product,
+ dimension,
+ )
+ .is_err());
+ assert_eq!(
+ CosineOutput::Similarity.try_round_from_dot(
+ CosineDot::Approximate {
+ value: dot,
+ absolute_sum_bound: 257.0 * f64::from(epsilon),
+ },
+ norm_product,
+ dimension,
+ ),
+ Ok(cosine_similarity(&query, query_norms[0], &row))
+ );
+
+ // Exercise pairwise refinement, batched refinement, and partial blocks
+ // in both result dimensions.
+ let block_edge = RAW_COSINE_ABSOLUTE_BLOCK_VECTORS + 1;
+ for (query_count, row_count) in [(4, 2), (4, 32), (4, block_edge),
(block_edge, 32)] {
+ let query_indices: Vec<_> = [1,
0].into_iter().cycle().take(query_count).collect();
+ let query_matrix: Vec<_> = query_indices
+ .iter()
+ .flat_map(|&index| queries[index].iter().copied().map(f64::from))
+ .collect();
+ let rows: Vec<_> = [&row, &other_row]
+ .into_iter()
+ .cycle()
+ .take(row_count)
+ .collect();
+ let stored: Vec<_> = rows
+ .iter()
+ .flat_map(|row| row.iter().copied().map(f64::from))
+ .collect();
+ let stored_norms: Vec<_> = stored
+ .chunks_exact(dimension)
+ .map(DenseCosineNorm::new)
+ .collect();
+ let scores = compute_raw_cosine_score_matrix(
+ &stored,
+ &stored_norms,
+ &query_matrix,
+ &query_norms,
+ &query_indices,
+ dimension,
+ )
+ .unwrap();
+ for (&query_index, scores) in
query_indices.iter().zip(scores.chunks_exact(row_count)) {
+ for (row, &score) in rows.iter().zip(scores) {
+ assert_eq!(
+ score,
+ cosine_similarity(queries[query_index],
query_norms[query_index], row)
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn test_raw_cosine_matrix_certifies_orthogonal_integer_dots() {
+ let dimension = 256;
+ let hadamard = |row: usize| {
+ (0..dimension).map(move |column| {
+ if (row & column).count_ones().is_multiple_of(2) {
+ 1.0
+ } else {
+ -1.0
+ }
+ })
+ };
+ for (query_scale, stored_scale) in [
+ (1.0, 1.0),
+ (1.0 / 16.0, 1.0 / 16.0),
+ (1.0 / 16.0, 1.0 / 32.0),
+ ] {
+ let queries: Vec<_> = (0..4).flat_map(hadamard).map(|v| v *
query_scale).collect();
+ let stored: Vec<_> = (4..20)
+ .flat_map(hadamard)
+ .map(|v| v * stored_scale)
+ .collect();
+ let stored_norms: Vec<_> = stored
+ .chunks_exact(dimension)
+ .map(DenseCosineNorm::new)
+ .collect();
+ let query_norms = queries
+ .chunks_exact(dimension)
+ .map(cosine_norm)
+ .collect::<Vec<_>>();
+ assert!(integer_dot_is_exact(
+ scaled_integer_max(&queries),
+ scaled_integer_max(&stored),
+ dimension
+ ));
+ let scores = compute_raw_cosine_score_matrix(
+ &stored,
+ &stored_norms,
+ &queries,
+ &query_norms,
+ &[0, 1, 2, 3],
+ dimension,
+ )
+ .unwrap();
+ assert_eq!(scores, vec![0.0; 4 * 16]);
+ }
+ let large = 2.0_f64.powi(26);
+ assert!(!integer_dot_is_exact(Some(large), Some(large), dimension));
+ assert_eq!(scaled_integer_max(&[1.0, 0.25]), Some(4.0));
+ assert_eq!(scaled_integer_max(&[-0.375, 0.25, -0.0]), Some(3.0));
+ assert_eq!(scaled_integer_max(&[2.0_f64.powi(53), 1.0]), None);
+ assert_eq!(scaled_integer_max(&[1.0, f64::INFINITY]), None);
+}
+
#[test]
fn test_raw_vector_score_matrix_l2_preserves_large_finite_distances() {
let dimension = 128;
@@ -374,8 +529,6 @@ fn
test_raw_vector_score_matrix_l2_preserves_large_finite_distances() {
let mut stored = query.clone();
stored.extend_from_slice(&nearby);
let queries = query.repeat(4);
- let query_l2_squared_norm = query.iter().map(|value| value *
value).sum::<f32>();
- let query_l2_squared_norms = vec![query_l2_squared_norm; 4];
let query_indices = vec![0, 1, 2, 3];
let matrix_scores = compute_raw_vector_score_matrix(
@@ -384,7 +537,7 @@ fn
test_raw_vector_score_matrix_l2_preserves_large_finite_distances() {
&queries,
4,
dimension,
- &query_l2_squared_norms,
+ &RawVectorNorms::new(queries.chunks_exact(dimension),
RawVectorMetric::L2),
&query_indices,
RawVectorMetric::L2,
)
@@ -401,13 +554,12 @@ fn
test_raw_vector_score_matrix_l2_preserves_large_finite_distances() {
#[test]
fn test_raw_vector_cosine_avoids_squared_norm_product_overflow() {
- let query = vec![1.0e15_f32, 0.0];
- let query_l2_squared_norm = query.iter().map(|value| value *
value).sum::<f32>();
- assert!(query_l2_squared_norm.is_finite());
- let values = Float32Array::from(query.clone());
+ let query = [1.0e15_f32, 0.0];
+ let query_norm = cosine_norm(&query);
+ let values = Float32Array::from(query.to_vec());
let scalar_score = compute_raw_vector_score_from_values(
&query,
- query_l2_squared_norm,
+ Some(query_norm),
&values,
0,
2,
@@ -415,16 +567,15 @@ fn
test_raw_vector_cosine_avoids_squared_norm_product_overflow() {
);
assert!((scalar_score - 1.0).abs() < 1e-6);
+ let query = query.map(f64::from);
let queries = query.repeat(4);
- let matrix_scores = compute_raw_vector_score_matrix(
+ let matrix_scores = compute_raw_cosine_score_matrix(
&query,
- 1,
+ &[DenseCosineNorm::new(&query)],
&queries,
- 4,
- 2,
- &[query_l2_squared_norm; 4],
+ &[query_norm; 4],
&[0, 1, 2, 3],
- RawVectorMetric::Cosine,
+ 2,
)
.unwrap();
assert!(matrix_scores
@@ -432,6 +583,256 @@ fn
test_raw_vector_cosine_avoids_squared_norm_product_overflow() {
.all(|score| (*score - 1.0).abs() < 1e-6));
}
+#[test]
+fn test_raw_cosine_top_k_is_invariant_to_vector_scale() {
+ for scale in [1.0e20_f32, 1.0e-23_f32] {
+ assert_raw_cosine_top_one(
+ &[scale, 0.0],
+ &[&[-scale, 0.0], &[scale, 0.0], &[0.0, scale]],
+ 11,
+ 1.0,
+ );
+ }
+}
+
+#[test]
+fn test_raw_cosine_top_k_orders_near_parallel_with_underflowing_squares() {
+ let scale = 2.0_f32.powi(-63);
+ let mut query = [0.0; 257];
+ query[256] = scale;
+ let mut nearly_parallel = [scale * 2.0_f32.powi(-12); 257];
+ nearly_parallel[256] = scale;
+ assert_raw_cosine_top_one(&query, &[&nearly_parallel, &query], 11, 1.0);
+}
+
+#[test]
+fn test_raw_cosine_top_k_orders_near_orthogonal_with_underflowing_dot() {
+ let similarity = 2.0_f32.powi(-24);
+ for scale in [1.0, 2.0_f32.powi(-63)] {
+ assert_raw_cosine_top_one(
+ &[scale, 0.0],
+ &[&[0.0, scale], &[scale * similarity, scale]],
+ 11,
+ similarity,
+ );
+ }
+}
+
+#[test]
+fn test_raw_cosine_top_k_orders_mixed_scale_candidates() {
+ let query = [3.0, 13.0];
+ let exact = [895.0 * query[0], 895.0 * query[1]];
+ for scale in [1.0, 2.0_f32.powi(64)] {
+ let nearby = [40.0 * scale, 173.0 * scale];
+ assert_raw_cosine_top_one(&query, &[&exact, &nearby], 10, 1.0);
+ }
+}
+
+#[test]
+fn test_raw_cosine_top_k_preserves_same_sign_terms_at_rounding_midpoint() {
+ let large = 2.0_f32.powi(32);
+ let small = 2.0_f32.powi(-12);
+ let tiny = 2.0_f32.powi(-27);
+ let query = [large, 0.0, 1.0, small, tiny, tiny, tiny, tiny];
+ let first = [0.0, large, 1.0, small, 0.0, 0.0, 0.0, 0.0];
+ let second = [0.0, large, 1.0, small, tiny, tiny, tiny, tiny];
+ let expected_score = 2.0_f32.powi(-64).next_up();
+ assert_raw_cosine_top_one(&query, &[&first, &second], 11, expected_score);
+}
+
+#[test]
+fn test_raw_cosine_top_k_preserves_small_norm_terms_in_either_order() {
+ let mut query = [0.0; 66];
+ query[0] = 1.0;
+ let mut nearby = [2.0_f32.powi(-27); 66];
+ nearby[0] = 1.0;
+ nearby[1] = 2.0_f32.powi(-12);
+ for _ in 0..2 {
+ assert_raw_cosine_top_one(&query, &[&nearby, &query], 11, 1.0);
+ query.reverse();
+ nearby.reverse();
+ }
+}
+
+#[test]
+fn test_raw_cosine_top_k_preserves_residual_after_dot_cancellation() {
+ let large = 2.0_f32.powi(64);
+ let small = 2.0_f32.powi(37);
+ let expected_score = 2.0_f32.powi(-55);
+ assert_raw_cosine_top_one(
+ &[large, small, large],
+ &[&[large, 0.0, -large], &[large, small, -large]],
+ 11,
+ expected_score,
+ );
+ assert_raw_cosine_top_one(
+ &[large, large, small],
+ &[&[large, -large, 0.0], &[large, -large, small]],
+ 11,
+ expected_score,
+ );
+}
+
+#[test]
+fn test_raw_cosine_top_k_preserves_residual_across_multiple_scales() {
+ let large = 2.0_f32.powi(64);
+ let medium = 2.0_f32.powi(37);
+ let small = 2.0_f32.powi(8);
+ assert_raw_cosine_top_one(
+ &[large, medium, small, large, medium],
+ &[
+ &[large, medium, 0.0, -large, -medium],
+ &[large, medium, small, -large, -medium],
+ ],
+ 11,
+ 2.0_f32.powi(-113),
+ );
+}
+
+#[test]
+fn test_raw_cosine_top_k_handles_many_product_scales() {
+ let mut query = (0..50)
+ .map(|i| 1.5 * 2.0_f32.powi(i * 17 % 240 - 120))
+ .collect::<Vec<_>>();
+ let mut nearby = (0..50)
+ .map(|i| 1.125 * 2.0_f32.powi(i * 29 % 240 - 120))
+ .collect::<Vec<_>>();
+ let mut orthogonal = vec![0.0; 50];
+ // The disjoint large coordinates make the positive dot product small
+ // relative to the norms. Mixed signs also exercise compensation in DGEMM.
+ query[0] = -query[0];
+ query.extend([f32::MAX, 0.0]);
+ nearby.extend([0.0, f32::MAX]);
+ orthogonal.extend([0.0, f32::MAX]);
+ let dot: f64 = query
+ .iter()
+ .zip(&nearby)
+ .map(|(&q, &s)| f64::from(q) * f64::from(s))
+ .sum();
+ let expected_score = (dot / (cosine_norm(&query) * cosine_norm(&nearby)))
as f32;
+ assert_raw_cosine_top_one(&query, &[&orthogonal, &nearby], 11,
expected_score);
+}
+
+fn assert_raw_cosine_top_one(
+ query: &[f32],
+ stored: &[&[f32]],
+ expected_row_id: u64,
+ expected_score: f32,
+) {
+ let mut builder = FixedSizeListBuilder::new(Float32Builder::new(),
query.len() as i32);
+ for vector in stored {
+ builder.values().append_slice(vector);
+ builder.append(true);
+ }
+ let vectors = builder.finish();
+ let schema = Arc::new(ArrowSchema::new(vec![
+ ArrowField::new("embedding", vectors.data_type().clone(), false),
+ ArrowField::new(ROW_ID_FIELD_NAME, ArrowDataType::Int64, false),
+ ]));
+ let row_ids = Int64Array::from_iter_values(10..10 + stored.len() as i64);
+ let batch = RecordBatch::try_new(schema, vec![Arc::new(vectors),
Arc::new(row_ids)]).unwrap();
+
+ for query_count in [1, RAW_SCORE_MATRIX_MIN_QUERY_COUNT] {
+ let searches = (0..query_count)
+ .map(|_| VectorSearch::new(query.to_vec(), 1,
"embedding".to_string()).unwrap())
+ .collect::<Vec<_>>();
+ let scoring_plan = RawScoringPlan::new(&searches,
RawVectorMetric::Cosine);
+ let mut top_k = (0..query_count)
+ .map(|_| RawScoreTopK::new(1))
+ .collect::<Vec<_>>();
+ collect_raw_batch_vector_batch(
+ &batch,
+ &searches,
+ RawVectorMetric::Cosine,
+ &scoring_plan,
+ &mut top_k,
+ )
+ .unwrap();
+ for result in top_k.into_iter().map(RawScoreTopK::into_search_result) {
+ assert_eq!(
+ result.row_ids,
+ vec![expected_row_id],
+ "query count={query_count}"
+ );
+ assert_eq!(result.scores, vec![expected_score]);
+ }
+ }
+}
+
+fn score_single_embedding_lists(
+ rows: &[[f32; 3]],
+ queries: &[[f32; 3]],
+ mode: ListScoring,
+) -> Vec<ScoredRowIds> {
+ let mut builder =
ListBuilder::new(FixedSizeListBuilder::new(Float32Builder::new(), 3));
+ for row in rows {
+ builder.values().values().append_slice(row);
+ builder.values().append(true);
+ builder.append(true);
+ }
+ let vectors = builder.finish();
+ let schema = Arc::new(ArrowSchema::new(vec![
+ ArrowField::new("embedding", vectors.data_type().clone(), false),
+ ArrowField::new(ROW_ID_FIELD_NAME, ArrowDataType::Int64, false),
+ ]));
+ let row_ids = Int64Array::from_iter_values(10..10 + rows.len() as i64);
+ let batch = RecordBatch::try_new(schema, vec![Arc::new(vectors),
Arc::new(row_ids)]).unwrap();
+ let searches = queries
+ .iter()
+ .map(|query| VectorSearch::new(query.to_vec(), 1,
"embedding".to_string()).unwrap())
+ .collect::<Vec<_>>();
+ let scoring = RawBatchScoring::new(&searches, RawVectorMetric::Cosine,
Some(mode)).unwrap();
+ let mut top_k = (0..mode.result_count(queries.len()))
+ .map(|_| RawScoreTopK::new(1))
+ .collect::<Vec<_>>();
+ scoring
+ .collect(&batch, &searches, RawVectorMetric::Cosine, &mut top_k)
+ .unwrap();
+ top_k
+ .into_iter()
+ .map(RawScoreTopK::into_search_result)
+ .collect()
+}
+
+#[test]
+fn test_list_cosine_top_k_matches_single_vectors_after_dot_cancellation() {
+ let tiny = 2.0_f32.powi(-27);
+ let query = [1.0, tiny, 1.0];
+ let rows = [[1.0, 0.0, -1.0], [1.0, tiny, -1.0]];
+ let expected_score = 2.0_f32.powi(-55);
+ assert_raw_cosine_top_one(&query, &[&rows[0], &rows[1]], 11,
expected_score);
+
+ for (mode, count) in [
+ (ListScoring::Independent, 1),
+ (ListScoring::Independent, RAW_SCORE_MATRIX_MIN_QUERY_COUNT),
+ (ListScoring::MaxSim, 1),
+ ] {
+ let results = score_single_embedding_lists(&rows, &vec![query; count],
mode);
+ assert_eq!(results.len(), count);
+ for result in results {
+ assert_eq!(result.row_ids, [11]);
+ assert_eq!(result.scores, [expected_score]);
+ }
+ }
+}
+
+#[test]
+fn
test_list_cosine_top_k_max_sim_preserves_small_terms_between_opposite_scores() {
+ let tiny = 2.0_f32.powi(-27);
+ let rows = [[1.0, 0.0, -1.0], [1.0, tiny, -1.0]];
+ let positive = [1.0, 0.0, -1.0];
+ let negative = [-1.0, 0.0, 1.0];
+ let orthogonal = [1.0, tiny, 1.0];
+ for queries in [
+ [positive, orthogonal, negative],
+ [negative, orthogonal, positive],
+ ] {
+ let results = score_single_embedding_lists(&rows, &queries,
ListScoring::MaxSim);
+ assert_eq!(results[0].row_ids, [11]);
+ assert_eq!(results[0].scores, [2.0_f32.powi(-55)]);
+ }
+}
+
#[test]
fn test_raw_score_top_k_matches_full_sort_with_linear_partial_selection() {
let limit = 7;
diff --git a/crates/paimon/src/table/hybrid_search_builder.rs
b/crates/paimon/src/table/hybrid_search_builder.rs
index dab23db5..1326f133 100644
--- a/crates/paimon/src/table/hybrid_search_builder.rs
+++ b/crates/paimon/src/table/hybrid_search_builder.rs
@@ -36,12 +36,15 @@ use crate::table::pk_full_text_scan::PrimaryKeyFullTextScan;
use crate::table::pk_search_position::PrimaryKeySearchPosition;
use crate::table::pk_search_ranker::{self, Ranking};
use crate::table::pk_vector_indexed_split_read::{PkVectorIndexedSplit,
PkVectorIndexedSplitRead};
+use crate::table::pk_vector_orchestrator::build_indexed_splits;
use crate::table::source::DataSplit;
use crate::table::vector_search_common::{
- collect_ranked_rows, ensure_no_reserved_read_columns,
reorder_and_strip_position, RankedRow,
+ collect_ranked_rows, ensure_no_reserved_read_columns,
reorder_and_strip_position,
+ take_only_result, RankedRow,
};
use crate::table::{ArrowRecordBatchStream, GlobalIndexResult, RowRange, Table};
use crate::vector_search::ScoredRowIds;
+use crate::vindex::pkvector::metric::VectorSearchMetric;
const RRF_K: f32 = 60.0;
const MAX_ROUTE_WORKERS: usize = 4;
@@ -883,7 +886,7 @@ impl<'a> HybridSearchBuilder<'a> {
.map(|snapshot|
self.table.copy_with_pinned_snapshot(Some(&snapshot))))
}
- /// Consume the vector search's scored positions, retaining its source
files
+ /// Consume the raw vector candidates, retaining their source files
/// and pinned snapshot for fusion before materialization.
async fn pk_vector_route(
&self,
@@ -891,18 +894,34 @@ impl<'a> HybridSearchBuilder<'a> {
route: &HybridSearchRoute,
) -> crate::Result<PkRoute> {
let builder = self.vector_route_builder(table, route);
- let result = builder.execute().await?;
- let positions = result
- .positions()?
+ let (scan, read) = builder.new_scan_and_read()?;
+ let result = read.search_primary_key(scan.plan().await?).await?;
+ let candidates = take_only_result(result.candidates, "vector search")?;
+ let cosine_distance_scores = result.metric ==
VectorSearchMetric::Cosine;
+ let positions = candidates
.iter()
- .map(PrimaryKeySearchPosition::from_vector_position)
+ .map(|candidate| {
+ // Negation preserves distance order and ties for RRF and MRR.
+ // Min-max normalization also works on -distance because it
+ // cancels the constant in the public cosine score 1 -
distance.
+ let score = if cosine_distance_scores {
+ -candidate.distance
+ } else {
+ result.metric.distance_to_score(candidate.distance)
+ };
+ PrimaryKeySearchPosition::from_vector_candidate(candidate,
score)
+ })
.collect::<crate::Result<Vec<_>>>()?;
- let source_splits = result.splits()?.to_vec();
+ let source_splits = build_indexed_splits(candidates,
&result.source_splits, result.metric)?
+ .into_iter()
+ .map(|split| split.split)
+ .collect();
Ok(PkRoute {
positions,
source_splits,
- snapshot_id: result.snapshot_id().unwrap_or(0),
+ snapshot_id: result.snapshot_id,
weight: route.weight as f64,
+ cosine_distance_scores,
})
}
@@ -1010,6 +1029,7 @@ impl<'a> HybridSearchBuilder<'a> {
source_splits,
snapshot_id: result.snapshot_id,
weight: route.weight as f64,
+ cosine_distance_scores: false,
})
}
@@ -1024,7 +1044,10 @@ impl<'a> HybridSearchBuilder<'a> {
let mut rankings = Vec::with_capacity(routes.len());
for route in routes {
if !route.positions.is_empty() {
- rankings.push(Ranking::new(route.positions.clone(),
route.weight)?);
+ rankings.push(
+ Ranking::new(route.positions.clone(), route.weight)?
+
.with_cosine_distance_scores(route.cosine_distance_scores),
+ );
}
}
match self.ranker {
@@ -1043,6 +1066,7 @@ struct PkRoute {
source_splits: Vec<DataSplit>,
snapshot_id: i64,
weight: f64,
+ cosine_distance_scores: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -1675,6 +1699,7 @@ mod pk_hybrid_tests {
location: &str,
file_name: &str,
vectors: &[[f32; DIM]],
+ metric: &str,
) -> u64 {
let n = vectors.len();
let flat: Vec<f32> = vectors.iter().flat_map(|v|
v.iter().copied()).collect();
@@ -1683,7 +1708,7 @@ mod pk_hybrid_tests {
("index.type".to_string(), "ivf_flat".to_string()),
("dimension".to_string(), DIM.to_string()),
("nlist".to_string(), "1".to_string()),
- ("metric".to_string(), "l2".to_string()),
+ ("metric".to_string(), metric.to_string()),
]);
let config = VectorIndexConfig::from_options(&native_options).unwrap();
let training = VectorIndexTrainer::train(config, &flat, n).unwrap();
@@ -1790,8 +1815,10 @@ mod pk_hybrid_tests {
// Vector ANN segment.
let vector_index_name = "vector-ivf-flat-pk-hybrid.index".to_string();
+ let metric =
+
&schema.options()[&format!("fields.{VECTOR_COLUMN}.pk-vector.distance.metric")];
let vector_index_size =
- write_ann_segment(&file_io, location, &vector_index_name,
vectors).await;
+ write_ann_segment(&file_io, location, &vector_index_name, vectors,
metric).await;
let vector_index = IndexFileMeta {
index_type: VECTOR_INDEX_TYPE.to_string(),
file_name: vector_index_name,
@@ -1971,6 +1998,169 @@ mod pk_hybrid_tests {
);
}
+ #[tokio::test]
+ async fn pk_hybrid_preserves_cosine_distance_order_after_reranking() {
+ let query = [3.0, 4.0, 0.0, 0.0];
+ let table = build_hybrid_table(
+ "memory:/pk_hybrid_cosine_order",
+ &[0, 1, 2],
+ &[[3.0015, 4.0, 0.0, 0.0], query, [4.0, -3.0, 0.0, 0.0]],
+ &["nearby", "exact", "orthogonal"],
+ &[("fields.embedding.pk-vector.distance.metric", "cosine")],
+ )
+ .await;
+
+ for (ranker, include_text) in [
+ (HybridSearchRanker::Rrf, false),
+ (HybridSearchRanker::Mrr, false),
+ (HybridSearchRanker::WeightedScore, false),
+ (HybridSearchRanker::WeightedScore, true),
+ ] {
+ for route_limit in [1, 2, 3] {
+ let mut builder = table.new_hybrid_search_builder();
+ builder
+ .add_vector_route(
+ VECTOR_COLUMN,
+ query.to_vec(),
+ route_limit,
+ 1.0,
+ HashMap::from([(
+ "fields.embedding.ivf.refine-factor".to_string(),
+ "2".to_string(),
+ )]),
+ )
+ .unwrap();
+ if include_text {
+ builder
+ .add_full_text_route(
+ TEXT_COLUMN,
+ r#"{"match":{"query":"orthogonal"}}"#,
+ 1,
+ 0.5,
+ HashMap::new(),
+ )
+ .unwrap();
+ }
+ builder.with_limit(1).with_ranker(ranker.as_str()).unwrap();
+ let batches = builder
+ .execute_read()
+ .await
+ .unwrap()
+ .try_collect::<Vec<_>>()
+ .await
+ .unwrap();
+ assert_eq!(
+ column_i32(&batches, "id"),
+ vec![1],
+ "{ranker:?}, limit={route_limit}, full text={include_text}"
+ );
+ let expected_score = if ranker == HybridSearchRanker::Rrf {
+ (1.0 / (f64::from(pk_search_ranker::DEFAULT_RRF_K) + 1.0))
as f32
+ } else {
+ 1.0
+ };
+ assert_eq!(
+ column_f32(&batches, SEARCH_SCORE_COLUMN),
+ vec![expected_score]
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn
pk_hybrid_weighted_cosine_breaks_equal_totals_by_position_in_either_route_order()
{
+ let a = [1.0, 0.0, 0.0, 0.0];
+ let b = [0.0, 1.0, 0.0, 0.0];
+ let middle = [1.0, 1.0, 0.0, 0.0];
+ let table = build_hybrid_table(
+ "memory:/pk_hybrid_weighted_cosine_route_order",
+ &[0, 1, 2],
+ &[a, b, [-1.0, -1.0, 15.0, 0.0]],
+ &["alpha", "beta", "gamma"],
+ &[("fields.embedding.pk-vector.distance.metric", "cosine")],
+ )
+ .await;
+
+ let mut scores = Vec::new();
+ for queries in [[a, middle, b], [b, middle, a]] {
+ let mut builder = table.new_hybrid_search_builder();
+ for query in queries {
+ builder
+ .add_vector_route(
+ VECTOR_COLUMN,
+ query.to_vec(),
+ 3,
+ 1.0,
+
HashMap::from([("fields.embedding.ivf.refine-factor".into(), "2".into())]),
+ )
+ .unwrap();
+ }
+ builder.with_limit(1).with_weighted_score_ranker();
+ let batches = builder
+ .execute_read()
+ .await
+ .unwrap()
+ .try_collect::<Vec<_>>()
+ .await
+ .unwrap();
+ assert_eq!(column_i32(&batches, "id"), [0], "queries={queries:?}");
+ scores.push(column_f32(&batches, SEARCH_SCORE_COLUMN));
+ }
+ assert_eq!(scores[0], scores[1]);
+ }
+
+ #[tokio::test]
+ async fn
pk_hybrid_weighted_cosine_preserves_tiny_distance_with_a_full_text_route() {
+ let query = [1.0, 0.0, 0.0, 0.0];
+ let table = build_hybrid_table(
+ "memory:/pk_hybrid_weighted_cosine_tiny_distance",
+ &[0, 1, 2],
+ &[
+ [1.0, 2.0_f32.powi(-30), 0.0, 0.0],
+ query,
+ [0.0, 1.0, 0.0, 0.0],
+ ],
+ &["nearby", "exact", "orthogonal"],
+ &[("fields.embedding.pk-vector.distance.metric", "cosine")],
+ )
+ .await;
+ let mut builder = table.new_hybrid_search_builder();
+ builder
+ .add_vector_route(
+ VECTOR_COLUMN,
+ query.to_vec(),
+ 3,
+ 1.0,
+ HashMap::from([("fields.embedding.ivf.refine-factor".into(),
"2".into())]),
+ )
+ .unwrap()
+ .with_limit(1)
+ .with_weighted_score_ranker();
+
+ for include_text in [false, true] {
+ if include_text {
+ builder
+ .add_full_text_route(
+ TEXT_COLUMN,
+ r#"{"match":{"query":"orthogonal"}}"#,
+ 1,
+ 0.5,
+ HashMap::new(),
+ )
+ .unwrap();
+ }
+ let batches = builder
+ .execute_read()
+ .await
+ .unwrap()
+ .try_collect::<Vec<_>>()
+ .await
+ .unwrap();
+ assert_eq!(column_i32(&batches, "id"), [1], "full
text={include_text}");
+ assert_eq!(column_f32(&batches, SEARCH_SCORE_COLUMN), [1.0]);
+ }
+ }
+
#[tokio::test]
async fn
pk_hybrid_weighted_score_uses_vector_scores_and_reads_in_fused_order() {
let table = build_hybrid_table(
diff --git a/crates/paimon/src/table/pk_search_position.rs
b/crates/paimon/src/table/pk_search_position.rs
index de521830..525c63ed 100644
--- a/crates/paimon/src/table/pk_search_position.rs
+++ b/crates/paimon/src/table/pk_search_position.rs
@@ -111,15 +111,16 @@ impl PrimaryKeySearchPosition {
)
}
- pub(crate) fn from_vector_position(
- position: &crate::vector_search::PrimaryKeySearchPosition,
+ pub(crate) fn from_vector_candidate(
+ candidate: &super::pk_vector_orchestrator::PkVectorCandidate,
+ score: f32,
) -> crate::Result<Self> {
Self::new(
- position.partition.clone(),
- position.bucket,
- position.data_file_name.clone(),
- position.row_position,
- position.score,
+ candidate.partition.clone(),
+ candidate.bucket,
+ candidate.data_file_name.clone(),
+ candidate.row_position,
+ score,
)
}
@@ -209,31 +210,25 @@ mod tests {
assert_eq!(set.len(), 2);
}
- fn vector_position(score: f32) ->
crate::vector_search::PrimaryKeySearchPosition {
- crate::vector_search::PrimaryKeySearchPosition {
+ #[test]
+ fn from_vector_candidate_uses_supplied_score_and_validates_position() {
+ let mut hit = super::super::pk_vector_orchestrator::PkVectorCandidate {
+ split_index: 0,
partition: BinaryRow::new(0),
bucket: 0,
data_file_name: "f".to_string(),
row_position: 0,
- score,
- }
- }
-
- #[test]
- fn from_vector_position_preserves_score_and_validates_position() {
- // GlobalIndexResult already converted distance to score; fusion must
preserve it.
- let mut hit = vector_position(0.5);
- let position =
PrimaryKeySearchPosition::from_vector_position(&hit).unwrap();
- assert_eq!(position.score(), 0.5);
+ distance: 0.25,
+ };
+ let position = PrimaryKeySearchPosition::from_vector_candidate(&hit,
-0.25).unwrap();
+ assert_eq!(position.score(), -0.25);
assert_eq!(position.row_position(), 0);
assert_eq!(position.data_file_name(), "f");
for score in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
- hit.score = score;
-
assert!(PrimaryKeySearchPosition::from_vector_position(&hit).is_err());
+ assert!(PrimaryKeySearchPosition::from_vector_candidate(&hit,
score).is_err());
}
- hit.score = 0.5;
hit.row_position = -1;
- assert!(PrimaryKeySearchPosition::from_vector_position(&hit).is_err());
+ assert!(PrimaryKeySearchPosition::from_vector_candidate(&hit,
-0.25).is_err());
}
#[test]
diff --git a/crates/paimon/src/table/pk_search_ranker.rs
b/crates/paimon/src/table/pk_search_ranker.rs
index 68bad568..23fc0122 100644
--- a/crates/paimon/src/table/pk_search_ranker.rs
+++ b/crates/paimon/src/table/pk_search_ranker.rs
@@ -31,6 +31,9 @@
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
+use num_rational::BigRational;
+use num_traits::ToPrimitive;
+
use crate::table::hybrid_search_builder::normalize_route_score;
use crate::table::pk_search_position::PrimaryKeySearchPosition;
@@ -51,6 +54,7 @@ fn data_invalid(message: impl Into<String>) -> crate::Error {
pub(crate) struct Ranking {
positions: Vec<PrimaryKeySearchPosition>,
weight: f64,
+ cosine_distance_scores: bool,
}
impl Ranking {
@@ -65,7 +69,16 @@ impl Ranking {
"Search route weight must be finite and positive: {weight}."
)));
}
- Ok(Self { positions, weight })
+ Ok(Self {
+ positions,
+ weight,
+ cosine_distance_scores: false,
+ })
+ }
+
+ pub(crate) fn with_cosine_distance_scores(mut self,
cosine_distance_scores: bool) -> Self {
+ self.cosine_distance_scores = cosine_distance_scores;
+ self
}
pub(crate) fn positions(&self) -> &[PrimaryKeySearchPosition] {
@@ -149,36 +162,123 @@ pub(crate) fn weighted_rrf(
top_k(fused_scores, limit)
}
-/// Fuses heterogeneous route scores after independently normalizing each route
-/// to `[0, 1]`. Mirrors Java `weightedScore`.
+/// Fuses heterogeneous route scores by normalizing each route to `[0, 1]`
+/// as in Java `weightedScore`. Cosine routes retain precision through
+/// normalization and fused ordering. A single cosine route keeps its
+/// distance order, including when normalized scores round to a tie.
pub(crate) fn weighted_score(
rankings: &[Ranking],
limit: usize,
) -> crate::Result<Vec<PrimaryKeySearchPosition>> {
check_limit(limit, "Weighted-score result limit")?;
+ let has_cosine = rankings
+ .iter()
+ .any(|ranking| ranking.cosine_distance_scores);
+ if has_cosine && rankings.len() > 1 {
+ return weighted_score_with_cosine(rankings, limit);
+ }
+
let mut fused_scores: HashMap<PrimaryKeySearchPosition, f64> =
HashMap::new();
for ranking in rankings {
- let mut unique: HashSet<PrimaryKeySearchPosition> = HashSet::new();
- let mut min = f32::INFINITY;
- let mut max = f32::NEG_INFINITY;
- for position in ranking.positions() {
- if !unique.insert(position.clone()) {
- return Err(data_invalid(format!(
- "One weighted-score ranking contains duplicate physical
position {}.",
- describe(position)
- )));
- }
- min = min.min(position.score());
- max = max.max(position.score());
- }
+ let (min, max) = score_bounds(ranking)?;
for position in ranking.positions() {
- let normalized = f64::from(normalize_route_score(position.score(),
min, max));
+ let normalized = if ranking.cosine_distance_scores && max > min {
+ (f64::from(position.score()) - f64::from(min)) /
(f64::from(max) - f64::from(min))
+ } else {
+ f64::from(normalize_route_score(position.score(), min, max))
+ };
*fused_scores.entry(position.clone()).or_insert(0.0) +=
ranking.weight() * normalized;
}
}
+ if has_cosine {
+ // The normalized score is monotone within one cosine route. Order
+ // directly by its original score so rounding cannot introduce ties.
+ let mut ranked = fused_scores
+ .into_iter()
+ .map(|(position, score)| Ok((position.with_score(score as f32)?,
position.score())))
+ .collect::<crate::Result<Vec<_>>>()?;
+ ranked.sort_by(|(left, left_order), (right, right_order)| {
+ right_order
+ .total_cmp(left_order)
+ .then_with(|| compare_to(left, right))
+ });
+ ranked.truncate(limit);
+ return Ok(ranked.into_iter().map(|(position, _)| position).collect());
+ }
top_k(fused_scores, limit)
}
+fn score_bounds(ranking: &Ranking) -> crate::Result<(f32, f32)> {
+ let mut unique = HashSet::new();
+ let mut min = f32::INFINITY;
+ let mut max = f32::NEG_INFINITY;
+ for position in ranking.positions() {
+ if !unique.insert(position) {
+ return Err(data_invalid(format!(
+ "One weighted-score ranking contains duplicate physical
position {}.",
+ describe(position)
+ )));
+ }
+ min = min.min(position.score());
+ max = max.max(position.score());
+ }
+ Ok((min, max))
+}
+
+fn weighted_score_with_cosine(
+ rankings: &[Ranking],
+ limit: usize,
+) -> crate::Result<Vec<PrimaryKeySearchPosition>> {
+ let mut fused_scores: HashMap<PrimaryKeySearchPosition, BigRational> =
HashMap::new();
+ for ranking in rankings {
+ let (min, max) = score_bounds(ranking)?;
+ let cosine_scale = (ranking.cosine_distance_scores && max >
min).then(|| {
+ // Min-max normalization is a ratio of finite binary floats. Keep
+ // it exact so tiny distances survive normalization near one and
+ // the sum of route contributions is independent of route order.
+ let min = BigRational::from_float(min).expect("finite route
score");
+ let max = BigRational::from_float(max).expect("finite route
score");
+ let weight =
BigRational::from_float(ranking.weight()).expect("finite route weight");
+ let scale = weight / (max - &min);
+ (min, scale)
+ });
+ for position in ranking.positions() {
+ let contribution = match &cosine_scale {
+ Some((min, scale)) => {
+ (BigRational::from_float(position.score()).expect("finite
route score") - min)
+ * scale
+ }
+ None => {
+ let normalized = normalize_route_score(position.score(),
min, max);
+ BigRational::from_float(ranking.weight() *
f64::from(normalized))
+ .expect("finite weighted route score")
+ }
+ };
+ *fused_scores.entry(position.clone()).or_default() += contribution;
+ }
+ }
+ let mut ranked = fused_scores
+ .into_iter()
+ .map(|(position, exact_score)| {
+ let score = exact_score.to_f64().expect("valid ratio");
+ Ok((position.with_score(score as f32)?, score, exact_score))
+ })
+ .collect::<crate::Result<Vec<_>>>()?;
+ ranked.sort_unstable_by(
+ |(left, left_score, left_exact), (right, right_score, right_exact)| {
+ right_score
+ .total_cmp(left_score)
+ .then_with(|| right_exact.cmp(left_exact))
+ .then_with(|| compare_to(left, right))
+ },
+ );
+ ranked.truncate(limit);
+ Ok(ranked
+ .into_iter()
+ .map(|(position, _, _)| position)
+ .collect())
+}
+
/// Fuses routes using weighted reciprocal rank without the RRF smoothing
/// constant. Mirrors Java `weightedMrr`.
pub(crate) fn weighted_mrr(
@@ -377,6 +477,21 @@ mod tests {
assert_eq!(ranked[1].score(), 2.0);
}
+ #[test]
+ fn weighted_score_uses_physical_ties_for_non_cosine_routes() {
+ let route = ranking(
+ vec![
+ position("file", 0, 1.0_f32.next_down()),
+ position("file", 1, 1.0),
+ position("file", 2, -1.0),
+ ],
+ 1.0,
+ );
+ let fused = weighted_score(&[route], 1).unwrap();
+ assert_eq!(fused[0].row_position(), 0);
+ assert_eq!(fused[0].score(), 1.0);
+ }
+
#[test]
fn rrf_k_matches_java_value() {
assert_eq!(DEFAULT_RRF_K, 60);
diff --git a/crates/paimon/src/table/pk_vector_data_file_reader.rs
b/crates/paimon/src/table/pk_vector_data_file_reader.rs
index 4af8d833..e0f26c4a 100644
--- a/crates/paimon/src/table/pk_vector_data_file_reader.rs
+++ b/crates/paimon/src/table/pk_vector_data_file_reader.rs
@@ -123,6 +123,10 @@ impl DataFilePkVectorReaderFactory {
for query in queries {
validate_query(query, self.dimension)?;
}
+ let prepared_queries: Vec<_> = queries
+ .iter()
+ .map(|query| metric.prepare_query(query))
+ .collect();
let file_meta = self
.data_split
@@ -201,11 +205,11 @@ impl DataFilePkVectorReaderFactory {
if is_excluded(pos) {
continue;
}
- for (query, heap) in queries.iter().zip(heaps.iter_mut()) {
+ for (query, heap) in
prepared_queries.iter().zip(heaps.iter_mut()) {
let candidate = PkVectorSearchResult {
data_file_name: file.file_name.clone(),
row_position: pos,
- distance: metric.compute_distance(query, vector),
+ distance: query.compute_distance(vector),
};
push_bounded(heap, candidate, exact_limit);
}
diff --git a/crates/paimon/src/table/pk_vector_read.rs
b/crates/paimon/src/table/pk_vector_read.rs
index 16d76871..13891c51 100644
--- a/crates/paimon/src/table/pk_vector_read.rs
+++ b/crates/paimon/src/table/pk_vector_read.rs
@@ -54,6 +54,13 @@ use futures::{stream, TryStreamExt};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
+pub(super) struct PkVectorSearchBatch {
+ pub(super) candidates: Vec<Vec<PkVectorCandidate>>,
+ pub(super) source_splits: Vec<PkVectorSearchSplit>,
+ pub(super) snapshot_id: i64,
+ pub(super) metric: VectorSearchMetric,
+}
+
pub(super) struct PkVectorRead {
table: Table,
options: HashMap<String, String>,
@@ -82,12 +89,12 @@ impl PkVectorRead {
limit,
}
}
-}
-
-impl Read for PkVectorRead {
- type Plan = PkVectorScanPlan;
- async fn read(&self, plan: PkVectorScanPlan) ->
crate::Result<Vec<GlobalIndexResult>> {
+ /// Search the pinned plan with distances and file references intact.
+ pub(super) async fn search(
+ &self,
+ plan: PkVectorScanPlan,
+ ) -> crate::Result<PkVectorSearchBatch> {
let core = CoreOptions::new(self.table.schema().options());
let queries: Vec<&[f32]> =
self.queries.iter().map(Vec::as_slice).collect();
let mut metadata_type = None;
@@ -147,16 +154,31 @@ impl Read for PkVectorRead {
¶ms,
)
.await?;
+ Ok(PkVectorSearchBatch {
+ candidates,
+ source_splits: plan.splits,
+ snapshot_id: plan.snapshot_id,
+ metric: params.metric,
+ })
+ }
+}
+
+impl Read for PkVectorRead {
+ type Plan = PkVectorScanPlan;
+
+ async fn read(&self, plan: PkVectorScanPlan) ->
crate::Result<Vec<GlobalIndexResult>> {
+ let result = self.search(plan).await?;
let table = Arc::new(self.table.clone());
- candidates
+ result
+ .candidates
.into_iter()
.map(|candidates| {
GlobalIndexResult::from_primary_key(
table.clone(),
- plan.snapshot_id,
+ result.snapshot_id,
candidates,
- &plan.splits,
- params.metric,
+ &result.source_splits,
+ result.metric,
)
})
.collect()
@@ -855,6 +877,7 @@ async fn rerank_indexed_positional(
let indexed_splits = build_indexed_splits(indexed, plan_splits, metric)?;
let dimension = query_vector.len();
+ let prepared_query = metric.prepare_query(query_vector);
let mut reranked: Vec<PkVectorCandidate> = Vec::new();
for split in indexed_splits {
let data_split = split.split.clone();
@@ -918,7 +941,7 @@ async fn rerank_indexed_positional(
),
source: None,
})?;
- candidate.distance = metric.compute_distance(query_vector,
vector);
+ candidate.distance = prepared_query.compute_distance(vector);
reranked.push(candidate);
}
}
diff --git a/crates/paimon/src/table/vector_read.rs
b/crates/paimon/src/table/vector_read.rs
index 42e1aac1..0135e32e 100644
--- a/crates/paimon/src/table/vector_read.rs
+++ b/crates/paimon/src/table/vector_read.rs
@@ -19,7 +19,8 @@
use crate::spec::{CoreOptions, Predicate};
use crate::table::de_vector_read::DeVectorRead;
-use crate::table::pk_vector_read::PkVectorRead;
+use crate::table::pk_vector_read::{PkVectorRead, PkVectorSearchBatch};
+use crate::table::pk_vector_scan::{plan_from_search_splits, PkVectorScanPlan};
use crate::table::pk_vector_search_params::PkVectorSearchParams;
use crate::table::vector_scan::{PlanContext, VectorScanPlan};
use crate::table::vector_search_common::{take_only_result,
targets_primary_key_column};
@@ -61,6 +62,21 @@ impl VectorRead {
"vector search",
)
}
+
+ pub(super) async fn search_primary_key(
+ &self,
+ plan: VectorScanPlan,
+ ) -> crate::Result<PkVectorSearchBatch> {
+ let table = self.batch.table_for_plan(&plan)?;
+ let VectorReadKind::PrimaryKey(reader) = &self.batch.reader else {
+ return Err(crate::Error::Unsupported {
+ message: "Primary-key vector search requires a primary-key
vector reader".into(),
+ });
+ };
+ reader
+ .search(self.batch.primary_key_plan(&table, &plan)?)
+ .await
+ }
}
/// Searches a common plan with multiple queries, preserving input order and
arity.
@@ -131,11 +147,7 @@ impl BatchVectorRead {
) -> crate::Result<Vec<GlobalIndexResult>> {
self.read_impl(plan, Some(executor)).await
}
- async fn read_impl(
- &self,
- plan: VectorScanPlan,
- executor: Option<&dyn SearchTaskExecutor>,
- ) -> crate::Result<Vec<GlobalIndexResult>> {
+ fn table_for_plan(&self, plan: &VectorScanPlan) -> crate::Result<Table> {
CoreOptions::new(self.table.schema().options()).ensure_read_authorized()?;
if let Some(snapshot) = &self.context.prepared_snapshot {
if snapshot.as_ref() != plan.snapshot() {
@@ -147,7 +159,29 @@ impl BatchVectorRead {
});
}
}
- let table = self.table.copy_with_pinned_snapshot(plan.snapshot());
+ Ok(self.table.copy_with_pinned_snapshot(plan.snapshot()))
+ }
+
+ fn primary_key_plan(
+ &self,
+ table: &Table,
+ plan: &VectorScanPlan,
+ ) -> crate::Result<PkVectorScanPlan> {
+ plan_from_search_splits(
+ table,
+ &self.context.column,
+ self.context.filter.as_ref(),
+ plan.snapshot().cloned(),
+ plan.splits(),
+ )
+ }
+
+ async fn read_impl(
+ &self,
+ plan: VectorScanPlan,
+ executor: Option<&dyn SearchTaskExecutor>,
+ ) -> crate::Result<Vec<GlobalIndexResult>> {
+ let table = self.table_for_plan(&plan)?;
match &self.reader {
VectorReadKind::DataEvolution(reader) => {
for source in plan.splits() {
@@ -194,15 +228,7 @@ impl BatchVectorRead {
message: "Distributed primary-key vector search is not
supported".into(),
});
}
- reader
- .read(super::pk_vector_scan::plan_from_search_splits(
- &table,
- &self.context.column,
- self.context.filter.as_ref(),
- plan.snapshot().cloned(),
- plan.splits(),
- )?)
- .await
+ reader.read(self.primary_key_plan(&table, &plan)?).await
}
}
}
diff --git a/crates/paimon/src/vindex/multi_vector.rs
b/crates/paimon/src/vindex/multi_vector.rs
index 58686aeb..1b77d3e3 100644
--- a/crates/paimon/src/vindex/multi_vector.rs
+++ b/crates/paimon/src/vindex/multi_vector.rs
@@ -17,6 +17,7 @@
//! Shared schema, Arrow and cosine semantics for embedding-list columns.
+use super::pkvector::metric::cosine_norm;
use crate::spec::DataType;
use crate::{Error, Result};
use arrow_array::{Array, FixedSizeListArray, Float32Array, ListArray};
@@ -51,7 +52,7 @@ pub(crate) fn validate_queries(queries: &[&[f32]], width:
Option<usize>) -> Resu
}
pub(crate) fn normalize_into(vector: &[f32], output: &mut Vec<f32>) {
- let norm = norm(vector);
+ let norm = cosine_norm(vector);
let scale = if norm == 0.0 { 1.0 } else { 1.0 / norm };
output.extend(
vector
@@ -60,24 +61,6 @@ pub(crate) fn normalize_into(vector: &[f32], output: &mut
Vec<f32>) {
);
}
-pub(crate) fn norm(vector: &[f32]) -> f64 {
- vector
- .iter()
- .map(|&value| f64::from(value) * f64::from(value))
- .sum::<f64>()
- .sqrt()
-}
-
-pub(crate) fn cosine(query: &[f32], query_norm: f64, vector: &[f32],
vector_norm: f64) -> f64 {
- let denominator = query_norm * vector_norm;
- if denominator == 0.0 {
- return 0.0;
- }
- vector.iter().zip(query).fold(0.0, |sum, (&left, &right)| {
- sum + f64::from(left) * f64::from(right)
- }) / denominator
-}
-
enum Embeddings<'a> {
Array(&'a ListArray),
Vector(&'a FixedSizeListArray),
diff --git a/crates/paimon/src/vindex/pkvector/exact.rs
b/crates/paimon/src/vindex/pkvector/exact.rs
index 80333b58..15b6f639 100644
--- a/crates/paimon/src/vindex/pkvector/exact.rs
+++ b/crates/paimon/src/vindex/pkvector/exact.rs
@@ -143,6 +143,7 @@ pub(crate) fn exact_search(
)));
}
+ let query = metric.prepare_query(query);
let mut reuse = vec![0.0f32; reader.dimension()];
let mut heap: BinaryHeap<WorstFirst> = BinaryHeap::with_capacity(limit +
1);
for position in 0..row_count {
@@ -153,7 +154,7 @@ pub(crate) fn exact_search(
let candidate = PkVectorSearchResult {
data_file_name: data_file_name.to_string(),
row_position: position,
- distance: metric.compute_distance(query, &reuse),
+ distance: query.compute_distance(&reuse),
};
push_bounded(&mut heap, candidate, limit);
}
@@ -193,6 +194,22 @@ mod tests {
}
}
+ #[test]
+ fn cosine_top_one_preserves_a_distance_below_the_similarity_precision() {
+ let mut reader = ArrayReader::new(2, vec![Some(vec![3.0015, 4.0]),
Some(vec![3.0, 4.0])]);
+ let results = exact_search(
+ "data-file",
+ &mut reader,
+ &[3.0, 4.0],
+ VectorSearchMetric::Cosine,
+ 1,
+ &no_exclusion(),
+ )
+ .unwrap();
+ assert_eq!(results[0].row_position, 1);
+ assert_eq!(results[0].distance, 0.0);
+ }
+
#[test]
fn nan_distance_candidate_never_beats_finite_top1() {
// Row 0's stored vector contains NaN → its inner-product distance is a
diff --git a/crates/paimon/src/vindex/pkvector/metric.rs
b/crates/paimon/src/vindex/pkvector/metric.rs
index 7d654e58..773463c6 100644
--- a/crates/paimon/src/vindex/pkvector/metric.rs
+++ b/crates/paimon/src/vindex/pkvector/metric.rs
@@ -15,9 +15,14 @@
// specific language governing permissions and limitations
// under the License.
-use super::data_invalid;
use std::cmp::Ordering;
+use num_bigint::{BigInt, BigUint, Sign};
+use num_traits::{FromPrimitive, ToPrimitive};
+
+use super::data_invalid;
+use crate::common::number::{accumulate_f64_partials, round_f64_partials};
+
/// Order two distances the way Java `Float.compare` does: every NaN sorts
after
/// all numeric values (so a NaN distance is always ranked worst, never best),
/// while non-NaN values keep `total_cmp`'s IEEE total order (which also
matches
@@ -41,8 +46,10 @@ pub(crate) fn normalize_metric(metric: &str) -> String {
metric.to_ascii_lowercase().replace('-', "_")
}
-/// Numeric semantics for a supported vector search metric. Mirrors Java
-/// `org.apache.paimon.globalindex.VectorSearchMetric`.
+/// Metric names and distance conventions follow Java
+/// `org.apache.paimon.globalindex.VectorSearchMetric`. Rust's exact cosine
+/// scorer rounds the distance after subtraction, so close matches can rank
+/// differently from Java.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum VectorSearchMetric {
L2,
@@ -84,15 +91,24 @@ impl VectorSearchMetric {
}
}
- /// Lower-is-better distance for exact vector search.
- pub(crate) fn compute_distance(&self, query: &[f32], stored: &[f32]) ->
f32 {
- match self {
- Self::L2 => squared_l2(query, stored),
- Self::Cosine => cosine_distance(cosine_similarity(query, stored)),
- Self::InnerProduct => -inner_product(query, stored),
+ /// Prepare the query once for exact scoring against multiple rows.
+ pub(crate) fn prepare_query(self, query: &[f32]) ->
PreparedVectorQuery<'_> {
+ PreparedVectorQuery {
+ metric: self,
+ query,
+ cosine_norm: if self == Self::Cosine {
+ cosine_norm(query)
+ } else {
+ 0.0
+ },
}
}
+ #[cfg(test)]
+ pub(crate) fn compute_distance(&self, query: &[f32], stored: &[f32]) ->
f32 {
+ self.prepare_query(query).compute_distance(stored)
+ }
+
/// Convert a higher-is-better standardized index score to a
lower-is-better
/// distance. For L2 with `score == 0.0` this yields `inf` (natural f32
/// behavior, matching Java — no clamp).
@@ -120,6 +136,30 @@ impl VectorSearchMetric {
}
}
+pub(crate) struct PreparedVectorQuery<'a> {
+ metric: VectorSearchMetric,
+ query: &'a [f32],
+ cosine_norm: f64,
+}
+
+impl PreparedVectorQuery<'_> {
+ /// Lower-is-better distance for exact vector search.
+ pub(crate) fn compute_distance(&self, stored: &[f32]) -> f32 {
+ match self.metric {
+ VectorSearchMetric::L2 => squared_l2(self.query, stored),
+ VectorSearchMetric::Cosine => cosine_score(
+ self.query,
+ self.cosine_norm,
+ stored,
+ None,
+ CosineOutput::Distance,
+ &mut Vec::new(),
+ ),
+ VectorSearchMetric::InnerProduct => -inner_product(self.query,
stored),
+ }
+ }
+}
+
fn squared_l2(query: &[f32], stored: &[f32]) -> f32 {
let mut squared = 0.0f32;
for i in 0..query.len() {
@@ -129,21 +169,357 @@ fn squared_l2(query: &[f32], stored: &[f32]) -> f32 {
squared
}
-fn cosine_similarity(query: &[f32], stored: &[f32]) -> f32 {
- let mut dot = 0.0f32;
- let mut query_norm = 0.0f32;
- let mut stored_norm = 0.0f32;
- for i in 0..query.len() {
- dot += query[i] * stored[i];
- query_norm += query[i] * query[i];
- stored_norm += stored[i] * stored[i];
+pub(crate) fn cosine_norm<T: Copy + Into<f64>>(vector: &[T]) -> f64 {
+ vector
+ .iter()
+ .map(|&value| {
+ let value = value.into();
+ value * value
+ })
+ .sum::<f64>()
+ .sqrt()
+}
+
+pub(crate) fn cosine_similarity(query: &[f32], query_norm: f64, stored:
&[f32]) -> f32 {
+ cosine_score(
+ query,
+ query_norm,
+ stored,
+ None,
+ CosineOutput::Similarity,
+ &mut Vec::new(),
+ )
+}
+
+pub(crate) fn cosine_similarity_with_norms(
+ query: &[f32],
+ query_norm: f64,
+ stored: &[f32],
+ stored_norm: f64,
+ partials: &mut Vec<f64>,
+) -> f32 {
+ cosine_score(
+ query,
+ query_norm,
+ stored,
+ Some(stored_norm),
+ CosineOutput::Similarity,
+ partials,
+ )
+}
+
+/// Similarity for aggregation across queries, with the dot accumulated before
+/// normalization and rounding deferred to the final score.
+pub(crate) fn cosine_similarity_f64(
+ query: &[f32],
+ stored: &[f32],
+ norm_product: f64,
+ partials: &mut Vec<f64>,
+) -> f64 {
+ if norm_product == 0.0 {
+ return 0.0;
+ }
+ accumulate_dot_partials(query, stored, partials);
+ (round_f64_partials(partials) / norm_product).clamp(-1.0, 1.0)
+}
+
+#[inline]
+fn cosine_score(
+ query: &[f32],
+ query_norm: f64,
+ stored: &[f32],
+ stored_norm: Option<f64>,
+ output: CosineOutput,
+ partials: &mut Vec<f64>,
+) -> f32 {
+ let mut dot = 0.0_f64;
+ let mut absolute_dot = 0.0_f64;
+ let mut stored_squared_norm = 0.0_f64;
+ for (&query, &stored) in query.iter().zip(stored) {
+ let q = f64::from(query);
+ let s = f64::from(stored);
+ let product = q * s;
+ dot += product;
+ if matches!(output, CosineOutput::Similarity) {
+ absolute_dot += product.abs();
+ }
+ if stored_norm.is_none() {
+ stored_squared_norm += s * s;
+ }
+ }
+ let stored_norm = stored_norm.unwrap_or_else(||
stored_squared_norm.sqrt());
+ let norm_product = query_norm * stored_norm;
+ let absolute_dot_bound = match output {
+ CosineOutput::Similarity => absolute_dot,
+ CosineOutput::Distance => norm_product,
+ };
+ let dot = CosineDot::Approximate {
+ value: dot,
+ absolute_sum_bound: absolute_dot_bound,
+ };
+ let mut bounds = match output.try_round_from_dot(dot, norm_product,
query.len()) {
+ Ok(rounded) => return rounded,
+ Err(bounds) => bounds,
+ };
+ if matches!(output, CosineOutput::Distance) && bounds.1 <= 0.5 {
+ if bounds.0 == 0.0 && (query == stored ||
positively_proportional(query, stored)) {
+ return 0.0;
+ }
+ let (lower, upper) = normalized_distance_bounds(query, stored,
query_norm, stored_norm);
+ bounds = (bounds.0.max(lower), bounds.1.min(upper));
+ if bounds.0 == bounds.1 {
+ return bounds.0;
+ }
+ }
+ output.round_exact(dot, norm_product, query, stored, bounds, partials)
+}
+
+fn positively_proportional(query: &[f32], stored: &[f32]) -> bool {
+ let Some((&query_pivot, &stored_pivot)) =
query.iter().zip(stored).find(|(q, _)| **q != 0.0)
+ else {
+ return false;
+ };
+ let query_pivot = f64::from(query_pivot);
+ let stored_pivot = f64::from(stored_pivot);
+ // Both cross products are exact because the coordinates are finite f32.
+ query_pivot * stored_pivot > 0.0
+ && query
+ .iter()
+ .zip(stored)
+ .all(|(&q, &s)| f64::from(q) * stored_pivot == f64::from(s) *
query_pivot)
+}
+
+/// Bound the cosine distance as half the squared difference of unit vectors.
+/// The distance interval narrows as the difference approaches zero.
+fn normalized_distance_bounds(
+ query: &[f32],
+ stored: &[f32],
+ query_norm: f64,
+ stored_norm: f64,
+) -> (f32, f32) {
+ let roundoff = (query.len() as f64 + 8.0) * f64::EPSILON;
+ if roundoff >= 0.5 {
+ return (0.0, 2.0);
+ }
+ let inverse_query_norm = query_norm.recip();
+ let inverse_stored_norm = stored_norm.recip();
+ let mut squared_length = 0.0_f64;
+ for (&q, &s) in query.iter().zip(stored) {
+ let difference = f64::from(q) * inverse_query_norm - f64::from(s) *
inverse_stored_norm;
+ squared_length += difference * difference;
+ }
+ let length = squared_length.sqrt();
+ // Each input has unit length. Bound the normalization errors in both
+ // inputs and the relative error in the length of their difference.
+ let error = (1.0 + length) * roundoff / (1.0 - roundoff);
+ let lower = (length - error).max(0.0);
+ let upper = (length + error).min(2.0);
+ ((0.5 * lower * lower) as f32, (0.5 * upper * upper) as f32)
+}
+
+#[derive(Clone, Copy)]
+pub(crate) enum CosineDot {
+ Exact(f64),
+ Approximate { value: f64, absolute_sum_bound: f64 },
+}
+
+#[derive(Clone, Copy)]
+pub(crate) enum CosineOutput {
+ Similarity,
+ Distance,
+}
+
+impl CosineOutput {
+ fn value(self, similarity: f64) -> f64 {
+ match self {
+ Self::Similarity => similarity,
+ Self::Distance => 1.0 - similarity,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn round_from_dot<T: Copy + Into<f64>>(
+ self,
+ dot_product: CosineDot,
+ norm_product: f64,
+ query: &[T],
+ stored: &[T],
+ partials: &mut Vec<f64>,
+ ) -> f32 {
+ self.try_round_from_dot(dot_product, norm_product, query.len())
+ .unwrap_or_else(|bounds| {
+ self.round_exact(dot_product, norm_product, query, stored,
bounds, partials)
+ })
+ }
+
+ #[inline]
+ pub(crate) fn try_round_from_dot(
+ self,
+ dot_product: CosineDot,
+ norm_product: f64,
+ dimension: usize,
+ ) -> Result<f32, (f32, f32)> {
+ let (dot, absolute_dot_bound) = match dot_product {
+ CosineDot::Exact(value) => (value, 0.0),
+ CosineDot::Approximate {
+ value,
+ absolute_sum_bound,
+ } => (value, absolute_sum_bound),
+ };
+ if norm_product == 0.0 {
+ return Ok(self.value(0.0) as f32);
+ }
+ if !norm_product.is_finite() {
+ return Ok(self.value(dot / norm_product) as f32);
+ }
+ let inverse_norm = norm_product.recip();
+ let estimate = self.value(dot * inverse_norm);
+ // The products of two f32 coordinates are exact in f64. Bound the
+ // accumulation error in the dot and both squared norms, then allow
+ // for the square roots, normalization, and distance subtraction.
+ let error = 8.0
+ * f64::EPSILON
+ * (dimension as f64 + 2.0)
+ * (absolute_dot_bound + dot.abs())
+ * inverse_norm
+ + f64::EPSILON * estimate.abs();
+ let lower = (estimate - error) as f32;
+ let upper = (estimate + error) as f32;
+ if lower.to_bits() == upper.to_bits() {
+ return Ok(lower);
+ }
+ let lower = self.clamp(lower);
+ let upper = self.clamp(upper);
+ if lower.to_bits() == upper.to_bits() {
+ return Ok(lower);
+ }
+ Err((lower, upper))
+ }
+
+ fn clamp(self, value: f32) -> f32 {
+ match self {
+ Self::Similarity => value.clamp(-1.0, 1.0),
+ Self::Distance => value.clamp(0.0, 2.0),
+ }
}
- let denominator = ((query_norm as f64).sqrt() * (stored_norm as
f64).sqrt()) as f32;
- if denominator == 0.0 {
- 0.0
- } else {
- dot / denominator
+
+ #[cold]
+ pub(crate) fn round_exact<T: Copy + Into<f64>>(
+ self,
+ dot_product: CosineDot,
+ norm_product: f64,
+ query: &[T],
+ stored: &[T],
+ mut bounds: (f32, f32),
+ partials: &mut Vec<f64>,
+ ) -> f32 {
+ let dot = match dot_product {
+ CosineDot::Exact(dot) => scale_f32_product(dot),
+ CosineDot::Approximate { .. } => exact_dot(query, stored,
partials),
+ };
+ if dot.sign() == Sign::NoSign {
+ return self.value(0.0) as f32;
+ }
+ let recovered_dot = match (self, dot_product) {
+ (Self::Similarity, CosineDot::Approximate { .. }) =>
exact_dot_as_f64(&dot),
+ _ => None,
+ };
+ if let Some(dot) = recovered_dot {
+ // Cancellation error is gone. The approximate norms may already
+ // be sufficient to decide the rounded similarity.
+ match self.try_round_from_dot(CosineDot::Exact(dot), norm_product,
query.len()) {
+ Ok(score) => return score,
+ Err((lower, upper)) => bounds = (bounds.0.max(lower),
bounds.1.min(upper)),
+ }
+ }
+ let negative = dot.sign() == Sign::Minus;
+ let norms_squared = exact_dot(query, query, partials).into_parts().1
+ * exact_dot(stored, stored, partials).into_parts().1;
+ let dot_squared = dot.magnitude() * dot.magnitude();
+ if dot_squared == norms_squared {
+ return self.value(if negative { -1.0 } else { 1.0 }) as f32;
+ }
+
+ // Every midpoint between adjacent f32 results is a multiple of 2^-150.
+ // Compare the exact cosine with each midpoint by squaring both sides.
+ // For a distance midpoint m, compare the cosine with 1 - m, retaining
+ // the tiny difference from 1 as an integer even if f64 would lose it.
+ const MIDPOINT_SCALE_EXPONENT: usize = 150;
+ let scale = 2.0_f64.powi(MIDPOINT_SCALE_EXPONENT as i32);
+ let one = BigUint::from(1_u8) << MIDPOINT_SCALE_EXPONENT;
+ let scaled_dot_squared = dot_squared << (2 * MIDPOINT_SCALE_EXPONENT);
+ let compare_magnitude =
+ |threshold: &BigUint| scaled_dot_squared.cmp(&(&norms_squared *
threshold * threshold));
+ let (lower, upper) = if matches!(self, Self::Similarity) && negative {
+ (-bounds.1, -bounds.0)
+ } else {
+ bounds
+ };
+ let mut first = lower.max(0.0).abs().to_bits();
+ let mut last = upper.max(0.0).abs().to_bits();
+ while first < last {
+ let bits = first + (last - first) / 2;
+ let lower = f32::from_bits(bits);
+ let midpoint = (f64::from(lower) + f64::from(lower.next_up())) *
0.5;
+ let threshold = BigUint::from_f64(midpoint * scale).expect("finite
f32 midpoint");
+ let ordering = match self {
+ Self::Similarity => compare_magnitude(&threshold),
+ Self::Distance if !negative && threshold < one => {
+ compare_magnitude(&(&one - &threshold)).reverse()
+ }
+ Self::Distance if negative && threshold > one => {
+ compare_magnitude(&(&threshold - &one))
+ }
+ Self::Distance if negative => Ordering::Greater,
+ Self::Distance => Ordering::Less,
+ };
+ if ordering == Ordering::Greater || (ordering == Ordering::Equal
&& bits & 1 != 0) {
+ first = bits + 1;
+ } else {
+ last = bits;
+ }
+ }
+ let rounded = f32::from_bits(first);
+ if matches!(self, Self::Similarity) && negative {
+ -rounded
+ } else {
+ rounded
+ }
+ }
+}
+
+/// Sum the products exactly in units of 2^-298, the square of the smallest
+/// nonzero f32. Keep the floating-point residuals until conversion so the loop
+/// over coordinates does not need arbitrary-precision arithmetic.
+fn exact_dot<T: Copy + Into<f64>>(query: &[T], stored: &[T], partials: &mut
Vec<f64>) -> BigInt {
+ accumulate_dot_partials(query, stored, partials);
+ partials.iter().copied().map(scale_f32_product).sum()
+}
+
+fn accumulate_dot_partials<T: Copy + Into<f64>>(
+ query: &[T],
+ stored: &[T],
+ partials: &mut Vec<f64>,
+) {
+ let products = query
+ .iter()
+ .zip(stored)
+ .map(|(&query, &stored)| query.into() * stored.into());
+ accumulate_f64_partials(products, partials);
+}
+
+fn scale_f32_product(value: f64) -> BigInt {
+ BigInt::from_f64(value * 2.0_f64.powi(298)).expect("finite f32 products")
+}
+
+fn exact_dot_as_f64(dot: &BigInt) -> Option<f64> {
+ // The remaining bits must fit the f64 significand after removing the
+ // common power of two. Dot products are in units of 2^-298.
+ let significant_bits = dot.bits() - dot.trailing_zeros().unwrap_or(0);
+ if significant_bits > u64::from(f64::MANTISSA_DIGITS) {
+ return None;
}
+ dot.to_f64().map(|scaled| scaled * 2.0_f64.powi(-298))
}
fn inner_product(query: &[f32], stored: &[f32]) -> f32 {
@@ -166,6 +542,39 @@ mod tests {
/// every finite value; `java_float_compare` must order it *after*.
const NEGATIVE_NAN: f32 = f32::from_bits(0xffc00000);
+ #[test]
+ fn test_recovered_dot_resolves_cosine_with_approximate_norms() {
+ let tiny = 2.0_f32.powi(-40);
+ let query = [1.0, tiny, 1.0];
+ let query_norm = cosine_norm(&query);
+ let mut partials = Vec::new();
+ let similarity = CosineOutput::Similarity;
+ for sign in [1.0, -1.0] {
+ let stored = [1.0, sign * tiny, -1.0];
+ let norm_product = query_norm * cosine_norm(&stored);
+ assert!(similarity
+ .try_round_from_dot(
+ CosineDot::Approximate {
+ value: 0.0,
+ absolute_sum_bound: 2.0,
+ },
+ norm_product,
+ query.len(),
+ )
+ .is_err());
+ let dot = exact_dot_as_f64(&exact_dot(&query, &stored, &mut
partials)).unwrap();
+ assert_eq!(dot, f64::from(sign) * 2.0_f64.powi(-80));
+ let expected = sign * 2.0_f32.powi(-81);
+ assert_eq!(
+ similarity.try_round_from_dot(CosineDot::Exact(dot),
norm_product, query.len()),
+ Ok(expected)
+ );
+ assert_eq!(cosine_similarity(&query, query_norm, &stored),
expected);
+ }
+ let inexact = exact_dot(&[1.0, tiny], &[1.0, tiny], &mut partials);
+ assert_eq!(exact_dot_as_f64(&inexact), None);
+ }
+
#[test]
fn java_float_compare_sorts_all_nan_after_finite() {
// Positive NaN after a finite value.
@@ -244,23 +653,170 @@ mod tests {
assert_eq!(VectorSearchMetric::Cosine.compute_distance(&zero, &s),
1.0);
}
+ #[test]
+ fn test_cosine_zero_preserves_nonfinite_scores() {
+ assert_eq!(cosine_similarity(&[0.0, 0.0], 0.0, &[1.0, 2.0]), 0.0);
+ assert!(cosine_similarity(&[0.0, 0.0], 0.0, &[f32::INFINITY,
0.0]).is_nan());
+ }
+
+ #[test]
+ fn test_cosine_exact_distance_is_invariant_to_vector_scale() {
+ for scale in [1.0e20_f32, 1.0e-23_f32] {
+ let query = [scale, 0.0];
+ assert_eq!(
+ VectorSearchMetric::Cosine.compute_distance(&query, &query),
+ 0.0
+ );
+ assert_eq!(
+ VectorSearchMetric::Cosine.compute_distance(&query, &[-scale,
0.0]),
+ 2.0
+ );
+ }
+ }
+
+ #[test]
+ fn test_cosine_distance_orders_near_parallel_with_underflowing_squares() {
+ let scale = 2.0_f32.powi(-63);
+ let mut query = [0.0; 257];
+ query[256] = scale;
+ let mut nearly_parallel = [scale * 2.0_f32.powi(-12); 257];
+ nearly_parallel[256] = scale;
+
+ let metric = VectorSearchMetric::Cosine;
+ assert_eq!(metric.compute_distance(&query, &query), 0.0);
+ assert!(metric.compute_distance(&query, &nearly_parallel) > 0.0);
+ }
+
+ #[test]
+ fn test_cosine_distance_orders_near_orthogonal_with_underflowing_dot() {
+ let similarity = 2.0_f32.powi(-24);
+ let metric = VectorSearchMetric::Cosine;
+ for scale in [1.0, 2.0_f32.powi(-63)] {
+ let query = [scale, 0.0];
+ let orthogonal = [0.0, scale];
+ let nearly_orthogonal = [scale * similarity, scale];
+ assert_eq!(metric.compute_distance(&query, &orthogonal), 1.0);
+ assert_eq!(
+ metric.compute_distance(&query, &nearly_orthogonal),
+ 1.0 - similarity
+ );
+ }
+ }
+
+ #[test]
+ fn test_cosine_distance_orders_mixed_scale_candidates() {
+ let query = [3.0, 13.0];
+ let exact = [895.0 * query[0], 895.0 * query[1]];
+ let metric = VectorSearchMetric::Cosine;
+ // The squared norm product exceeds the squared dot by one:
+ // (3 * 173 - 13 * 40)^2 == 1.
+ let denominator = (178.0_f64 * 31_529.0).sqrt();
+ let expected_distance = (1.0 / (denominator * (denominator + 2369.0)))
as f32;
+ for scale in [1.0, 2.0_f32.powi(64)] {
+ let nearby = [40.0 * scale, 173.0 * scale];
+ let nearby_distance = metric.compute_distance(&query, &nearby);
+ assert_eq!(nearby_distance, expected_distance);
+ assert_eq!(metric.compute_distance(&query, &exact), 0.0);
+ }
+ }
+
+ #[test]
+ fn test_cosine_distance_preserves_angle_below_f64_similarity_precision() {
+ let tiny = 2.0_f32.powi(-50);
+ let distance = VectorSearchMetric::Cosine.compute_distance(&[1.0,
0.0], &[1.0, tiny]);
+ assert_eq!(distance, 2.0_f32.powi(-101));
+ }
+
+ #[test]
+ fn test_normalized_distance_resolves_near_parallel_rounding() {
+ let query = [1.0; 256];
+ let query_norm = cosine_norm(&query);
+ for k in 1..=13 {
+ let mut stored = query;
+ let delta = k as f32 * 2.0_f32.powi(-12);
+ stored[0] += delta;
+ let stored_norm = cosine_norm(&stored);
+
+ // For q = [1, ..., 1] and s = q + delta*e_0, the squared norm
+ // product minus the squared dot is (dimension - 1) * delta^2.
+ let delta = f64::from(delta);
+ let norm_product = query_norm * stored_norm;
+ let dot = 256.0 + delta;
+ let expected = (255.0 * delta * delta / (norm_product *
(norm_product + dot))) as f32;
+ assert!(CosineOutput::Distance
+ .try_round_from_dot(
+ CosineDot::Approximate {
+ value: dot,
+ absolute_sum_bound: norm_product,
+ },
+ norm_product,
+ query.len(),
+ )
+ .is_err());
+ assert_eq!(
+ normalized_distance_bounds(&query, &stored, query_norm,
stored_norm),
+ (expected, expected)
+ );
+ assert_eq!(
+ VectorSearchMetric::Cosine.compute_distance(&query, &stored),
+ expected
+ );
+ }
+ }
+
+ #[test]
+ fn test_cosine_distance_for_exact_rescalings() {
+ let mut query: Vec<_> = (0..256).map(|i| ((31 * i % 27) - 13) as
f32).collect();
+ query[0] = 0.0;
+ let prepared = VectorSearchMetric::Cosine.prepare_query(&query);
+ for scale in 2..=17 {
+ let stored: Vec<_> = query.iter().map(|&value| value * scale as
f32).collect();
+ assert!(positively_proportional(&query, &stored));
+ assert_eq!(prepared.compute_distance(&stored), 0.0);
+ let opposite: Vec<_> = stored.iter().map(|&value|
-value).collect();
+ assert!(!positively_proportional(&query, &opposite));
+ assert_eq!(prepared.compute_distance(&opposite), 2.0);
+ }
+ let mut nearby = query.clone();
+ nearby[0] = 2.0_f32.powi(-50);
+ assert!(!positively_proportional(&query, &nearby));
+ assert!(prepared.compute_distance(&nearby) > 0.0);
+ }
+
+ #[test]
+ fn test_cosine_similarity_rounds_signed_subnormal_midpoints_to_even() {
+ let tiny = 2.0_f32.powi(-75);
+ let mut query = vec![tiny];
+ let mut stored = vec![tiny];
+ // Pad each squared norm to exactly one using disjoint coordinates.
+ // The only shared product is 2^-150, the first f32 rounding midpoint.
+ for i in 1..=75 {
+ let value = 2.0_f32.powi(-i);
+ query.extend([value, value, value, 0.0, 0.0, 0.0]);
+ stored.extend([0.0, 0.0, 0.0, value, value, value]);
+ }
+ let norm = cosine_norm(&query);
+ assert_eq!(
+ cosine_similarity(&query, norm, &stored).to_bits(),
+ 0.0_f32.to_bits()
+ );
+ stored[0] = -tiny;
+ assert_eq!(
+ cosine_similarity(&query, norm, &stored).to_bits(),
+ (-0.0_f32).to_bits()
+ );
+ }
+
#[test]
fn test_cosine_non_perfect_square_norm_uses_f64_sqrt() {
- // query [0,3] -> norm 9, stored [1,2] -> norm 5; sqrt(5) is irrational
- // so the f32-sqrt path (each sqrt taken in f32, then widened) and the
- // f64-sqrt path (widen first, sqrt in f64) produce different f32 bits:
- // buggy similarity 0.8944271 vs correct 0.8944272. Encode the f64
contract
- // in the expected value (dot / (sqrt(9.0f64) * sqrt(5.0f64)) as f32)
rather
- // than a magic literal, so this pins the Java-matching f64
arithmetic. The
- // cosine distance is `1 - similarity`, so the sqrt path is exercised
here.
+ // Taking the square roots in f32 can already lose a bit of the score.
let q = [0.0f32, 3.0];
let s = [1.0f32, 2.0];
- let dot = 6.0f32;
- let denominator = ((9.0f64).sqrt() * (5.0f64).sqrt()) as f32;
- let expected_similarity = dot / denominator;
+ let denominator = (9.0_f64).sqrt() * (5.0_f64).sqrt();
+ let expected_distance = (1.0 - 6.0 / denominator) as f32;
assert_eq!(
VectorSearchMetric::Cosine.compute_distance(&q, &s),
- 1.0 - expected_similarity
+ expected_distance
);
}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 4ed6bae9..5e4c7745 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -3156,6 +3156,19 @@ Larger refine factors may improve recall and ordering
quality, but they also
increase index result merging, raw-vector reads, and exact scoring work. Use
the
smallest factor that provides the desired recall.
+### Exact Cosine Scoring in Rust and Java
+
+For the cosine metric on Data Evolution tables, exact raw scans and reranking
+rank by similarity. Rust accumulates the dot product in wider precision. Java
+can accumulate it in `float`, where cancellation can change scores and the
+Top-K order of closely matched candidates.
+
+Rust's exact scans and reranking on primary-key tables round the cosine
distance
+(`1 - cosine`) to `f32`. The Java scorer rounds the similarity to `float`
before
+subtracting it from one. Closely matched candidates can therefore have
different
+distances or Top-K order across the two runtimes.
+[Java exact
scorer](https://github.com/apache/paimon/blob/68dddca6ba335b17bbf8febb6444a121dcd8dcce/paimon-core/src/main/java/org/apache/paimon/globalindex/VectorSearchMetric.java#L87-L130)
+
### Lateral Joins
Use `CROSS JOIN LATERAL` when query vectors come from another relation. In
this mode, the third `vector_search` argument is a column reference from the
left side of the join instead of a JSON literal: