//! 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( reader: &mut R, absolute_offset: u64, source_kind: u32, source_bytes: u64, elements: u64, calibration: &kar_codec::Calibration, destination: &Path, ) -> Result { 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 { 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::, _>>()?; 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, planes: &mut [BufWriter], 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, 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()) } #[cfg(test)] mod tests { use super::*; use crate::{iq3_s, kar, kar_writer}; use std::io::Cursor; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn streamed_section_matches_existing_writer_and_forms_verified_archive() { let root = std::env::temp_dir().join(format!( "strata-stream-section-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )); fs::create_dir(&root).unwrap(); let weights = (0..33) .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) .collect::>(); let source = weights .iter() .flat_map(|value| value.to_le_bytes()) .collect::>(); let calibration = kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], }; let expected = kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); let books = calibration .books .iter() .map(Vec::as_slice) .collect::>(); let planes = expected .planes .iter() .map(Vec::as_slice) .collect::>(); let source_digest: [u8; 32] = Sha256::digest(&source).into(); let reference = root.join("reference.section"); kar_writer::write_nested_section( &reference, &kar_writer::Tensor { name: "expert", dims: &[33], source_dtype: 0, source_digest, source_offset: 0, data: kar_writer::TensorData::Nested { group: 32, nesting: 0, planes_min: 1, planes_max: 2, scales: &expected.scales, books: &books, planes: &planes, }, }, ) .unwrap(); let output = root.join("streamed.section"); let streamed = encode_section( &mut Cursor::new(&source), 0, 0, source.len() as u64, weights.len() as u64, &calibration, &output, ) .unwrap(); assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); assert_eq!(streamed.source_digest, source_digest); assert_eq!(streamed.derived_digest, source_digest); assert!(streamed.relative_l2.is_finite()); let archive = root.join("model.kar"); kar_writer::write_archive( &archive, &kar_writer::SourceIdentity { name: "streamed-test", architecture: "synthetic", builder: "test-streamed-g32-l2", digest: source_digest, total_elements: 33, bytes: source.len() as u64, }, &[kar_writer::Tensor { name: "expert", dims: &[33], source_dtype: 0, source_digest, source_offset: 0, data: kar_writer::TensorData::NestedFile { group: 32, nesting: 0, planes_min: 1, planes_max: 2, levels: 2, path: &output, offset: 0, bytes: streamed.bytes, digest: streamed.digest, }, }], ) .unwrap(); assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); fs::remove_dir_all(root).unwrap(); } #[test] fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { let mut block = [0u8; iq3_s::BLOCK_BYTES]; block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); let source = block.repeat(257); let calibration = kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], }; let path = std::env::temp_dir().join(format!( "strata-iq3-stream-{}-{}.section", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )); let result = encode_section( &mut Cursor::new(&source), 0, 21, source.len() as u64, (257 * iq3_s::BLOCK_ELEMENTS) as u64, &calibration, &path, ) .unwrap(); assert_eq!( result.source_digest.as_slice(), Sha256::digest(&source).as_slice() ); let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS); assert_eq!( result.derived_digest.as_slice(), Sha256::digest(&virtual_f32).as_slice() ); assert_eq!(result.relative_l2, 0.25); fs::remove_file(path).unwrap(); } }