Extracted helpers: ReqCtx::new, Profile::gateway, RuntimeServer::new, props, Generate::line, Http::request, read_events, parse_macos, parse_nvidia, validate_nested_slices, sample_windows, tool_markup, count_input_tokens, model_control_prelude, vision fetch, admit, decode_tensor_row, Registry::observe, provenance_value, decode_source_tensor, service_install parse, provision prepare, provision arguments, write_group, pool relay. Test ids: 543 before and after, 0 missing, 0 outcome changes; warnings in the two crates 0. Counts (strata-control / strata-desktop-core), functions over 30 lines / complexity 10 / nesting 4 / wide lines: prod 187/135/17/196 -> 166/130/17/194 and 81/59/6/54 -> 77/59/6/54; test unchanged (214/17/30/133, 65/3/3/27).
265 lines
8.9 KiB
Rust
265 lines
8.9 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)?;
|
|
write_bytes(scales, &scale.to_le_bytes())?;
|
|
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;
|
|
accumulate_error(f64::from(*original), f64::from(rebuilt), error_sum, reference_sum);
|
|
}
|
|
}
|
|
write_plane_words(planes, words)
|
|
}
|
|
|
|
/// Add one weight's squared reconstruction error and squared magnitude to the running sums.
|
|
fn accumulate_error(original: f64, rebuilt: f64, error_sum: &mut f64, reference_sum: &mut f64) {
|
|
let delta = original - rebuilt;
|
|
*error_sum += delta * delta;
|
|
*reference_sum += original.powi(2);
|
|
}
|
|
|
|
/// One 32-bit word per level plane, little endian.
|
|
fn write_plane_words(planes: &mut [BufWriter<File>], words: [u32; 8]) -> Result<(), String> {
|
|
for (writer, word) in planes.iter_mut().zip(words) {
|
|
write_bytes(writer, &word.to_le_bytes())?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn write_bytes(writer: &mut BufWriter<File>, bytes: &[u8]) -> Result<(), String> {
|
|
writer.write_all(bytes).map_err(|error| error.to_string())
|
|
}
|
|
|
|
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;
|