Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

feat(vector): wire opt-in scalar8 (SQ8) quantization into the kNN serving path

xerj-org66fefbd090b0
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index bc615b1e9..eebb4ac58 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -10612,6 +10612,33 @@ fn es_properties_to_fields(properties: &Value) -> Vec<FieldConfig> {
// ES default similarity for dense_vector with index: true.
fc.options.similarity = Some("cosine".to_string());
}
+
+ // Opt-in scalar8 (SQ8) quantization. ES expresses this via
+ // `index_options.type`: the `int8_*` families are 8-bit scalar
+ // quantized, which we map to our serving-path SQ8 code store. A
+ // direct `quantization` string on the field def is also honoured
+ // (and overrides). Only `scalar8` changes the serving path — every
+ // other family (hnsw/flat/bbq*/int4*) keeps the exact f32 scan, so
+ // we leave `quantization` unset (None) for them and default
+ // behaviour stays byte-identical.
+ let mut quant: Option<String> = None;
+ if let Some(io_type) = field_def
+ .get("index_options")
+ .and_then(|io| io.get("type"))
+ .and_then(Value::as_str)
+ {
+ if matches!(io_type, "int8_hnsw" | "int8_flat") {
+ quant = Some("scalar8".to_string());
+ }
+ }
+ if let Some(q) = field_def.get("quantization").and_then(Value::as_str) {
+ match q {
+ "scalar8" | "int8" => quant = Some("scalar8".to_string()),
+ "none" => quant = None,
+ _ => {}
+ }
+ }
+ fc.options.quantization = quant;
}
fields.push(fc);
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index 9105b443b..5124eab33 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -182,14 +182,18 @@ impl Config {
));
}
- // Vector: dense_vector quantization is not implemented. The quantizer
- // types exist in xerj-vector but are not wired into the HNSW index
- // build/query path, so any scheme other than `none` would store full
- // float32 vectors while claiming a memory saving.
- if self.vector.default_quantization != VectorQuantization::None {
+ // Vector: `scalar8` (SQ8) quantization is now wired into the kNN
+ // serving path (`Index::run_knn_brute_force`): a `scalar8` dense_vector
+ // field keeps a per-field u8 code store (1 byte/dim vs 4) and scores
+ // candidates by decoding those codes, giving a real ~4× reduction on
+ // that field's vector working set. `none` and `scalar8` are therefore
+ // accepted. `binary` (1-bit) has no implemented quantizer, so honouring
+ // it would silently store full-precision vectors while claiming a 32×
+ // saving — it stays rejected until a BinaryQuantizer lands.
+ if self.vector.default_quantization == VectorQuantization::Binary {
return Err(XerjError::config(
- "vector.default_quantization: vector quantization is not implemented in this \
- build; only \"none\" is supported",
+ "vector.default_quantization: binary (1-bit) quantization is not implemented in \
+ this build; only \"none\" and \"scalar8\" are supported",
));
}
@@ -536,17 +540,22 @@ pub struct VectorConfig {
/// Can be overridden per query. Must be ≥ the number of neighbours
/// requested (`k`).
pub hnsw_ef_search: usize,
- /// Default quantization: `"none"` (default). `"scalar8"` / `"binary"` are
- /// **not implemented in this build** and are rejected at startup.
+ /// Default quantization: `"none"` (default) or `"scalar8"`. `"binary"` is
+ /// **not implemented in this build** and is rejected at startup.
///
/// - `"none"` — full float32 vectors (highest accuracy, most memory).
- /// - `"scalar8"` — 8-bit scalar quantization (~4× memory reduction) — NOT YET IMPLEMENTED.
- /// - `"binary"` — 1-bit binary quantization (~32× memory reduction) — NOT YET IMPLEMENTED.
+ /// - `"scalar8"` — 8-bit scalar quantization (~4× memory reduction) — WIRED
+ /// into the kNN serving path. A `scalar8` dense_vector field keeps a
+ /// per-field u8 code store (1 byte/dim) and scores candidates by decoding
+ /// those codes, so the memory saving is real, not cosmetic. Typically
+ /// opted into per field via `index_options.type: int8_hnsw` on the
+ /// mapping; this global default applies the same scheme index-wide.
+ /// - `"binary"` — 1-bit binary quantization (~32× memory reduction) — NOT
+ /// YET IMPLEMENTED (no `BinaryQuantizer` exists).
///
- /// The quantizer types exist in `xerj-vector` but are not wired into the
- /// index build/query path, so honouring `scalar8`/`binary` would silently
- /// store full-precision vectors while claiming a memory saving. Until the
- /// wiring lands, only `none` is accepted (see `Config::validate`).
+ /// Honouring `binary` would silently store full-precision vectors while
+ /// claiming a saving, so only `none` and `scalar8` are accepted (see
+ /// `Config::validate`).
pub default_quantization: VectorQuantization,
/// Maximum supported vector dimensionality (default: `16384`).
pub max_dimensions: usize,
@@ -968,18 +977,17 @@ mod tests {
}
#[test]
- fn quantization_scalar8_rejected() {
- let result = Config::from_toml_str(
+ fn quantization_scalar8_accepted() {
+ // scalar8 (SQ8) is now wired into the kNN serving path, so it must be
+ // accepted at startup (no longer a silent-fake rejection).
+ let cfg = Config::from_toml_str(
r#"
[vector]
default_quantization = "scalar8"
"#,
- );
- let err = result.expect_err("scalar8 quantization must be rejected as unimplemented");
- assert!(
- err.to_string().contains("not implemented"),
- "error should explain quantization is unimplemented, got: {err}"
- );
+ )
+ .expect("scalar8 quantization must be accepted now that it is wired");
+ assert_eq!(cfg.vector.default_quantization, VectorQuantization::Scalar8);
}
#[test]
diff --git a/engine/crates/xerj-common/src/types.rs b/engine/crates/xerj-common/src/types.rs
index 671625b67..0151664c8 100644
--- a/engine/crates/xerj-common/src/types.rs
+++ b/engine/crates/xerj-common/src/types.rs
@@ -241,6 +241,14 @@ pub struct FieldOptions {
/// Similarity metric override for this vector field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub similarity: Option<String>,
+ /// Vector quantization scheme for this dense_vector field.
+ ///
+ /// `Some("scalar8")` opts this field into the serving-path SQ8 code store
+ /// (1 byte/dim, ~4× memory reduction); `None`/absent keeps the exact
+ /// full-precision f32 brute-force path. Set from the mapping's
+ /// `index_options.type` (`int8_hnsw`/`int8_flat` → `scalar8`) in es_compat.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub quantization: Option<String>,
/// Null value to substitute when the field is missing from a document.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub null_value: Option<serde_json::Value>,
@@ -270,6 +278,7 @@ impl Default for FieldOptions {
term_positions: true,
dimensions: None,
similarity: None,
+ quantization: None,
null_value: None,
multi_value: true,
boost: 1.0,
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 0ac87e16f..8a095c8f2 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -31,6 +31,7 @@ use xerj_storage::segment::SectionType;
use xerj_storage::wal::{SyncMode, WalEntry};
use xerj_vector::distance::DistanceMetric;
use xerj_vector::hnsw::{HnswIndex, HnswParams};
+use xerj_vector::Sq8Params;
use crate::aggs::run_aggs_with_all;
@@ -315,6 +316,45 @@ impl RequestCacheSeen {
}
}
+// ── SQ8 serving-path code store ───────────────────────────────────────────────
+
+/// Per-field in-memory SQ8 (scalar8) code store used by the kNN serving path.
+///
+/// Holds one shared [`Sq8Params`] (fitted from the first ~1000 ingested
+/// vectors for the field) plus a `doc_id -> Vec<u8>` code map. Each code vector
+/// is 1 byte per dimension — a quarter of the 4 bytes/dim an f32 vector costs —
+/// so this is the concrete artifact behind the ~4× memory claim. The store is
+/// consulted by [`Index::run_knn_brute_force`] instead of reading the f32
+/// vector from `_source` for scoring.
+struct Sq8FieldStore {
+ /// Shared per-dimension min/scale codec for this field.
+ params: Sq8Params,
+ /// Vector dimensionality the params were fitted for.
+ dim: usize,
+ /// Whether vectors were L2-normalised before quantising (cosine fields).
+ normalize: bool,
+ /// doc_id → SQ8 codes (1 byte/dim).
+ codes: HashMap<String, Vec<u8>>,
+}
+
+impl Sq8FieldStore {
+ /// Total bytes held by the u8 code map — the working set we shrank 4×.
+ fn code_bytes(&self) -> usize {
+ self.codes.values().map(|c| c.len()).sum()
+ }
+}
+
+/// L2-normalise a vector in place (no-op for a zero vector). Used for cosine
+/// fields so SQ8 fits over bounded per-dimension ranges (better recall).
+fn l2_normalize_vec(v: &mut [f32]) {
+ let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if norm > 0.0 {
+ for x in v.iter_mut() {
+ *x /= norm;
+ }
+ }
+}
+
// ── Index ────────────────────────────────────────────────────────────────────
/// Per-index coordinator.
@@ -368,6 +408,18 @@ pub struct Index {
hnsw_id_rev: Arc<RwLock<HashMap<u64, String>>>,
/// Monotonic counter for HNSW node IDs.
hnsw_next_id: Arc<AtomicU64>,
+ /// Per-field SQ8 (scalar8) code stores for the kNN serving path.
+ ///
+ /// Keyed by dense_vector field name. Populated only for fields whose
+ /// mapping opts into `scalar8` quantization (`index_options.type:
+ /// int8_hnsw`). Each store holds one shared [`Sq8Params`] plus a
+ /// `doc_id -> Vec<u8>` code map (1 byte/dim, NOT 4), giving a real ~4×
+ /// reduction on that field's vector working set. Built lazily on the first
+ /// kNN over the field from the same (doc_id, source) candidates the
+ /// brute-force scan already gathers, then refreshed incrementally as new
+ /// docs appear. Default (none) fields never touch this map, so their exact
+ /// f32 brute-force path is byte-identical to before.
+ sq8_stores: Arc<RwLock<HashMap<String, Sq8FieldStore>>>,
// ── Per-index concurrency control ─────────────────────────────────────────
/// Semaphore that limits the number of queries executing concurrently
/// against this index. The default is 64 permits, matching the global
@@ -735,6 +787,7 @@ impl Index {
hnsw_id_map: Arc::new(RwLock::new(HashMap::new())),
hnsw_id_rev: Arc::new(RwLock::new(HashMap::new())),
hnsw_next_id: Arc::new(AtomicU64::new(1)),
+ sq8_stores: Arc::new(RwLock::new(HashMap::new())),
metric_query_count: Arc::new(AtomicU64::new(0)),
metric_query_total_ms: Arc::new(AtomicU64::new(0)),
metric_index_count: Arc::new(AtomicU64::new(0)),
@@ -909,6 +962,7 @@ impl Index {
hnsw_id_map: Arc::new(RwLock::new(id_map_init)),
hnsw_id_rev: Arc::new(RwLock::new(id_rev_init)),
hnsw_next_id: Arc::new(AtomicU64::new(next_id_init)),
+ sq8_stores: Arc::new(RwLock::new(HashMap::new())),
metric_query_count: Arc::new(AtomicU64::new(0)),
metric_query_total_ms: Arc::new(AtomicU64::new(0)),
metric_index_count: Arc::new(AtomicU64::new(0)),
@@ -3379,35 +3433,135 @@ impl Index {
}
}
+ // ── Determine whether this field opts into SQ8 (scalar8) ──────
+ // Default fields keep the exact f32 brute-force scan below,
+ // byte-identical to before. A `scalar8` field instead scores against
+ // a per-field u8 code store — decoding each doc's SQ8 codes rather
+ // than reading its f32 vector from `_source` for scoring.
+ let use_sq8 = {
+ let schema = self.schema.read().await;
+ lookup_vector_quantization(&schema.schema, field).as_deref() == Some("scalar8")
+ };
+
// ── Score each candidate against the query vector ─────────────
let mut scored: Vec<(String, f32, Value)> = Vec::with_capacity(candidates.len());
- for (id, src) in candidates {
- // Apply filter: if the filter doesn't match this doc, skip.
- if let Some(ref f) = filter {
- let mut src_with_id = src.clone();
- if let Some(obj) = src_with_id.as_object_mut() {
- obj.insert("_id".to_string(), Value::String(id.clone()));
+ if use_sq8 {
+ // Cosine fields are L2-normalised before quantising so SQ8 fits
+ // over bounded [-1,1] per-dim ranges (much better recall); cosine
+ // is invariant to that scaling so ranking stays correct. Non-cosine
+ // metrics must keep raw magnitudes, so they are quantised as-is.
+ let normalize = !matches!(similarity, "l2_norm" | "dot_product" | "max_inner_product");
+ let dim = query_vec.len();
+
+ // Post-filter candidate vectors for this field: (id, src, doc_vec).
+ let mut cand: Vec<(String, Value, Vec<f32>)> = Vec::with_capacity(candidates.len());
+ for (id, src) in candidates {
+ if let Some(ref f) = filter {
+ let mut src_with_id = src.clone();
+ if let Some(obj) = src_with_id.as_object_mut() {
+ obj.insert("_id".to_string(), Value::String(id.clone()));
+ }
+ if !doc_matches_query(f, &src_with_id) {
+ continue;
+ }
}
- if !doc_matches_query(f, &src_with_id) {
+ let vec_val = match get_field_value(&src, field) {
+ Some(v) => v,
+ None => continue,
+ };
+ let mut doc_vec: Vec<f32> = match &vec_val {
+ Value::Array(arr) => arr
+ .iter()
+ .filter_map(|v| v.as_f64().map(|f| f as f32))
+ .collect(),
+ _ => continue,
+ };
+ if doc_vec.len() != dim {
continue;
}
+ if normalize {
+ l2_normalize_vec(&mut doc_vec);
+ }
+ cand.push((id, src, doc_vec));
}
- let vec_val = match get_field_value(&src, field) {
- Some(v) => v,
- None => continue,
- };
- let doc_vec: Vec<f32> = match &vec_val {
- Value::Array(arr) => arr
- .iter()
- .filter_map(|v| v.as_f64().map(|f| f as f32))
- .collect(),
- _ => continue,
- };
- if doc_vec.len() != query_vec.len() {
- continue;
+
+ // Build/refresh the per-field SQ8 code store: fit params once from
+ // the first ≤1000 vectors, then encode any doc not yet stored. The
+ // store holds u8 codes (1 byte/dim), so its steady-state footprint
+ // is ~4× smaller than the f32 vectors it replaces for scoring.
+ {
+ let mut stores = self.sq8_stores.write().await;
+ let store = stores.entry(field.to_string()).or_insert_with(|| {
+ let sample: Vec<Vec<f32>> =
+ cand.iter().take(1000).map(|(_, _, v)| v.clone()).collect();
+ let params = Sq8Params::fit(&sample, dim);
+ Sq8FieldStore {
+ params,
+ dim,
+ normalize,
+ codes: HashMap::new(),
+ }
+ });
+ if store.dim == dim {
+ for (id, _src, v) in cand.iter() {
+ if !store.codes.contains_key(id) {
+ store.codes.insert(id.clone(), store.params.encode(v));
+ }
+ }
+ debug!(
+ field,
+ docs = store.codes.len(),
+ code_bytes = store.code_bytes(),
+ f32_bytes = store.codes.len() * store.dim * std::mem::size_of::<f32>(),
+ normalize = store.normalize,
+ "SQ8 code store refreshed"
+ );
+ }
+ }
+
+ // Score by DECODING the stored SQ8 codes (never the raw f32).
+ let stores = self.sq8_stores.read().await;
+ if let Some(store) = stores.get(field) {
+ let mut decoded = vec![0.0f32; store.dim];
+ for (id, src, _v) in cand {
+ let codes = match store.codes.get(&id) {
+ Some(c) if c.len() == store.dim => c,
+ _ => continue,
+ };
+ store.params.decode_into(codes, &mut decoded);
+ let score = compute_vector_similarity(similarity, query_vec, &decoded);
+ scored.push((id, score, src));
+ }
+ }
+ } else {
+ for (id, src) in candidates {
+ // Apply filter: if the filter doesn't match this doc, skip.
+ if let Some(ref f) = filter {
+ let mut src_with_id = src.clone();
+ if let Some(obj) = src_with_id.as_object_mut() {
+ obj.insert("_id".to_string(), Value::String(id.clone()));
+ }
+ if !doc_matches_query(f, &src_with_id) {
+ continue;
+ }
+ }
+ let vec_val = match get_field_value(&src, field) {
+ Some(v) => v,
+ None => continue,
+ };
+ let doc_vec: Vec<f32> = match &vec_val {
+ Value::Array(arr) => arr
+ .iter()
+ .filter_map(|v| v.as_f64().map(|f| f as f32))
+ .collect(),
+ _ => continue,
+ };
+ if doc_vec.len() != query_vec.len() {
+ continue;
+ }
+ let score = compute_vector_similarity(similarity, query_vec, &doc_vec);
+ scored.push((id, score, src));
}
- let score = compute_vector_similarity(similarity, query_vec, &doc_vec);
- scored.push((id, score, src));
}
// ── Rank, cap the candidate pool at k, then paginate ──────────
@@ -11287,6 +11441,33 @@ fn lookup_vector_similarity(schema: &Schema, field: &str) -> String {
.unwrap_or_else(|| "cosine".to_string())
}
+/// Look up the quantization scheme declared for a dense_vector `field`.
+///
+/// Returns `Some("scalar8")` only for fields that opted into SQ8 (via
+/// `index_options.type: int8_hnsw` at mapping time); `None` for every default
+/// full-precision field. Mirrors [`lookup_vector_similarity`]'s dotted-path
+/// descent so nested vector fields resolve correctly.
+fn lookup_vector_quantization(schema: &Schema, field: &str) -> Option<String> {
+ fn find<'a>(fields: &'a [FieldConfig], path: &[&str]) -> Option<&'a FieldConfig> {
+ if path.is_empty() {
+ return None;
+ }
+ let head = path[0];
+ let tail = &path[1..];
+ for fc in fields {
+ if fc.name == head {
+ if tail.is_empty() {
+ return Some(fc);
+ }
+ return find(&fc.fields, tail);
+ }
+ }
+ None
+ }
+ let parts: Vec<&str> = field.split('.').collect();
+ find(&schema.fields, &parts).and_then(|fc| fc.options.quantization.clone())
+}
+
/// Rewrite a query by resolving any field aliases to their canonical field names.
///
/// Traverses the query tree, replacing alias field names with their target paths.
diff --git a/engine/crates/xerj-vector/src/lib.rs b/engine/crates/xerj-vector/src/lib.rs
index 7605cbdee..994be0c2e 100644
--- a/engine/crates/xerj-vector/src/lib.rs
+++ b/engine/crates/xerj-vector/src/lib.rs
@@ -15,7 +15,9 @@ pub mod search;
pub use distance::{compute_distance, cosine, dot_product, l2_squared, DistanceMetric};
pub use hnsw::{HnswIndex, HnswParams};
-pub use quantizer::{NoneQuantizer, QuantizedData, QuantizedVectors, Quantizer, Scalar8Quantizer};
+pub use quantizer::{
+ NoneQuantizer, QuantizedData, QuantizedVectors, Quantizer, Scalar8Quantizer, Sq8Params,
+};
pub use search::{SearchResult, VectorSearcher};
pub use xerj_common::Result;
diff --git a/engine/crates/xerj-vector/src/quantizer.rs b/engine/crates/xerj-vector/src/quantizer.rs
index 72ff4e9e6..8aecc8662 100644
--- a/engine/crates/xerj-vector/src/quantizer.rs
+++ b/engine/crates/xerj-vector/src/quantizer.rs
@@ -5,6 +5,7 @@
//! during graph traversal, with optional re-ranking using full-precision
//! vectors for the final top-K.
+use serde::{Deserialize, Serialize};
use xerj_common::XerjError;
/// Result alias.
@@ -307,6 +308,112 @@ impl Quantizer for Scalar8Quantizer {
}
}
+// ─────────────────────────────────────────────────────────────────────────────
+// Sq8Params — serializable serving-path scalar8 codec
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Serializable per-dimension scalar-quantization (SQ8) parameters.
+///
+/// This is the serving-path counterpart to [`Scalar8Quantizer`]: instead of
+/// packing a whole batch into one blob, it exposes a fitted codec that the
+/// engine keeps *per dense_vector field*. The engine stores one shared
+/// `Sq8Params` (fitted from the first ~1000 ingested vectors for the field)
+/// plus a `doc_id -> Vec<u8>` code map, so the brute-force kNN scan reads
+/// **1 byte/dim** instead of the 4 bytes/dim an f32 vector costs — a ~4×
+/// reduction on the quantized field's vector working set.
+///
+/// `mins[d]`/`scales[d]` are the per-dimension minimum and range (`max-min`)
+/// observed in the fitting sample. `encode` maps `v[d]` linearly to a u8 in
+/// `[0,255]`; `decode` reverses it. A zero scale (constant dimension) encodes
+/// to 0 and decodes back to `min`. The encode/decode math is bit-for-bit
+/// identical to [`Scalar8Quantizer`]'s private `encode_dim`/`decode_dim`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Sq8Params {
+ /// Per-dimension minimum value.
+ pub mins: Vec<f32>,
+ /// Per-dimension scale (`max - min`).
+ pub scales: Vec<f32>,
+}
+
+impl Sq8Params {
+ /// Fit per-dimension min/max over `sample`.
+ ///
+ /// `dim` is the required vector dimensionality; sample vectors of a
+ /// different length are skipped. If no usable vector is present the
+ /// params degenerate to zero scale (every code becomes 0, decoding to 0).
+ pub fn fit(sample: &[Vec<f32>], dim: usize) -> Sq8Params {
+ let mut mins = vec![f32::MAX; dim];
+ let mut maxs = vec![f32::MIN; dim];
+ let mut seen = false;
+ for v in sample {
+ if v.len() != dim {
+ continue;
+ }
+ seen = true;
+ for (d, &x) in v.iter().enumerate() {
+ if x < mins[d] {
+ mins[d] = x;
+ }
+ if x > maxs[d] {
+ maxs[d] = x;
+ }
+ }
+ }
+ if !seen {
+ mins = vec![0.0; dim];
+ maxs = vec![0.0; dim];
+ }
+ let scales = mins
+ .iter()
+ .zip(maxs.iter())
+ .map(|(&mn, &mx)| mx - mn)
+ .collect();
+ Sq8Params { mins, scales }
+ }
+
+ /// Vector dimensionality this codec was fitted for.
+ #[inline]
+ pub fn dim(&self) -> usize {
+ self.mins.len()
+ }
+
+ /// Encode a full-precision vector to one u8 per dimension.
+ #[inline]
+ pub fn encode(&self, v: &[f32]) -> Vec<u8> {
+ v.iter()
+ .enumerate()
+ .map(|(d, &x)| {
+ let min = self.mins.get(d).copied().unwrap_or(0.0);
+ let scale = self.scales.get(d).copied().unwrap_or(0.0);
+ if scale == 0.0 {
+ return 0u8;
+ }
+ let normalized = (x - min) / scale;
+ (normalized * 255.0).round().clamp(0.0, 255.0) as u8
+ })
+ .collect()
+ }
+
+ /// Decode a code slice back to approximate f32 values (allocating).
+ #[inline]
+ pub fn decode(&self, codes: &[u8]) -> Vec<f32> {
+ let mut out = vec![0.0f32; codes.len()];
+ self.decode_into(codes, &mut out);
+ out
+ }
+
+ /// Decode into a caller-provided buffer, avoiding per-score allocation on
+ /// the hot kNN scan. `out` must be at least `codes.len()` long.
+ #[inline]
+ pub fn decode_into(&self, codes: &[u8], out: &mut [f32]) {
+ for (d, &b) in codes.iter().enumerate() {
+ let min = self.mins.get(d).copied().unwrap_or(0.0);
+ let scale = self.scales.get(d).copied().unwrap_or(0.0);
+ out[d] = min + (b as f32 / 255.0) * scale;
+ }
+ }
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Scalar4Quantizer
// ─────────────────────────────────────────────────────────────────────────────
@@ -588,4 +695,141 @@ mod tests {
"scalar4 ({bytes4} B) should be ~50% of scalar8 ({bytes8} B)"
);
}
+
+ // ── Sq8Params (serving-path codec) ────────────────────────────────────────
+
+ /// Tiny deterministic xorshift RNG so the recall/memory tests are
+ /// reproducible without pulling in the `rand` crate.
+ struct XorShift(u64);
+ impl XorShift {
+ fn next_u64(&mut self) -> u64 {
+ let mut x = self.0;
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ self.0 = x;
+ x
+ }
+ /// Standard-normal-ish sample via sum of 4 uniforms (CLT), in ~[-2,2].
+ fn next_gauss(&mut self) -> f32 {
+ let mut s = 0.0f32;
+ for _ in 0..4 {
+ s += (self.next_u64() as f64 / u64::MAX as f64) as f32;
+ }
+ s - 2.0 // mean 0
+ }
+ }
+
+ fn l2_normalize(v: &mut [f32]) {
+ let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if norm > 0.0 {
+ for x in v.iter_mut() {
+ *x /= norm;
+ }
+ }
+ }
+
+ fn cosine_sim(a: &[f32], b: &[f32]) -> f32 {
+ let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
+ let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
+ let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if na > 0.0 && nb > 0.0 {
+ dot / (na * nb)
+ } else {
+ 0.0
+ }
+ }
+
+ /// (b) MEMORY: the SQ8 code store is ~4× smaller than the f32 equivalent.
+ #[test]
+ fn sq8_store_is_quarter_of_f32() {
+ let n = 2000usize;
+ let dim = 128usize;
+ let mut rng = XorShift(0x1234_5678_9abc_def0);
+ let vecs: Vec<Vec<f32>> = (0..n)
+ .map(|_| {
+ let mut v: Vec<f32> = (0..dim).map(|_| rng.next_gauss()).collect();
+ l2_normalize(&mut v);
+ v
+ })
+ .collect();
+ let params = Sq8Params::fit(&vecs, dim);
+ let code_bytes: usize = vecs.iter().map(|v| params.encode(v).len()).sum();
+ // params overhead is 2 * dim * 4 bytes, shared across all N vectors.
+ let params_bytes = (params.mins.len() + params.scales.len()) * std::mem::size_of::<f32>();
+ let f32_bytes = n * dim * std::mem::size_of::<f32>();
+ let ratio = f32_bytes as f64 / (code_bytes + params_bytes) as f64;
+ println!(
+ "SQ8 memory: f32={f32_bytes}B codes={code_bytes}B params={params_bytes}B ratio={ratio:.3}x"
+ );
+ assert!(
+ ratio >= 3.5,
+ "SQ8 store should be >=3.5x smaller than f32, got {ratio:.3}x"
+ );
+ }
+
+ /// (c) RECALL: scalar8 serving-path scoring keeps recall@10 >= 0.90 vs the
+ /// exact (none) path over >=2000 vectors / >=100 queries at dim>=64.
+ #[test]
+ fn sq8_recall_at_10_above_090() {
+ let n = 2000usize;
+ let dim = 128usize;
+ let k = 10usize;
+ let queries = 100usize;
+ let mut rng = XorShift(0xdead_beef_cafe_0001);
+
+ // Corpus, L2-normalized (cosine convention, as the serving path does).
+ let corpus: Vec<Vec<f32>> = (0..n)
+ .map(|_| {
+ let mut v: Vec<f32> = (0..dim).map(|_| rng.next_gauss()).collect();
+ l2_normalize(&mut v);
+ v
+ })
+ .collect();
+
+ // Fit params from the first 1000 vectors (mirrors the engine's sample).
+ let sample: Vec<Vec<f32>> = corpus.iter().take(1000).cloned().collect();
+ let params = Sq8Params::fit(&sample, dim);
+ let codes: Vec<Vec<u8>> = corpus.iter().map(|v| params.encode(v)).collect();
+
+ let mut recall_sum = 0.0f64;
+ let mut decoded = vec![0.0f32; dim];
+ for _ in 0..queries {
+ let q: Vec<f32> = (0..dim).map(|_| rng.next_gauss()).collect();
+
+ // Exact (ground truth) top-k by cosine on the raw f32 corpus.
+ let mut exact: Vec<(usize, f32)> = corpus
+ .iter()
+ .enumerate()
+ .map(|(i, v)| (i, cosine_sim(&q, v)))
+ .collect();
+ exact.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
+ let truth: std::collections::HashSet<usize> =
+ exact.iter().take(k).map(|(i, _)| *i).collect();
+
+ // Approximate top-k by cosine on the DECODED SQ8 codes.
+ let mut approx: Vec<(usize, f32)> = codes
+ .iter()
+ .enumerate()
+ .map(|(i, c)| {
+ params.decode_into(c, &mut decoded);
+ (i, cosine_sim(&q, &decoded))
+ })
+ .collect();
+ approx.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
+
+ let hit = approx
+ .iter()
+ .take(k)
+ .filter(|(i, _)| truth.contains(i))
+ .count();
+ recall_sum += hit as f64 / k as f64;
+ }
+ let mean_recall = recall_sum / queries as f64;
+ println!("SQ8 recall@{k}: {mean_recall:.4} over {queries} queries / {n} vectors dim={dim}");
+ assert!(
+ mean_recall >= 0.90,
+ "SQ8 recall@{k} should be >=0.90, got {mean_recall:.4}"
+ );
+ }
}