Files
leleka/control-plane/src/kar_codec.rs
T
Pavlo Ratushnyi a498381cb7
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 5m16s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 5m19s
Linux / linux-static-cli (pull_request) Failing after 7m35s
Linux / release-cli (pull_request) Skipped
refactor(model): extract independent Rust IQ3 decoding core
2026-10-07 20:53:25 +02:00

461 lines
17 KiB
Rust

//! Experimental KAR scalar calibration, bit-plane encoding, and CPU decoding.
//! The caller selects samples and lossy rates; serving does not enable this path.
pub struct EncodedPlanes {
pub scales: Vec<u16>,
/// Plane zero is the most significant index bit. Bit m of word w belongs
/// to weight 32*w+m, matching the koference CUDA decoder.
pub planes: Vec<Vec<u32>>,
pub padded_elements: usize,
}
pub struct NormalizedTensor {
pub scales: Vec<u16>,
pub values: Vec<f32>,
}
/// Normalize one finite f32 tensor using the exact rounded f16 group scales
/// that the KAR decoder will later multiply back in.
pub fn normalize_for_calibration(weights: &[f32], group: u16) -> Result<NormalizedTensor, String> {
let group = usize::from(group);
if weights.is_empty()
|| group == 0
|| group > 1024
|| !group.is_multiple_of(32)
|| weights.iter().any(|value| !value.is_finite())
{
return Err("invalid KAR normalization input".into());
}
let padded = weights
.len()
.div_ceil(group)
.checked_mul(group)
.ok_or("KAR encoder padded size overflow")?;
let mut scales = Vec::with_capacity(padded / group);
let mut values = Vec::with_capacity(padded);
let mut normalized = vec![0.0f32; group];
for group_index in 0..padded / group {
let start = group_index * group;
let end = (start + group).min(weights.len());
let scale_bits = normalize_group_into(&weights[start..end], &mut normalized)?;
scales.push(scale_bits);
values.extend_from_slice(&normalized);
}
Ok(NormalizedTensor { scales, values })
}
/// Normalize one nonempty group into reusable, padded storage.
pub fn normalize_group_into(weights: &[f32], output: &mut [f32]) -> Result<u16, String> {
if weights.is_empty()
|| weights.len() > output.len()
|| output.is_empty()
|| output.len() > 1024
|| !output.len().is_multiple_of(32)
|| weights.iter().any(|value| !value.is_finite())
{
return Err("invalid KAR normalization input".into());
}
let maximum = weights
.iter()
.map(|value| value.abs())
.fold(0.0f32, f32::max);
if maximum > 65504.0 || (maximum != 0.0 && maximum < f32::from_bits(0x3380_0000)) {
return Err("KAR scale overflows or underflows f16".into());
}
let scale = if maximum == 0.0 {
f32::from_bits(0x3380_0000)
} else {
maximum
};
let scale_bits = f32_to_f16_bits(scale);
let rounded_scale = f16_bits_to_f32(scale_bits);
if !rounded_scale.is_finite() || rounded_scale == 0.0 {
return Err("KAR rounded scale is invalid".into());
}
for (position, value) in output.iter_mut().enumerate() {
*value = weights
.get(position)
.map_or(0.0, |weight| *weight / rounded_scale);
}
Ok(scale_bits)
}
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())
{
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(
scales: &[u16],
book: &[u16],
planes: &[&[u32]],
group: u16,
start: usize,
output: &mut [f32],
) -> Result<(), String> {
let group = usize::from(group);
if group == 0
|| group > 1024
|| !group.is_multiple_of(32)
|| !(1..=16).contains(&planes.len())
|| book.len() != 1usize << planes.len()
{
return Err("invalid KAR decoder geometry or book".into());
}
let padded = scales
.len()
.checked_mul(group)
.ok_or("KAR decoder padded size overflow")?;
let end = start
.checked_add(output.len())
.ok_or("KAR decoder range overflow")?;
if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) {
return Err("KAR decoder range or plane length is invalid".into());
}
if scales[start / group..end.div_ceil(group)]
.iter()
.any(|bits| bits & 0x7c00 == 0x7c00)
|| book.iter().any(|bits| bits & 0x7c00 == 0x7c00)
{
return Err("KAR decoder received non-finite f16 data".into());
}
for (relative, value) in output.iter_mut().enumerate() {
let position = start + relative;
let mut index = 0usize;
for plane in planes {
let bit = (plane[position / 32] >> (position % 32)) & 1;
index = (index << 1) | bit as usize;
}
*value = f16_bits_to_f32(book[index]) * f16_bits_to_f32(scales[position / group]);
}
Ok(())
}
pub fn encode_with_boundaries(
weights: &[f32],
group: u16,
boundaries: &[f32],
levels: u8,
) -> Result<EncodedPlanes, String> {
if !(1..=16).contains(&levels) || boundaries.len() != (1usize << levels) - 1 {
return Err("invalid KAR encoder shape or calibration".into());
}
if boundaries.iter().any(|value| !value.is_finite())
|| boundaries.windows(2).any(|pair| pair[0] >= pair[1])
{
return Err("KAR encoder needs increasing finite boundaries".into());
}
let normalized = normalize_for_calibration(weights, group)?;
let padded = normalized.values.len();
let words = padded / 32;
let mut planes = vec![vec![0u32; words]; usize::from(levels)];
for (position, value) in normalized.values.iter().enumerate() {
// NumPy searchsorted defaults to side='left': equality stays in
// the lower cell, as in koference's reference encoder.
let index = boundaries.partition_point(|boundary| *boundary < *value);
for (level, plane) in planes.iter_mut().enumerate() {
let bit = (index >> (usize::from(levels) - 1 - level)) & 1;
plane[position / 32] |= (bit as u32) << (position % 32);
}
}
Ok(EncodedPlanes {
scales: normalized.scales,
planes,
padded_elements: padded,
})
}
// IEEE-754 round-to-nearest, ties-to-even conversion, independent of host
// f16 support so the Linux control binary and offline oracle agree.
pub fn f32_to_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 & 0x7f_ffff;
if exponent == 255 {
return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 };
}
let half_exponent = exponent - 127 + 15;
if half_exponent >= 31 {
return sign | 0x7c00;
}
if half_exponent <= 0 {
if half_exponent < -10 {
return sign;
}
let significand = mantissa | 0x80_0000;
let shift = (14 - half_exponent) as u32;
let rounded =
(significand + ((1u32 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift;
return sign | rounded as u16;
}
let rounded = mantissa + 0x0fff + ((mantissa >> 13) & 1);
if rounded & 0x80_0000 != 0 {
return sign | (((half_exponent + 1) as u16) << 10);
}
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 use leleka_quant_core::f16_bits_to_f32;
#[cfg(test)]
mod tests {
use super::*;
use crate::{kar, kar_writer};
use sha2::{Digest, Sha256};
use std::fs;
#[test]
fn f16_rounding_and_subnormals_match_ieee_examples() {
for (value, bits) in [
(0.0, 0x0000),
(-0.0, 0x8000),
(1.0, 0x3c00),
(-2.0, 0xc000),
(65504.0, 0x7bff),
(f32::from_bits(0x3380_0000), 0x0001),
] {
assert_eq!(f32_to_f16_bits(value), bits);
assert_eq!(f16_bits_to_f32(bits), value);
}
assert_eq!(f32_to_f16_bits(f32::from_bits(0x3300_0000)), 0);
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),
(0x4198_4a5a, 0x4cc2),
(0x3477_febd, 0x0004),
(0x417f_f3d3, 0x4c00),
(0xbe5d_73a8, 0xb2ec),
(0x365d_0d88, 0x0037),
(0xc0b3_076e, 0xc598),
(0x3e8a_8af9, 0x3454),
] {
assert_eq!(f32_to_f16_bits(f32::from_bits(float_bits)), half_bits);
}
}
#[test]
fn calibrated_planes_follow_koference_word_order_and_write_kar() {
let weights = [-1.0, -0.25, 0.25, 1.0].repeat(8);
let encoded = encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap();
assert_eq!(encoded.scales, [0x3c00]);
assert_eq!(encoded.planes, [vec![0xcccc_cccc], vec![0xaaaa_aaaa]]);
assert_eq!(encoded.padded_elements, 32);
let book1 = [0xb800, 0x3800];
let book2 = [0xba00, 0xb400, 0x3400, 0x3a00];
let books: [&[u16]; 2] = [&book1, &book2];
let planes = encoded.planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let mut decoded = [0.0f32; 5];
decode_range(&encoded.scales, &book2, &planes, 32, 3, &mut decoded).unwrap();
assert_eq!(decoded, [0.75, -0.75, -0.25, 0.25, 0.75]);
decode_range(&encoded.scales, &book1, &planes[..1], 32, 3, &mut decoded).unwrap();
assert_eq!(decoded, [0.5, -0.5, -0.5, 0.5, 0.5]);
assert!(decode_range(&encoded.scales, &book2, &planes, 32, 31, &mut decoded).is_err());
let source = kar_writer::SourceIdentity {
name: "synthetic",
architecture: "qwen35",
builder: "strata-next-experimental",
digest: Sha256::digest(b"source").into(),
total_elements: 32,
bytes: 6,
};
let tensor = [kar_writer::Tensor {
name: "expert",
dims: &[32],
source_dtype: 0,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &encoded.scales,
books: &books,
planes: &planes,
},
}];
let path = std::env::temp_dir().join(format!("strata-codec-{}.kar", std::process::id()));
let _ = fs::remove_file(&path);
kar_writer::write_archive(&path, &source, &tensor).unwrap();
assert_eq!(kar::verify(&path).unwrap().tensor_count, 1);
let archived = kar::decode_preview_tensor(&path, "expert", 2).unwrap();
assert_eq!(&archived[3..8], &[0.75, -0.75, -0.25, 0.25, 0.75]);
assert_eq!(kar::f32_fnv1a64(&[1.0]), 0x4b72_477f_9c5c_2f98);
let coarse = kar::decode_preview_tensor(&path, "expert", 1).unwrap();
assert_eq!(&coarse[3..8], &[0.5, -0.5, -0.5, 0.5, 0.5]);
assert!(kar::decode_preview_tensor(&path, "expert", 3).is_err());
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
]
);
}
}