Fit experimental KAR top-down codebooks

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 20:36:25 +02:00
parent 5b9604765a
commit 689b4b183f
4 changed files with 175 additions and 1 deletions
+172
View File
@@ -9,6 +9,108 @@ pub struct EncodedPlanes {
pub padded_elements: usize,
}
pub struct Calibration {
pub boundaries: Vec<f32>,
/// One f16 reconstruction table per level, from level 1 upward.
pub books: Vec<Vec<u16>>,
}
/// 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<Calibration, String> {
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::<Vec<_>>();
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('<e') oracle, seeded f32 bit samples.
for (float_bits, half_bits) in [
(0xb148_141c, 0x8000),
@@ -260,4 +394,42 @@ mod tests {
assert_eq!(kar::verify(&path).unwrap().tensor_count, 1);
fs::remove_file(path).unwrap();
}
#[test]
fn topdown_calibration_matches_pinned_koference_oracle() {
// koference 806d2398, kar_codec.nested_books(sample, 2, "topdown").
let sample = [-1.0, -0.75, -0.25, -0.1, 0.1, 0.25, 0.75, 1.0];
let calibration = fit_topdown(&sample, 2).unwrap();
assert_eq!(calibration.boundaries, [-0.5, 0.0, 0.5]);
assert_eq!(calibration.books[0], [0xb833, 0x3833]);
assert_eq!(calibration.books[1], [0xbb00, 0xb19a, 0x319a, 0x3b00]);
assert!(fit_topdown(&[0.0; 8], 2).is_err());
let varied = [
-1.0, -0.93, -0.8, -0.65, -0.49, -0.3, -0.15, -0.05, 0.05, 0.14, 0.29, 0.43, 0.6, 0.77,
0.91, 1.0,
];
let calibration = fit_topdown(&varied, 3).unwrap();
assert_eq!(
calibration
.boundaries
.iter()
.map(|v| v.to_bits())
.collect::<Vec<_>>(),
[
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
]
);
}
}
+1
View File
@@ -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.
+1 -1
View File
@@ -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
+1
View File
@@ -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.