From 689b4b183f4bc5b105687bda6f0c8f94eef07ffd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 20:36:25 +0200 Subject: [PATCH] Fit experimental KAR top-down codebooks --- control-plane/src/kar_codec.rs | 172 +++++++++++++++++++++++++++++++++ docs/build-validation.md | 1 + docs/compressed-runtime.md | 2 +- docs/roadmap.md | 1 + 4 files changed, 175 insertions(+), 1 deletion(-) diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs index 61f27285..ef0b730e 100644 --- a/control-plane/src/kar_codec.rs +++ b/control-plane/src/kar_codec.rs @@ -9,6 +9,108 @@ pub struct EncodedPlanes { pub padded_elements: usize, } +pub struct Calibration { + pub boundaries: Vec, + /// One f16 reconstruction table per level, from level 1 upward. + pub books: Vec>, +} + +/// Fit koference's top-down nested scalar partitions to an already selected, +/// normalized sample. Sampling policy and rate selection remain external. +pub fn fit_topdown(sample: &[f32], levels: u8) -> Result { + if !(1..=16).contains(&levels) + || sample.len() < (1usize << levels) + || sample + .iter() + .any(|value| !value.is_finite() || !(-1.0..=1.0).contains(value)) + { + return Err("invalid KAR calibration sample or level count".into()); + } + let mut sorted = sample + .iter() + .map(|value| f64::from(*value)) + .collect::>(); + sorted.sort_unstable_by(f64::total_cmp); + let mut sums = Vec::with_capacity(sorted.len() + 1); + let mut squares = Vec::with_capacity(sorted.len() + 1); + sums.push(0.0); + squares.push(0.0); + for value in &sorted { + sums.push(sums.last().copied().unwrap() + value); + squares.push(squares.last().copied().unwrap() + value * value); + } + let mut cells = vec![(0usize, sorted.len())]; + let mut boundaries = Vec::with_capacity((1usize << levels) - 1); + for _ in 0..levels { + let mut next = Vec::with_capacity(cells.len() * 2); + for (lo, hi) in cells { + let mut best = None; + for middle in lo + 1..hi { + if sorted[middle - 1] == sorted[middle] { + continue; + } + let left_count = (middle - lo) as f64; + let right_count = (hi - middle) as f64; + let left_sum = sums[middle] - sums[lo]; + let right_sum = sums[hi] - sums[middle]; + let left_cost = squares[middle] - squares[lo] - left_sum * left_sum / left_count; + let right_cost = + squares[hi] - squares[middle] - right_sum * right_sum / right_count; + let cost = left_cost + right_cost; + if best.is_none_or(|(_, previous)| cost < previous) { + best = Some((middle, cost)); + } + } + let (middle, _) = best.ok_or("KAR calibration sample cannot split every cell")?; + boundaries.push(((sorted[middle - 1] + sorted[middle]) / 2.0) as f32); + next.push((lo, middle)); + next.push((middle, hi)); + } + cells = next; + } + boundaries.sort_unstable_by(f32::total_cmp); + if boundaries.windows(2).any(|pair| pair[0] >= pair[1]) { + return Err("KAR calibration boundaries collapse in f32".into()); + } + let finest = 1usize << levels; + let mut counts = vec![0usize; finest]; + let mut totals = vec![0f64; finest]; + for value in &sorted { + let index = boundaries.partition_point(|boundary| f64::from(*boundary) < *value); + counts[index] += 1; + totals[index] += value; + } + let mut books = vec![Vec::new(); usize::from(levels)]; + for level in (1..=usize::from(levels)).rev() { + books[level - 1] = counts + .iter() + .zip(&totals) + .map(|(count, total)| { + f64_to_f16_bits(if *count == 0 { + 0.0 + } else { + *total / *count as f64 + }) + }) + .collect(); + if level > 1 { + counts = counts + .as_chunks::<2>() + .0 + .iter() + .map(|pair| pair[0] + pair[1]) + .collect(); + totals = totals + .as_chunks::<2>() + .0 + .iter() + .map(|pair| pair[0] + pair[1]) + .collect(); + } + } + Ok(Calibration { boundaries, books }) +} + /// Decode a bounded range from a selected KAR prefix. `book` is the f16 table /// for exactly `planes.len()` levels; `start` is a flat element index. pub fn decode_range( @@ -157,6 +259,35 @@ pub fn f32_to_f16_bits(value: f32) -> u16 { sign | ((half_exponent as u16) << 10) | ((rounded >> 13) as u16) } +fn f64_to_f16_bits(value: f64) -> u16 { + let bits = value.to_bits(); + let sign = ((bits >> 48) & 0x8000) as u16; + let exponent = ((bits >> 52) & 0x7ff) as i32; + let mantissa = bits & 0x000f_ffff_ffff_ffff; + if exponent == 2047 { + return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 }; + } + let half_exponent = exponent - 1023 + 15; + if half_exponent >= 31 { + return sign | 0x7c00; + } + if half_exponent <= 0 { + if half_exponent < -10 { + return sign; + } + let significand = mantissa | 0x0010_0000_0000_0000; + let shift = (43 - half_exponent) as u32; + let rounded = + (significand + ((1u64 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift; + return sign | rounded as u16; + } + let rounded = mantissa + 0x0000_01ff_ffff_ffff + ((mantissa >> 42) & 1); + if rounded & 0x0010_0000_0000_0000 != 0 { + return sign | (((half_exponent + 1) as u16) << 10); + } + sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16) +} + pub fn f16_bits_to_f32(bits: u16) -> f32 { let sign = (u32::from(bits & 0x8000)) << 16; let exponent = (bits >> 10) & 0x1f; @@ -198,6 +329,9 @@ mod tests { assert_eq!(f32_to_f16_bits(f32::from_bits(0x3f80_1000)), 0x3c00); assert_eq!(f32_to_f16_bits(f32::from_bits(0x3f80_3000)), 0x3c02); assert_eq!(f32_to_f16_bits(f32::INFINITY), 0x7c00); + let above_midpoint = 1.0 + 2f64.powi(-11) + 2f64.powi(-40); + assert_eq!(f32_to_f16_bits(above_midpoint as f32), 0x3c00); + assert_eq!(f64_to_f16_bits(above_midpoint), 0x3c01); // Independent Python struct.pack('>(), + [ + 0xbf5d_70a4, + 0xbf11_eb85, + 0xbe66_6667, + 0, + 0x3e5c_28f6, + 0x3f03_d70a, + 0x3f57_0a3e, + ] + ); + assert_eq!( + calibration.books[2], + [ + 0xbbb8, 0xb9cd, 0xb652, 0xae66, 0x2e14, 0x35c3, 0x397b, 0x3ba4 + ] + ); + } } diff --git a/docs/build-validation.md b/docs/build-validation.md index 248f2625..5ad16108 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -84,3 +84,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Added a file-backed NESTED path for already coded KAR sections. A synthetic file-backed section produces the same complete archive bytes as the in-memory writer; corrupted scale, nonzero padding, and wrong section digest each fail before publication. The path streams through 1 MiB and retains no full encoded tensor in RAM. All 35 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source-to-NESTED encoder is still missing, so this does not complete model conversion. - Added an experimental native f32-to-KAR bit-plane encoder with supplied thresholds. A synthetic four-cell pattern produced the koference word layout (`0xcccccccc`, `0xaaaaaaaa`), then passed through the KAR writer and verifier. IEEE f16 scale conversion tests include the smallest subnormal and ties-to-even. All 37 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Calibration fitting, IQ3_S decoding, bounded source conversion, and full-model quality remain open. - Added bounded CPU prefix decoding for the synthetic tensor: a five-value slice reconstructed at levels 1 and 2 exactly as the supplied f16 books specify, and an out-of-range slice was rejected. This oracle has not yet been compared with the koference GPU decoder on hardware. +- Ported top-down nested boundary and book fitting for a supplied normalized sample. Two pinned koference Python fixtures match the Rust f32 boundary bits and f16 book values; a degenerate sample is rejected. The f64-to-f16 path avoids double rounding of fitted means. All 38 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This only establishes synthetic calibration parity, not representative model sampling or a quality result. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 51aec3f0..800afb37 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -14,7 +14,7 @@ The Rust `kar_writer` module now emits a KAR-2 container from already coded RAW/ `strata-next model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. The KAR writer can stream both RAW tensor bytes and pre-encoded NESTED sections from files through a 1 MiB buffer. It checks the RAW source digest or NESTED section digest; the latter also checks finite f16 scales/books and zero alignment padding. This is input preparation for a streamed converter; quantized tensors still need a native encoder. -An experimental native `kar_codec::encode_with_boundaries` now converts one in-memory f32 tensor to group scales and MSB-first bit planes using externally calibrated nested boundaries. It rounds scales to IEEE f16 before assigning cells and uses the same bit-within-u32 order as koference's CUDA decoder. `kar_codec::decode_range` reconstructs a selected prefix into a caller-sized CPU buffer, giving a small numerical oracle for later CUDA checks. The encoder does not fit codebooks, decode IQ3_S source blocks, choose a rate, or enable a lossy path for serving. The full converter still needs bounded per-tensor encoding and calibration provenance. +An experimental native `kar_codec::encode_with_boundaries` converts one in-memory f32 tensor to group scales and MSB-first bit planes using nested boundaries. `kar_codec::fit_topdown` fits those boundaries and f16 books to an already selected normalized sample; pinned synthetic fixtures match koference's Python reference. It rounds scales to IEEE f16 before assigning cells and uses the same bit-within-u32 order as koference's CUDA decoder. `kar_codec::decode_range` reconstructs a selected prefix into a caller-sized CPU buffer, giving a small numerical oracle for later CUDA checks. The encoder does not decode IQ3_S source blocks, choose a model rate, select a representative sample, or enable a lossy path for serving. The full converter still needs bounded per-tensor encoding and calibration provenance. ## GPU path diff --git a/docs/roadmap.md b/docs/roadmap.md index 66acdea5..a092c2e1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -60,6 +60,7 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f - [x] Stream pre-encoded NESTED sections into KAR-2 with checked section geometry, finite f16 values, zero padding, and digest verification. - [x] Encode a synthetic f32 tensor to native KAR scales and bit planes using supplied calibration; keep the lossy path experimental. - [x] Decode a selected KAR bit-plane prefix into a caller-sized CPU buffer for numerical tests. +- [x] Fit experimental top-down nested boundaries and f16 books from a supplied normalized sample; match pinned koference synthetic oracles. - [ ] Feed the native writer from a bounded-memory GGUF tensor iterator and a native KAR encoder; implement `model prepare` on real shards. - [ ] Make one-command `serve` fetch, verify, and prepare missing model assets, then reuse the verified compressed archive. - [ ] Compare KAR reconstruction with its CPU oracle; run full-model quality before making the compressed path a default.