diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs index 1f0b1823..bc047dd8 100644 --- a/control-plane/src/kar_codec.rs +++ b/control-plane/src/kar_codec.rs @@ -33,37 +33,53 @@ pub fn normalize_for_calibration(weights: &[f32], group: u16) -> Result 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()); - } + let scale_bits = normalize_group_into(&weights[start..end], &mut normalized)?; scales.push(scale_bits); - values.extend( - weights[start..end] - .iter() - .map(|value| *value / rounded_scale), - ); - values.resize((group_index + 1) * group, 0.0); + 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 { + 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, /// One f16 reconstruction table per level, from level 1 upward. diff --git a/control-plane/src/kar_sample.rs b/control-plane/src/kar_sample.rs new file mode 100644 index 00000000..2c9917df --- /dev/null +++ b/control-plane/src/kar_sample.rs @@ -0,0 +1,194 @@ +//! Deterministic bounded calibration sampling from a GGUF tensor stream. +//! This is an offline preparation primitive; quality approval is separate. + +use std::io::{Read, Seek}; + +use crate::{gguf_f32_stream, kar_codec}; + +pub const MAX_SAMPLE_VALUES: usize = 65_536; + +pub fn sample_normalized( + reader: &mut R, + absolute_offset: u64, + source_kind: u32, + source_bytes: u64, + elements: u64, + source_digest: [u8; 32], + max_samples: usize, +) -> Result, String> { + if elements == 0 || max_samples == 0 || max_samples > MAX_SAMPLE_VALUES { + return Err("invalid KAR sample size or tensor element count".into()); + } + let padded = elements + .div_ceil(32) + .checked_mul(32) + .ok_or("KAR sampled tensor size overflow")?; + let stride = padded.div_ceil(max_samples as u64); + let seed = u64::from_le_bytes(source_digest[..8].try_into().unwrap()); + let mut targets = + Vec::with_capacity(max_samples.min(usize::try_from(padded).unwrap_or(max_samples))); + let mut bucket = 0u64; + let mut start = 0u64; + while start < padded { + let span = stride.min(padded - start); + targets.push(start + mix64(seed ^ bucket) % span); + start += span; + bucket += 1; + } + let mut sampled = Vec::with_capacity(targets.len()); + let mut group = [0.0f32; 32]; + let mut normalized = [0.0f32; 32]; + let mut filled = 0usize; + let mut position = 0u64; + let mut target_index = 0usize; + let mut seen = 0u64; + let decoded_bytes = gguf_f32_stream::visit( + reader, + absolute_offset, + source_kind, + source_bytes, + |_, f32_bytes| { + for word in f32_bytes.as_chunks::<4>().0 { + if seen >= elements { + return Err("GGUF tensor decodes to more elements than its shape".into()); + } + group[filled] = f32::from_le_bytes(*word); + filled += 1; + seen += 1; + if filled == 32 { + collect_group( + &group, + &mut normalized, + &targets, + &mut target_index, + &mut position, + &mut sampled, + )?; + filled = 0; + } + } + Ok(()) + }, + )?; + if seen != elements || decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? { + return Err("GGUF tensor decoded element count differs from its shape".into()); + } + if filled > 0 { + collect_group( + &group[..filled], + &mut normalized, + &targets, + &mut target_index, + &mut position, + &mut sampled, + )?; + } + if position != padded || target_index != targets.len() { + return Err("KAR calibration sample coverage mismatch".into()); + } + Ok(sampled) +} + +fn collect_group( + weights: &[f32], + normalized: &mut [f32; 32], + targets: &[u64], + target_index: &mut usize, + position: &mut u64, + sample: &mut Vec, +) -> Result<(), String> { + kar_codec::normalize_group_into(weights, normalized)?; + for value in normalized { + if targets.get(*target_index) == Some(position) { + sample.push(*value); + *target_index += 1; + } + *position += 1; + } + Ok(()) +} + +fn mix64(mut value: u64) -> u64 { + value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); + value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + value ^ (value >> 31) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::iq3_s; + use std::io::Cursor; + + #[test] + fn small_sample_matches_existing_full_tensor_normalization() { + let weights = (0..33) + .map(|number| (number as f32 - 16.0) / 8.0) + .collect::>(); + let bytes = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let sample = sample_normalized( + &mut Cursor::new(bytes.clone()), + 0, + 0, + bytes.len() as u64, + weights.len() as u64, + [7; 32], + 64, + ) + .unwrap(); + assert_eq!( + sample, + kar_codec::normalize_for_calibration(&weights, 32) + .unwrap() + .values + ); + } + + #[test] + fn large_sample_is_bounded_and_deterministic() { + let weights = (0..2048) + .map(|number| (number as f32 - 1024.0) / 1024.0) + .collect::>(); + let bytes = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let run = || { + sample_normalized( + &mut Cursor::new(&bytes), + 0, + 0, + bytes.len() as u64, + 2048, + [3; 32], + 32, + ) + .unwrap() + }; + assert_eq!(run(), run()); + assert_eq!(run().len(), 32); + } + + #[test] + fn iq3_sampling_stays_bounded_across_source_chunks() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let source = block.repeat(257); + let sample = sample_normalized( + &mut Cursor::new(&source), + 0, + 21, + source.len() as u64, + (257 * iq3_s::BLOCK_ELEMENTS) as u64, + [9; 32], + 64, + ) + .unwrap(); + assert_eq!(sample.len(), 64); + assert!(sample.iter().all(|value| *value == 1.0)); + } +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index e23d8697..ce2f4e9d 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -10,6 +10,7 @@ mod iq3s_grid; pub mod kar; pub mod kar_codec; pub mod kar_fixture; +pub mod kar_sample; pub mod kar_writer; pub mod model; pub mod model_pipeline; diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 485f3610..797571b1 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -30,6 +30,8 @@ KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be The native `gguf_f32_stream` visitor now yields source bytes and derived little-endian F32 bytes in bounded chunks for F32, F16, BF16, and IQ3_S tensors. The sharded identity path uses it, so the next full-model encoder can consume decoded tensor values without allocating a whole source tensor. This removes one memory bottleneck; calibration, encoded-section streaming, and verification on real target shards remain to implement. The small preview limits remain in effect. +The experimental `kar_sample` primitive normalizes these streamed values in reusable groups of 32 with the same rounded f16 scale logic as the existing codec. It takes at most 65,536 values from deterministic, digest-seeded positions spread across the padded tensor. A small tensor sampled at every position matches the existing full-tensor normalization exactly. This is a bounded calibration input, not a validated rate policy; the encoded-section writer, per-class policy, and real-model quality gate remain open. + ## GPU path For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim.