Cotton code
122 lines · 4.8 KB · RustRaw
//! The int8 quantiser — a provider's 512 floats, as the 512 bytes the file//! holds. The port of `packages/core/src/engine/quantize.ts`.//!//! The whole point of normalising BEFORE quantising is that it makes cosine//! similarity a plain integer dot product: both the stored vector and the query//! vector are unit length, so `cos(a,b) = Σ aᵢ·bᵢ` with no division, no stored//! norm and no float column. That is what lets the lane scan a byte array and//! keep the file 512 bytes per chunk instead of 4 KB.//!//! This is an APPROXIMATE index and says so: quantisation perturbs each//! vector's length by well under a percent, which reorders near-ties. It never//! reorders results that were not already a coin toss.//!//! The scan itself — the dot product, the per-source top-k heap — is the LANE's//! and lands with it. This module is the format alone: floats in, bytes out,//! bytes back to floats.use crate::js_number::math_round;/// How many components a stored vector has.////// Declared HERE. The live second spelling of the number is/// `crates/cotton-ai/src/embeddings.rs`, which asks the model for exactly this/// width; `quantize_tests.rs` pins this one.pub const EMBED_DIMS: usize = 512;/// Bytes per stored vector — one signed byte per dimension.pub const EMBED_VECTOR_BYTES: usize = EMBED_DIMS;/// The int8 scale: a unit-length component maps onto -127…127.////// 127 rather than 128 so the range is symmetric — -128 has no positive twin,/// and a vector and its negation must quantise to exact opposites or the dot/// product acquires a direction-dependent bias.pub const EMBED_QUANTIZE_SCALE: f64 = 127.0;/// Why a vector could not be stored. The `Display` strings are the TypeScript's/// thrown messages verbatim, because its tests match on them.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum QuantizeError {    #[error("embedding has {0} dimensions, expected 512 — the provider call must pass the dimensions parameter")]    Dimensions(usize),    #[error("embedding contains a non-finite value")]    NonFinite,    #[error("embedding has zero length and no direction")]    ZeroLength,    #[error("stored vector is {0} bytes, expected 512")]    VectorBytes(usize),}fn assert_dims(length: usize) -> Result<(), QuantizeError> {    if length == EMBED_DIMS {        Ok(())    } else {        Err(QuantizeError::Dimensions(length))    }}/// L2-normalise to unit length.////// A zero vector is REFUSED rather than passed through: it has no direction,/// its dot product with everything is zero, and stored as 512 zero bytes it/// would be a chunk that silently never matches anything. A provider returning/// one means the call went wrong, and that is worth a failure the indexer's/// backoff can see rather than a row nobody can explain later.pub fn normalize_unit(values: &[f64]) -> Result<Vec<f64>, QuantizeError> {    assert_dims(values.len())?;    let mut sum_squares = 0.0_f64;    for value in values {        if !value.is_finite() {            return Err(QuantizeError::NonFinite);        }        sum_squares += value * value;    }    let norm = sum_squares.sqrt();    if norm == 0.0 {        return Err(QuantizeError::ZeroLength);    }    Ok(values.iter().map(|value| value / norm).collect())}/// A provider's vector as the 512 bytes the embeddings table holds.////// `clamp(round(v × 127), -127, 127)` over the unit-normalised vector. The/// clamp is not decoration: a component of a unit vector cannot exceed 1, so it/// can only fire on floating-point slop at ±1, and it is cheaper than reasoning/// about whether it ever will.////// The bytes are the signed values reinterpreted, which is how the column/// stores them and how the lane reads them back.pub fn quantize_embedding(values: &[f64]) -> Result<Vec<u8>, QuantizeError> {    let unit = normalize_unit(values)?;    Ok(unit        .iter()        .take(EMBED_DIMS)        .map(|component| {            let scaled = math_round(component * EMBED_QUANTIZE_SCALE);            let clamped = scaled.clamp(-EMBED_QUANTIZE_SCALE, EMBED_QUANTIZE_SCALE);            (clamped as i8) as u8        })        .collect())}/// The stored bytes back as floats — the inverse of [`quantize_embedding`], to/// within the quantisation step.////// Deliberately NOT re-normalised: the result is what the lane's integer dot/// product actually compares, so a caller checking the approximation is/// checking the real thing rather than a tidied version of it.pub fn dequantize_embedding(bytes: &[u8]) -> Result<Vec<f64>, QuantizeError> {    if bytes.len() != EMBED_VECTOR_BYTES {        return Err(QuantizeError::VectorBytes(bytes.len()));    }    Ok(bytes        .iter()        .map(|byte| f64::from(*byte as i8) / EMBED_QUANTIZE_SCALE)        .collect())}#[cfg(test)]#[path = "quantize_tests.rs"]mod tests;