//! 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, gguf_f32_stream::TensorSpan, 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( reader: &mut R, span: TensorSpan, calibration: &kar_codec::Calibration, destination: &Path, ) -> Result { layout::check_calibration(calibration, span.elements)?; let layout = layout::section_layout(span.elements, calibration.books.len())?; let section = create_section(destination)?; let source = Source { reader, absolute_offset: span.absolute_offset, source_kind: span.source_kind, source_bytes: span.source_bytes, elements: span.elements, }; let result = fill_section(§ion, &layout, source, calibration, destination); drop(section); if result.is_err() { let _ = fs::remove_file(destination); } result } fn create_section(destination: &Path) -> Result { OpenOptions::new() .read(true) .write(true) .create_new(true) .open(destination) .map_err(|error| error.to_string()) } /// The tensor bytes to encode: where they sit in the reader and how many elements they decode to. struct Source<'a, R> { reader: &'a mut R, absolute_offset: u64, source_kind: u32, source_bytes: u64, elements: u64, } fn fill_section( section: &File, layout: &layout::Layout, source: Source<'_, R>, calibration: &kar_codec::Calibration, destination: &Path, ) -> Result { section .set_len(layout.section_bytes) .map_err(|error| error.to_string())?; let mut encoder = Encoder::open(calibration, destination, layout)?; let (source_digest, derived_digest) = encoder.stream(source)?; let relative_l2 = encoder.finish(layout.words)?; write_books(destination, layout.books_start, calibration)?; section.sync_all().map_err(|error| error.to_string())?; let digest = hash_file(destination)?; Ok(SectionResult { bytes: layout.section_bytes, digest, source_digest, derived_digest, relative_l2, }) } /// Running state of the group encoder: the open scale and plane writers and the error sums. struct Encoder<'a> { calibration: &'a kar_codec::Calibration, scale_writer: BufWriter, plane_writers: Vec>, pending: [f32; 32], filled: usize, seen: u64, groups: u64, sums: ErrorSums, } /// Squared reconstruction error and squared magnitude summed over every weight. #[derive(Default)] struct ErrorSums { error: f64, reference: f64, } impl ErrorSums { /// Add one weight's squared reconstruction error and squared magnitude. fn add(&mut self, original: f32, rebuilt: f32) { let (original, rebuilt) = (f64::from(original), f64::from(rebuilt)); let delta = original - rebuilt; self.error += delta * delta; self.reference += original.powi(2); } fn relative_l2(&self) -> f64 { if self.reference == 0.0 { self.error.sqrt() } else { (self.error / self.reference).sqrt() } } } impl<'a> Encoder<'a> { fn open( calibration: &'a kar_codec::Calibration, destination: &Path, layout: &layout::Layout, ) -> Result { let scale_writer = writer_at(destination, 0)?; let plane_writers = (0..calibration.books.len()) .map(|level| { writer_at( destination, layout.planes_start + level as u64 * layout.plane_stride, ) }) .collect::, _>>()?; Ok(Self { calibration, scale_writer, plane_writers, pending: [0.0f32; 32], filled: 0, seen: 0, groups: 0, sums: ErrorSums::default(), }) } /// Decodes the source through the bridge, encoding each full group of 32 weights as it arrives. fn stream( &mut self, source: Source<'_, R>, ) -> Result<([u8; 32], [u8; 32]), String> { let mut source_hash = Sha256::new(); let mut derived_hash = Sha256::new(); let decoded_bytes = gguf_f32_stream::visit( source.reader, source.absolute_offset, source.source_kind, source.source_bytes, |raw, f32_bytes| { source_hash.update(raw); derived_hash.update(f32_bytes); self.accept(f32_bytes, source.elements) }, )?; if self.seen != source.elements || decoded_bytes != source.elements.checked_mul(4).ok_or("F32 size overflow")? { return Err("GGUF decoded tensor shape mismatch".into()); } Ok(( source_hash.finalize().into(), derived_hash.finalize().into(), )) } fn accept(&mut self, f32_bytes: &[u8], elements: u64) -> Result<(), String> { for word in f32_bytes.as_chunks::<4>().0 { if self.seen >= elements { return Err("GGUF tensor decodes beyond its shape".into()); } self.pending[self.filled] = f32::from_le_bytes(*word); self.filled += 1; self.seen += 1; if self.filled == 32 { self.write_pending(32)?; self.filled = 0; self.groups += 1; } } Ok(()) } fn write_pending(&mut self, count: usize) -> Result<(), String> { write_group( &self.pending[..count], self.calibration, &mut self.scale_writer, &mut self.plane_writers, &mut self.sums, ) } /// Writes the partial last group, checks the group count, flushes and closes the writers. fn finish(mut self, words: u64) -> Result { if self.filled != 0 { self.write_pending(self.filled)?; self.groups += 1; } if self.groups != words { return Err("KAR encoded group count mismatch".into()); } self.scale_writer .flush() .map_err(|error| error.to_string())?; for writer in &mut self.plane_writers { writer.flush().map_err(|error| error.to_string())?; } Ok(self.sums.relative_l2()) } } fn write_books( destination: &Path, books_start: u64, calibration: &kar_codec::Calibration, ) -> Result<(), String> { 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()) } fn write_group( weights: &[f32], calibration: &kar_codec::Calibration, scales: &mut BufWriter, planes: &mut [BufWriter], sums: &mut ErrorSums, ) -> 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; sums.add(*original, rebuilt); } } write_plane_words(planes, words) } /// One 32-bit word per level plane, little endian. fn write_plane_words(planes: &mut [BufWriter], 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, bytes: &[u8]) -> Result<(), String> { writer.write_all(bytes).map_err(|error| error.to_string()) } fn writer_at(path: &Path, offset: u64) -> Result, 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 { 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()) } mod layout; #[cfg(test)] mod tests;