use std::cmp::Ordering;
const F32_ROUNDOFF: f64 = 1.0 / 16_777_216.0;
const F32_SUBNORMAL_STEP: f64 = 1.401_298_464_324_817e-45;
#[must_use]
pub fn vector_norm(vector: &[f32]) -> f32 {
vector.iter().map(|value| value * value).sum::<f32>().sqrt()
}
#[must_use]
pub fn dot_product(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).map(|(a, b)| a * b).sum::<f32>()
}
#[must_use]
pub fn score(dot: f32, denom: f32, exported: bool) -> f32 {
let mut score = if denom == 0.0 { 0.0 } else { dot / denom };
if exported {
score *= if score >= 0.0 { 1.1 } else { 0.9 };
}
score
}
#[must_use]
pub fn rank_order(a: (f32, u32), b: (f32, u32)) -> Ordering {
let score_a = if a.0.is_finite() {
a.0
} else {
f32::NEG_INFINITY
};
let score_b = if b.0.is_finite() {
b.0
} else {
f32::NEG_INFINITY
};
if score_a == score_b {
a.1.cmp(&b.1)
} else {
score_b.total_cmp(&score_a)
}
}
pub(crate) fn f32_at_or_below(value: f64) -> f32 {
#[expect(
clippy::cast_possible_truncation,
reason = "rounding to f32 is the point; the result is corrected below"
)]
let rounded = value as f32;
if f64::from(rounded) > value {
rounded.next_down()
} else {
rounded
}
}
pub(crate) fn f32_at_or_above(value: f64) -> f32 {
#[expect(
clippy::cast_possible_truncation,
reason = "rounding to f32 is the point; the result is corrected below"
)]
let rounded = value as f32;
if f64::from(rounded) < value {
rounded.next_up()
} else {
rounded
}
}
fn gamma(terms: usize) -> f64 {
let nu = terms as f64 * F32_ROUNDOFF;
nu / (1.0 - nu)
}
#[derive(Clone, Debug)]
pub(crate) struct QueryTerms {
pub(crate) norm: f32,
l1: f64,
l2: f64,
gamma: f64,
subnormal_slack: f64,
}
impl QueryTerms {
pub(crate) fn new(query: &[f32]) -> Self {
let l1 = query
.iter()
.map(|value| f64::from(*value).abs())
.sum::<f64>();
let l2 = query
.iter()
.map(|value| f64::from(*value) * f64::from(*value))
.sum::<f64>()
.sqrt();
Self {
norm: vector_norm(query),
l1,
l2,
gamma: gamma(query.len() + 2 * LANES),
subnormal_slack: 4.0 * (query.len() + 2 * LANES) as f64 * F32_SUBNORMAL_STEP,
}
}
pub(crate) fn center(&self, query: &[f32], center: &[f32]) -> CenterTerms {
let shift = query
.iter()
.zip(center)
.map(|(q, m)| f64::from(*q) * f64::from(*m))
.sum::<f64>();
let l2 = center
.iter()
.map(|m| f64::from(*m) * f64::from(*m))
.sum::<f64>()
.sqrt()
* (1.0 + 1e-12);
CenterTerms {
shift,
shift_error: (query.len() + 2) as f64 * f64::EPSILON * self.l2 * l2,
l2,
}
}
pub(crate) fn dot_bounds(
&self,
approx: f32,
params: &ScanParams,
center: &CenterTerms,
) -> (f32, f32) {
let scale = f64::from(params.scale);
let estimate = center.shift + scale * f64::from(approx);
let quantization =
(f64::from(params.max_residual) * self.l1).min(f64::from(params.residual) * self.l2);
let vector_l2 = f64::from(params.norm) * (1.0 + 2.0 * self.gamma);
let rounding =
self.gamma * self.l2 * (2.0 * vector_l2 + center.l2 + f64::from(params.residual))
+ self.subnormal_slack * (1.0 + scale)
+ center.shift_error
+ estimate.abs() * f64::EPSILON;
let error = (quantization + rounding) * (1.0 + 1e-9);
(
f32_at_or_above(estimate - error),
f32_at_or_below(estimate + error),
)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct CenterTerms {
shift: f64,
shift_error: f64,
l2: f64,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) struct ScanParams {
pub(crate) scale: f32,
pub(crate) residual: f32,
pub(crate) norm: f32,
pub(crate) max_residual: f32,
}
impl ScanParams {
pub(crate) fn is_sound(&self) -> bool {
[self.scale, self.residual, self.norm, self.max_residual]
.iter()
.all(|value| value.is_finite() && *value >= 0.0)
}
}
const LANES: usize = 16;
pub(crate) fn approx_kernel() -> fn(&[f32], &[u8]) -> f32 {
#[cfg(target_arch = "x86_64")]
if std::arch::is_x86_feature_detected!("avx2") {
return approx_dot_avx2_detected;
}
approx_dot
}
#[cfg(target_arch = "x86_64")]
fn approx_dot_avx2_detected(query: &[f32], codes: &[u8]) -> f32 {
#[target_feature(enable = "avx2")]
fn avx2(query: &[f32], codes: &[u8]) -> f32 {
approx_dot(query, codes)
}
unsafe { avx2(query, codes) }
}
#[inline(always)]
pub(crate) fn approx_dot(query: &[f32], codes: &[u8]) -> f32 {
let mut lanes = [0f32; LANES];
let (query_chunks, query_rest) = query.as_chunks::<LANES>();
let (code_chunks, code_rest) = codes.as_chunks::<LANES>();
for (q, c) in query_chunks.iter().zip(code_chunks) {
for ((lane, q), c) in lanes.iter_mut().zip(q).zip(c) {
*lane += q * f32::from(c.cast_signed());
}
}
let mut total = 0f32;
for lane in lanes {
total += lane;
}
for (q, c) in query_rest.iter().zip(code_rest) {
total += q * f32::from(c.cast_signed());
}
total
}
pub(crate) fn mean<'v>(
vectors: impl ExactSizeIterator<Item = &'v [f32]>,
dimensions: usize,
) -> Vec<f32> {
let count = vectors.len();
let mut sums = vec![0f64; dimensions];
for vector in vectors {
for (sum, value) in sums.iter_mut().zip(vector) {
*sum += f64::from(*value);
}
}
sums.iter()
.map(|sum| {
#[expect(
clippy::cast_possible_truncation,
reason = "any f32 near the mean serves; the residuals are measured against the stored one"
)]
let value = (sum / count.max(1) as f64) as f32;
value
})
.collect()
}
pub(crate) fn quantize(vector: &[f32], center: &[f32], codes: &mut Vec<u8>) -> ScanParams {
let offsets: Vec<f64> = vector
.iter()
.zip(center)
.map(|(v, m)| f64::from(*v) - f64::from(*m))
.collect();
let peak = offsets.iter().fold(0f64, |peak, w| peak.max(w.abs()));
#[expect(
clippy::cast_possible_truncation,
reason = "any f32 scale works; the residuals are measured against the stored one"
)]
let scale = (peak / 127.0) as f32;
let mut squares = 0f64;
let mut max_residual = 0f64;
for offset in &offsets {
let code = if scale > 0.0 {
(offset / f64::from(scale)).round().clamp(-127.0, 127.0)
} else {
0.0
};
#[expect(
clippy::cast_possible_truncation,
reason = "the code is a whole number clamped to -127..=127"
)]
let code = code as i8;
codes.push(code.cast_unsigned());
let residual = (offset - f64::from(scale) * f64::from(code)).abs();
squares += residual * residual;
max_residual = max_residual.max(residual);
}
let slack = peak * f64::EPSILON;
let margin = 1.0 + 1e-12;
ScanParams {
scale,
residual: f32_at_or_above(
(squares.sqrt() + slack * (offsets.len() as f64).sqrt()) * margin,
),
norm: vector_norm(vector),
max_residual: f32_at_or_above((max_residual + slack) * margin),
}
}