Files
leleka/control-plane/src/kar_sample.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

306 lines
9.7 KiB
Rust

//! 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<R: Read + Seek>(
reader: &mut R,
absolute_offset: u64,
source_kind: u32,
source_bytes: u64,
elements: u64,
source_digest: [u8; 32],
max_samples: usize,
) -> Result<Vec<f32>, 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;
}
if elements > 1_048_576 {
return sample_sparse(
reader,
absolute_offset,
source_kind,
source_bytes,
elements,
&targets,
);
}
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 sample_sparse<R: Read + Seek>(
reader: &mut R,
absolute_offset: u64,
source_kind: u32,
source_bytes: u64,
elements: u64,
targets: &[u64],
) -> Result<Vec<f32>, String> {
let (block_elements, block_bytes) = crate::gguf::block_geometry(source_kind)
.ok_or("unsupported GGUF source kind for KAR sampling")?;
if !elements.is_multiple_of(block_elements)
|| elements / block_elements * block_bytes != source_bytes
{
return Err("KAR sampling source geometry differs from tensor shape".into());
}
let mut sampled = Vec::with_capacity(targets.len());
let mut normalized = [0.0f32; 32];
let mut previous_group = None;
for &target in targets {
let group_start = target / 32 * 32;
if previous_group != Some(group_start) {
let count = (elements - group_start).min(32);
let first_block = group_start / block_elements;
let block_offset = first_block
.checked_mul(block_bytes)
.ok_or("KAR sample block offset overflow")?;
let skip = group_start % block_elements;
let blocks = (skip + count).div_ceil(block_elements);
let bytes = blocks
.checked_mul(block_bytes)
.ok_or("KAR sample byte count overflow")?;
let mut values = Vec::with_capacity((blocks * block_elements * 4) as usize);
gguf_f32_stream::visit(
reader,
absolute_offset
.checked_add(block_offset)
.ok_or("KAR sample absolute offset overflow")?,
source_kind,
bytes,
|_, f32_bytes| {
values.extend_from_slice(f32_bytes);
Ok(())
},
)?;
let begin = usize::try_from(skip * 4).map_err(|error| error.to_string())?;
let end = usize::try_from((skip + count) * 4).map_err(|error| error.to_string())?;
let group = values[begin..end]
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word))
.collect::<Vec<_>>();
kar_codec::normalize_group_into(&group, &mut normalized)?;
previous_group = Some(group_start);
}
sampled.push(normalized[(target - group_start) as usize]);
}
Ok(sampled)
}
fn collect_group(
weights: &[f32],
normalized: &mut [f32; 32],
targets: &[u64],
target_index: &mut usize,
position: &mut u64,
sample: &mut Vec<f32>,
) -> 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::<Vec<_>>();
let bytes = weights
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<_>>();
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::<Vec<_>>();
let bytes = weights
.iter()
.flat_map(|value| value.to_le_bytes())
.collect::<Vec<_>>();
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));
}
#[test]
fn sparse_sampling_matches_complete_stream_for_f32_and_iq3() {
let f32_bytes = (0..2048)
.flat_map(|number| ((number as f32 - 1024.0) / 1024.0).to_le_bytes())
.collect::<Vec<_>>();
let mut iq3_block = [0u8; iq3_s::BLOCK_BYTES];
iq3_block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let iq3_bytes = iq3_block.repeat(17);
for (kind, bytes, elements) in [(0, f32_bytes, 2048u64), (21, iq3_bytes, 4352u64)] {
let seed = u64::from_le_bytes([11; 8]);
let padded = elements.div_ceil(32) * 32;
let stride = padded.div_ceil(64);
let targets = (0..padded.div_ceil(stride))
.map(|bucket| {
let start = bucket * stride;
start + mix64(seed ^ bucket) % stride.min(padded - start)
})
.collect::<Vec<_>>();
let full = sample_normalized(
&mut Cursor::new(&bytes),
0,
kind,
bytes.len() as u64,
elements,
[11; 32],
64,
)
.unwrap();
let sparse = sample_sparse(
&mut Cursor::new(&bytes),
0,
kind,
bytes.len() as u64,
elements,
&targets,
)
.unwrap();
assert_eq!(sparse, full);
}
}
}