Files
leleka/crates/kar-codec/src/lib.rs
T

363 lines
14 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 (scale_bits, rounded_scale) = group_scale(weights)?;
for (position, value) in output.iter_mut().enumerate() {
*value = weights.get(position).map_or(0.0, |weight| *weight / rounded_scale);
}
Ok(scale_bits)
}
/// The f16 scale bits of a group and the scale they round to.
fn group_scale(weights: &[f32]) -> Result<(u16, f32), String> {
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());
}
Ok((scale_bits, rounded_scale))
}
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 boundaries = split_boundaries(&sorted, levels)?;
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 books = level_books(&sorted, &boundaries, levels);
Ok(Calibration { boundaries, books })
}
/// Prefix sums of the values and of their squares (one leading zero).
fn prefix_sums(sorted: &[f64]) -> (Vec<f64>, Vec<f64>) {
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);
}
(sums, squares)
}
/// Prefix sums over a sorted sample, for the split search.
struct Prefix<'a> {
sorted: &'a [f64],
sums: Vec<f64>,
squares: Vec<f64>,
}
impl Prefix<'_> {
/// The best split point of the cell `lo..hi` by least squared error, if the values allow one.
fn best_split(&self, lo: usize, hi: usize) -> Option<(usize, f64)> {
let (sorted, sums, squares) = (self.sorted, &self.sums, &self.squares);
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));
}
}
best
}
}
/// The cell boundaries of `levels` rounds of halving every cell (unsorted).
fn split_boundaries(sorted: &[f64], levels: u8) -> Result<Vec<f32>, String> {
let (sums, squares) = prefix_sums(sorted);
let prefix = Prefix { sorted, sums, squares };
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 best = prefix.best_split(lo, hi);
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;
}
Ok(boundaries)
}
/// One f16 reconstruction table per level, from level 1 upward.
fn level_books(sorted: &[f64], boundaries: &[f32], levels: u8) -> Vec<Vec<u16>> {
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 = pair_sums(&counts);
totals = pair_sums(&totals);
}
}
books
}
/// Adds neighbouring pairs (the next coarser level).
fn pair_sums<T: Copy + std::ops::Add<Output = T>>(values: &[T]) -> Vec<T> {
values.as_chunks::<2>().0.iter().map(|pair| pair[0] + pair[1]).collect()
}
/// 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);
check_decoder_input(scales, book, planes, group, start, output.len())?;
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(())
}
/// The geometry, range and finiteness checks of `decode_range`, in its order.
fn check_decoder_input(
scales: &[u16],
book: &[u16],
planes: &[&[u32]],
group: usize,
start: usize,
len: usize,
) -> Result<(), String> {
if !decoder_geometry_ok(book, planes, group) {
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(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());
}
let range = &scales[start / group..end.div_ceil(group)];
if has_non_finite(range) || has_non_finite(book) {
return Err("KAR decoder received non-finite f16 data".into());
}
Ok(())
}
fn decoder_geometry_ok(book: &[u16], planes: &[&[u32]], group: usize) -> bool {
group != 0
&& group <= 1024
&& group.is_multiple_of(32)
&& (1..=16).contains(&planes.len())
&& book.len() == 1usize << planes.len()
}
fn has_non_finite(bits: &[u16]) -> bool {
bits.iter().any(|bits| bits & 0x7c00 == 0x7c00)
}
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 planes = quantize_planes(&normalized.values, boundaries, levels);
Ok(EncodedPlanes {
scales: normalized.scales,
planes,
padded_elements: padded,
})
}
/// One bit plane per level: the cell index of every value, most significant level first.
fn quantize_planes(values: &[f32], boundaries: &[f32], levels: u8) -> Vec<Vec<u32>> {
let words = values.len() / 32;
let mut planes = vec![vec![0u32; words]; usize::from(levels)];
for (position, value) in 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);
}
}
planes
}
// 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;