scripts/dev/extract_tests.py moves a trailing cfg(test) mod tests block into foo/tests.rs for 118 files of leleka-runtime, cuda-driver, control-plane, gateway-text, deploy and nine smaller crates (31,000 lines), leaving production code and test ids untouched; 22 files that are themselves loaded through a path attribute carry an explicit path to their tests file. Not touched: the files the kar-off-ab branch edits (backend.rs, backend_original_serve.rs, backend_original_serve_replay.rs, qwen4exp_resident_expert_source.rs and seven deploy files). Verified: cargo check --all-targets for the whole workspace on x86_64 Linux and on the Windows host; the 2429 library unit-test ids of the workspace are identical before and after (Linux listing diff empty); the loadable sections of leleka-inference, leleka-daemon, leleka-cli and strata-next are byte-identical between a release build before and after (scripts/dev/elf-sections-equal.sh), so the shipped code is the same. The architecture ratchets exclude tests.rs from the path-include count; the baseline drops from 329 to 311 oversize files and from 302,000 to 273,600 lines.
255 lines
8.4 KiB
Rust
255 lines
8.4 KiB
Rust
//! Bounded-memory KAR-2 section encoder. Calibration is supplied explicitly;
|
|
//! this module does not approve a lossy rate or a serving configuration.
|
|
|
|
use std::{
|
|
fs::{self, File, OpenOptions},
|
|
io::{BufWriter, Read, Seek, SeekFrom, Write},
|
|
path::Path,
|
|
};
|
|
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use crate::{gguf_f32_stream, kar_codec};
|
|
|
|
pub struct SectionResult {
|
|
pub bytes: u64,
|
|
pub digest: [u8; 32],
|
|
pub source_digest: [u8; 32],
|
|
pub derived_digest: [u8; 32],
|
|
pub relative_l2: f64,
|
|
}
|
|
|
|
pub fn encode_section<R: Read + Seek>(
|
|
reader: &mut R,
|
|
absolute_offset: u64,
|
|
source_kind: u32,
|
|
source_bytes: u64,
|
|
elements: u64,
|
|
calibration: &kar_codec::Calibration,
|
|
destination: &Path,
|
|
) -> Result<SectionResult, String> {
|
|
let levels = calibration.books.len();
|
|
if elements == 0
|
|
|| !(1..=8).contains(&levels)
|
|
|| calibration.boundaries.len() != (1usize << levels) - 1
|
|
|| calibration
|
|
.boundaries
|
|
.iter()
|
|
.any(|boundary| !boundary.is_finite())
|
|
|| calibration
|
|
.boundaries
|
|
.windows(2)
|
|
.any(|pair| pair[0] >= pair[1])
|
|
|| calibration.books.iter().enumerate().any(|(index, book)| {
|
|
book.len() != 1usize << (index + 1) || book.iter().any(|bits| bits & 0x7c00 == 0x7c00)
|
|
})
|
|
{
|
|
return Err("invalid streamed KAR calibration".into());
|
|
}
|
|
let words = elements.div_ceil(32);
|
|
let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?;
|
|
let books_start = round_up(scales_bytes, 16)?;
|
|
let books_bytes = (1u64 << (levels + 2)) - 4;
|
|
let planes_start = round_up(
|
|
books_start
|
|
.checked_add(books_bytes)
|
|
.ok_or("KAR books overflow")?,
|
|
16,
|
|
)?;
|
|
let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?;
|
|
if plane_stride > u32::MAX as u64 {
|
|
return Err("KAR plane stride exceeds format limit".into());
|
|
}
|
|
let section_bytes = round_up(
|
|
planes_start
|
|
.checked_add(
|
|
plane_stride
|
|
.checked_mul(levels as u64)
|
|
.ok_or("KAR planes overflow")?,
|
|
)
|
|
.ok_or("KAR section overflow")?,
|
|
256,
|
|
)?;
|
|
let section = OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(destination)
|
|
.map_err(|error| error.to_string())?;
|
|
let result = (|| -> Result<SectionResult, String> {
|
|
section
|
|
.set_len(section_bytes)
|
|
.map_err(|error| error.to_string())?;
|
|
let mut scale_writer = writer_at(destination, 0)?;
|
|
let mut plane_writers = (0..levels)
|
|
.map(|level| writer_at(destination, planes_start + level as u64 * plane_stride))
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
let mut pending = [0.0f32; 32];
|
|
let mut filled = 0usize;
|
|
let mut seen = 0u64;
|
|
let mut groups = 0u64;
|
|
let mut error_sum = 0.0f64;
|
|
let mut reference_sum = 0.0f64;
|
|
let mut source_hash = Sha256::new();
|
|
let mut derived_hash = Sha256::new();
|
|
let decoded_bytes = gguf_f32_stream::visit(
|
|
reader,
|
|
absolute_offset,
|
|
source_kind,
|
|
source_bytes,
|
|
|raw, f32_bytes| {
|
|
source_hash.update(raw);
|
|
derived_hash.update(f32_bytes);
|
|
for word in f32_bytes.as_chunks::<4>().0 {
|
|
if seen >= elements {
|
|
return Err("GGUF tensor decodes beyond its shape".into());
|
|
}
|
|
pending[filled] = f32::from_le_bytes(*word);
|
|
filled += 1;
|
|
seen += 1;
|
|
if filled == 32 {
|
|
write_group(
|
|
&pending,
|
|
calibration,
|
|
&mut scale_writer,
|
|
&mut plane_writers,
|
|
&mut error_sum,
|
|
&mut reference_sum,
|
|
)?;
|
|
filled = 0;
|
|
groups += 1;
|
|
}
|
|
}
|
|
Ok(())
|
|
},
|
|
)?;
|
|
if seen != elements
|
|
|| decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|
|
{
|
|
return Err("GGUF decoded tensor shape mismatch".into());
|
|
}
|
|
if filled != 0 {
|
|
write_group(
|
|
&pending[..filled],
|
|
calibration,
|
|
&mut scale_writer,
|
|
&mut plane_writers,
|
|
&mut error_sum,
|
|
&mut reference_sum,
|
|
)?;
|
|
groups += 1;
|
|
}
|
|
if groups != words {
|
|
return Err("KAR encoded group count mismatch".into());
|
|
}
|
|
scale_writer.flush().map_err(|error| error.to_string())?;
|
|
for writer in &mut plane_writers {
|
|
writer.flush().map_err(|error| error.to_string())?;
|
|
}
|
|
drop(scale_writer);
|
|
drop(plane_writers);
|
|
let mut book_writer = writer_at(destination, books_start)?;
|
|
for book in &calibration.books {
|
|
for bits in book {
|
|
book_writer
|
|
.write_all(&bits.to_le_bytes())
|
|
.map_err(|error| error.to_string())?;
|
|
}
|
|
}
|
|
book_writer.flush().map_err(|error| error.to_string())?;
|
|
drop(book_writer);
|
|
section.sync_all().map_err(|error| error.to_string())?;
|
|
let digest = hash_file(destination)?;
|
|
let relative_l2 = if reference_sum == 0.0 {
|
|
error_sum.sqrt()
|
|
} else {
|
|
(error_sum / reference_sum).sqrt()
|
|
};
|
|
Ok(SectionResult {
|
|
bytes: section_bytes,
|
|
digest,
|
|
source_digest: source_hash.finalize().into(),
|
|
derived_digest: derived_hash.finalize().into(),
|
|
relative_l2,
|
|
})
|
|
})();
|
|
drop(section);
|
|
if result.is_err() {
|
|
let _ = fs::remove_file(destination);
|
|
}
|
|
result
|
|
}
|
|
|
|
fn write_group(
|
|
weights: &[f32],
|
|
calibration: &kar_codec::Calibration,
|
|
scales: &mut BufWriter<File>,
|
|
planes: &mut [BufWriter<File>],
|
|
error_sum: &mut f64,
|
|
reference_sum: &mut f64,
|
|
) -> Result<(), String> {
|
|
let mut normalized = [0.0f32; 32];
|
|
let scale = kar_codec::normalize_group_into(weights, &mut normalized)?;
|
|
scales
|
|
.write_all(&scale.to_le_bytes())
|
|
.map_err(|error| error.to_string())?;
|
|
let mut words = [0u32; 8];
|
|
let final_book = calibration.books.last().ok_or("missing KAR codebook")?;
|
|
let rounded_scale = kar_codec::f16_bits_to_f32(scale);
|
|
for (position, value) in normalized.iter().enumerate() {
|
|
let index = calibration
|
|
.boundaries
|
|
.partition_point(|boundary| *boundary < *value);
|
|
for (level, word) in words[..planes.len()].iter_mut().enumerate() {
|
|
let bit = (index >> (planes.len() - 1 - level)) & 1;
|
|
*word |= (bit as u32) << position;
|
|
}
|
|
if let Some(original) = weights.get(position) {
|
|
let rebuilt = kar_codec::f16_bits_to_f32(final_book[index]) * rounded_scale;
|
|
let delta = f64::from(*original) - f64::from(rebuilt);
|
|
*error_sum += delta * delta;
|
|
*reference_sum += f64::from(*original).powi(2);
|
|
}
|
|
}
|
|
for (writer, word) in planes.iter_mut().zip(words) {
|
|
writer
|
|
.write_all(&word.to_le_bytes())
|
|
.map_err(|error| error.to_string())?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn writer_at(path: &Path, offset: u64) -> Result<BufWriter<File>, String> {
|
|
let mut file = OpenOptions::new()
|
|
.write(true)
|
|
.open(path)
|
|
.map_err(|error| error.to_string())?;
|
|
file.seek(SeekFrom::Start(offset))
|
|
.map_err(|error| error.to_string())?;
|
|
Ok(BufWriter::with_capacity(64 * 1024, file))
|
|
}
|
|
|
|
fn round_up(value: u64, alignment: u64) -> Result<u64, String> {
|
|
value
|
|
.div_ceil(alignment)
|
|
.checked_mul(alignment)
|
|
.ok_or("KAR section offset overflow".into())
|
|
}
|
|
|
|
fn hash_file(path: &Path) -> Result<[u8; 32], String> {
|
|
let mut file = File::open(path).map_err(|error| error.to_string())?;
|
|
let mut hash = Sha256::new();
|
|
let mut buffer = [0u8; 1024 * 1024];
|
|
loop {
|
|
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
hash.update(&buffer[..count]);
|
|
}
|
|
Ok(hash.finalize().into())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|