Cotton code
123 lines · 4.9 KB · RustRaw
//! How a vector is written into a typed column — one encoding for every//! engine that fills one (the serving Mac's Vision and Core ML today, an//! Android engine later), so a column read anywhere means one thing.//!//! The text is base64 (standard alphabet, padded) of the vector's components//! as little-endian IEEE 754 HALF-precision floats. Half, because the column//! syncs to every device: a 768-component image print is 1.5 KB rather than//! 3 KB, and a 512-component face print 1 KB, and cosine distance between//! unit vectors moves in the fourth decimal at most — well under the margins//! the matchers decide on. The model that made the vector is its own column//! beside it; vectors of two models are never compared.use base64::Engine;/// f32 → IEEE 754 binary16 bits, round to nearest even. Out-of-range values/// become ±infinity, a NaN stays a NaN.pub fn f16_bits(value: f32) -> u16 {    let bits = value.to_bits();    let sign = ((bits >> 16) & 0x8000) as u16;    let exponent = ((bits >> 23) & 0xff) as i32;    let mantissa = bits & 0x007f_ffff;    if exponent == 0xff {        // Infinity or NaN; a NaN keeps a set mantissa bit.        return sign | 0x7c00 | if mantissa != 0 { 0x0200 } else { 0 };    }    let unbiased = exponent - 127;    if unbiased > 15 {        return sign | 0x7c00;    }    if unbiased >= -14 {        // Normal half. Keep 10 mantissa bits, round to nearest even.        let half_exponent = ((unbiased + 15) as u32) << 10;        let mut half = half_exponent | (mantissa >> 13);        let rest = mantissa & 0x1fff;        if rest > 0x1000 || (rest == 0x1000 && (half & 1) == 1) {            half += 1; // may carry into the exponent, which is correct rounding        }        return sign | half as u16;    }    if unbiased >= -25 {        // Subnormal half.        let full = mantissa | 0x0080_0000;        let shift = (-unbiased - 14 + 13) as u32;        let mut half = full >> shift;        let rest = full & ((1 << shift) - 1);        let midpoint = 1 << (shift - 1);        if rest > midpoint || (rest == midpoint && (half & 1) == 1) {            half += 1;        }        return sign | half as u16;    }    sign}/// IEEE 754 binary16 bits → f32, exactly.pub fn f32_of_f16(half: u16) -> f32 {    let sign = u32::from(half & 0x8000) << 16;    let exponent = u32::from((half >> 10) & 0x1f);    let mantissa = u32::from(half & 0x03ff);    let bits = match (exponent, mantissa) {        (0, 0) => sign,        (0, _) => {            // Subnormal: normalise it.            let mut e: i32 = -14;            let mut m = mantissa;            while m & 0x0400 == 0 {                m <<= 1;                e -= 1;            }            sign | (((e + 127) as u32) << 23) | ((m & 0x03ff) << 13)        }        (0x1f, 0) => sign | 0x7f80_0000,        (0x1f, _) => sign | 0x7fc0_0000,        _ => sign | ((exponent + 127 - 15) << 23) | (mantissa << 13),    };    f32::from_bits(bits)}/// The column text for a vector.pub fn encode(vector: &[f32]) -> String {    let bytes: Vec<u8> = vector.iter().flat_map(|value| f16_bits(*value).to_le_bytes()).collect();    base64::engine::general_purpose::STANDARD.encode(bytes)}/// A vector back out of its column text, or `None` for text that is not one/// (bad base64, an odd byte count, or empty).pub fn decode(text: &str) -> Option<Vec<f32>> {    let bytes = base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()?;    if bytes.is_empty() || bytes.len() % 2 != 0 {        return None;    }    let (pairs, _) = bytes.as_chunks::<2>();    Some(pairs.iter().map(|pair| f32_of_f16(u16::from_le_bytes(*pair))).collect())}#[cfg(test)]mod tests {    use super::*;    /// RULE: A vector written into a column reads back within half precision, so a print made on one device means the same on every other.    #[test]    fn a_vector_survives_its_column() {        let vector: Vec<f32> = (0..768).map(|i| ((i as f32) * 0.37).sin() * 0.05).collect();        let back = decode(&encode(&vector)).expect("decodes");        assert_eq!(back.len(), vector.len());        for (a, b) in vector.iter().zip(back.iter()) {            assert!((a - b).abs() <= a.abs() / 1024.0 + 1e-7, "{a} came back as {b}");        }        assert_eq!(decode(&encode(&[1.0, -2.0, 0.0, 65504.0])), Some(vec![1.0, -2.0, 0.0, 65504.0]));        assert!(f32_of_f16(f16_bits(1e6)).is_infinite());        assert!(f32_of_f16(f16_bits(f32::NAN)).is_nan());        assert_eq!(f32_of_f16(f16_bits(1e-6)), f32_of_f16(f16_bits(1e-6)));        assert!((f32_of_f16(f16_bits(1e-6)) - 1e-6).abs() < 1e-7);    }    /// RULE: Text that is not a vector reads as none, never as a short or zero vector that would match everything.    #[test]    fn text_that_is_not_a_vector_reads_as_none() {        assert_eq!(decode(""), None);        assert_eq!(decode("not base64!"), None);        assert_eq!(decode("AA=="), None); // one byte    }}