//! What has to hold: the bytes are 512 of them, the round trip loses less than //! the gap between two genuinely different results, and quantising is stable //! under anything that does not change a vector's DIRECTION — because direction //! is all cosine similarity reads. use super::*; /// A deterministic pseudo-random vector — an LCG, so no test depends on a seed /// anybody has to trust. The same one the TypeScript test uses, so the two /// suites are looking at the same numbers. fn vector(seed: u32, dims: usize) -> Vec { let mut state = seed; (0..dims) .map(|_| { state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); f64::from(state) / f64::from(0xffff_ffffu32) - 0.5 }) .collect() } fn full(seed: u32) -> Vec { vector(seed, EMBED_DIMS) } fn dot(a: &[f64], b: &[f64]) -> f64 { a.iter().zip(b).map(|(x, y)| x * y).sum() } fn length(values: &[f64]) -> f64 { dot(values, values).sqrt() } fn signed(bytes: &[u8]) -> Vec { bytes.iter().map(|b| *b as i8).collect() } // ── normalizeUnit ──────────────────────────────────────────────────────────── #[test] fn returns_a_unit_length_vector() { let unit = normalize_unit(&full(1)).expect("512 finite dimensions"); assert!((length(&unit) - 1.0).abs() < 1e-12); } #[test] fn keeps_direction_so_a_multiple_normalises_the_same_way() { let values = full(2); let scaled: Vec = values.iter().map(|v| v * 37.0).collect(); let a = normalize_unit(&scaled).expect("512 finite dimensions"); let b = normalize_unit(&values).expect("512 finite dimensions"); // To float precision, not bit-for-bit: dividing by a different norm rounds // differently. What matters is that quantising them lands on the same byte, // which the scale-invariance test below asserts exactly. for (x, y) in a.iter().zip(&b) { assert!((x - y).abs() < 1e-12); } } #[test] fn refuses_a_vector_with_the_wrong_number_of_dimensions() { assert_eq!( normalize_unit(&vector(3, 1536)), Err(QuantizeError::Dimensions(1536)) ); assert_eq!(normalize_unit(&[]), Err(QuantizeError::Dimensions(0))); assert!(normalize_unit(&vector(3, 1536)) .unwrap_err() .to_string() .contains("1536 dimensions, expected 512")); } /// It has no direction; its dot product with everything is zero, so stored it /// would be a chunk that silently never matches anything. #[test] fn refuses_a_zero_vector_rather_than_storing_512_zero_bytes() { assert_eq!( normalize_unit(&vec![0.0; EMBED_DIMS]), Err(QuantizeError::ZeroLength) ); } #[test] fn refuses_a_non_finite_component() { let mut broken = full(4); broken[17] = f64::NAN; assert_eq!(normalize_unit(&broken), Err(QuantizeError::NonFinite)); broken[17] = f64::INFINITY; assert_eq!(normalize_unit(&broken), Err(QuantizeError::NonFinite)); } // ── quantizeEmbedding ──────────────────────────────────────────────────────── #[test] fn is_exactly_one_byte_per_dimension() { assert_eq!( quantize_embedding(&full(5)) .expect("a well-shaped vector") .len(), EMBED_VECTOR_BYTES ); assert_eq!(EMBED_VECTOR_BYTES, EMBED_DIMS); } #[test] fn is_deterministic_and_scale_invariant() { let values = full(6); let once = quantize_embedding(&values).expect("a well-shaped vector"); assert_eq!( quantize_embedding(&values).expect("a well-shaped vector"), once ); let tiny: Vec = values.iter().map(|v| v * 0.001).collect(); assert_eq!( quantize_embedding(&tiny).expect("a well-shaped vector"), once ); } /// The reason the scale is 127 and not 128: -128 has no positive twin, and an /// asymmetric range would give the dot product a direction-dependent bias. #[test] fn maps_a_negated_vector_to_the_exact_opposite_bytes() { let values = full(7); let positive = signed(&quantize_embedding(&values).expect("a well-shaped vector")); let negated: Vec = values.iter().map(|v| -v).collect(); let opposite = signed(&quantize_embedding(&negated).expect("a well-shaped vector")); let expected: Vec = positive .iter() .map(|b| if *b == 0 { 0 } else { -*b }) .collect(); assert_eq!(opposite, expected); } #[test] fn puts_a_saturated_axis_at_the_scale_never_past_it() { let mut axis = vec![0.0; EMBED_DIMS]; axis[0] = 4.2; let restored = dequantize_embedding(&quantize_embedding(&axis).expect("a well-shaped vector")) .expect("512 bytes"); assert_eq!(restored[0] * EMBED_QUANTIZE_SCALE, EMBED_QUANTIZE_SCALE); assert_eq!(restored[1], 0.0); } #[test] fn quantize_refuses_the_wrong_number_of_dimensions() { assert_eq!( quantize_embedding(&vector(8, 256)), Err(QuantizeError::Dimensions(256)) ); } // ── dequantizeEmbedding ────────────────────────────────────────────────────── #[test] fn round_trips_to_within_half_a_quantisation_step_per_component() { let unit = normalize_unit(&full(9)).expect("512 finite dimensions"); let restored = dequantize_embedding(&quantize_embedding(&unit).expect("a well-shaped vector")) .expect("512 bytes"); for (a, b) in restored.iter().zip(&unit) { assert!((a - b).abs() <= 0.5 / EMBED_QUANTIZE_SCALE + 1e-12); } } #[test] fn perturbs_the_vectors_length_by_well_under_a_percent() { for seed in [10, 11, 12, 13] { let restored = dequantize_embedding(&quantize_embedding(&full(seed)).expect("a well-shaped vector")) .expect("512 bytes"); assert!((length(&restored) - 1.0).abs() < 0.01, "seed {seed}"); } } #[test] fn refuses_a_blob_that_is_not_a_whole_vector() { assert_eq!( dequantize_embedding(&vec![0u8; 511]), Err(QuantizeError::VectorBytes(511)) ); assert_eq!( dequantize_embedding(&[]), Err(QuantizeError::VectorBytes(0)) ); assert_eq!( dequantize_embedding(&vec![0u8; 511]) .unwrap_err() .to_string(), "stored vector is 511 bytes, expected 512" ); } /// A driver may hand back a view into a shared buffer; reading it must honour /// the offset rather than starting at zero. (In TypeScript that is a real trap /// — an `Int8Array` over a `Uint8Array`'s buffer starts at byte 0 unless the /// offset is passed. In Rust a subslice carries its own bounds, so this is the /// proof of a property rather than the guard against a bug.) #[test] fn reads_a_vector_out_of_a_larger_buffer_without_reading_its_neighbours() { let one = quantize_embedding(&full(14)).expect("a well-shaped vector"); let mut packed = vec![0u8; EMBED_VECTOR_BYTES * 2]; packed[EMBED_VECTOR_BYTES..].copy_from_slice(&one); assert_eq!( dequantize_embedding(&packed[EMBED_VECTOR_BYTES..]), dequantize_embedding(&one) ); } // ── the approximation is faithful enough to rank with ──────────────────────── /// The lane's own arithmetic lands with the lane. What this asserts is the /// property the lane will rest on: quantisation reorders near-ties, not results /// a person could tell apart. #[test] fn orders_candidates_by_the_quantised_dot_product_the_way_float_cosine_does() { let query = normalize_unit(&full(100)).expect("512 finite dimensions"); let candidates: Vec> = (0..24) .map(|i| { // Mix each candidate with the query in a different proportion, so // the true similarities are spread out rather than clustered. let noise = normalize_unit(&full(200 + i)).expect("512 finite dimensions"); let mix = 0.15 + f64::from(i) * 0.03; let mixed: Vec = query .iter() .zip(&noise) .map(|(q, n)| q * mix + n * (1.0 - mix)) .collect(); normalize_unit(&mixed).expect("512 finite dimensions") }) .collect(); let quantised = |values: &[f64]| -> Vec { dequantize_embedding(&quantize_embedding(values).expect("a well-shaped vector")) .expect("512 bytes") }; let query_q = quantised(&query); let exact: Vec = candidates.iter().map(|c| dot(&query, c)).collect(); let approximate: Vec = candidates .iter() .map(|c| dot(&query_q, &quantised(c))) .collect(); let rank = |scores: &[f64]| -> Vec { let mut order: Vec = (0..scores.len()).collect(); order.sort_by(|a, b| scores[*b].total_cmp(&scores[*a])); order }; assert_eq!(rank(&approximate), rank(&exact)); // And every similarity is within the quantisation noise of the true one. for (a, b) in approximate.iter().zip(&exact) { assert!((a - b).abs() < 0.01); } } // ── the declared width ────────────────────────────────────────────────────── /// `EMBED_DIMS` was declared here and in /// `packages/store/src/schema/embeddings.ts`, and a test read that file by path /// to hold the two equal. Step 5i deleted the package, so the constant below is /// the declaration. What survives is the pin on its VALUE: the width is written /// into every stored vector, and changing it silently would make every /// embedding already on disk unreadable. #[test] fn the_dimensions_are_the_declared_width() { assert_eq!(EMBED_DIMS, 512); assert_eq!(EMBED_VECTOR_BYTES, EMBED_DIMS); }