Files
leleka/crates/kar-codec/src/lib.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 b3274c1130
Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Failing after 8s
Desktop foundation / core (ubuntu-latest) (push) Failing after 11s
Rust port / port-oracles (push) Failing after 11s
Rust port / port-linux-tests (push) Failing after 14s
Rust port / port-fast (push) Failing after 9s
Linux / verify (push) Failing after 17s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Merge claude/port-gpu-bringup (CUDA runtime port, upstream sync) into main
Brings the Rust/CUDA port of the Strata mode17 serve path together with the
CPU/iGPU/NPU gpt-oss runtime that main gained meanwhile.

Control plane: the Qwen tokenizer is the implementation behind the Qwen35
variant of codec::TextCodec (qwen(), encode_prompt() widen the trait; QwenCodec
derefs to the tokenizer), so control-token marks, images, chat template, the
runtime backend and vision keep their behavior, while the gpt-oss/Harmony path
and the worker pool keep main's. Config carries the union of fields; extra_workers
is rejected together with runtime, lazy_load, idle_unload_s and vision; the
gpt-oss family refuses top_k/min_p/penalties (its GEN line has no such keys).
leleka-kar-codec takes f16_bits_to_f32 from leleka-quant-core (identical code).
Workspace members and default-members are the union of both sides.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:32:33 +01:00

327 lines
12 KiB
Rust

//! KAR scalar calibration, bit-plane encoding, and CPU decoding (moved from `control-plane/src/kar_codec.rs`,
//! whose archive tests still cover it). Experimental: 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)
}
pub 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;