//! 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 struct SectionRequest<'a> { pub absolute_offset: u64, pub source_kind: u32, pub source_bytes: u64, pub elements: u64, pub calibration: &'a kar_codec::Calibration, pub destination: &'a Path, } struct SectionLayout { levels: usize, words: u64, books_start: u64, planes_start: u64, plane_stride: u64, section_bytes: u64, } struct SectionLayoutValues { books_start: u64, planes_start: u64, plane_stride: u64, section_bytes: u64, } struct SectionEncoder<'a> { path: std::path::PathBuf, calibration: &'a kar_codec::Calibration, scale_writer: BufWriter, plane_writers: Vec>, pending: [f32; 32], filled: usize, seen: u64, groups: u64, error_sum: f64, reference_sum: f64, } pub fn encode_section( reader: &mut R, request: &SectionRequest<'_>, ) -> Result { encode_section_with_set_len(reader, request, File::set_len) } fn encode_section_with_set_len( reader: &mut R, request: &SectionRequest<'_>, set_len: fn(&File, u64) -> std::io::Result<()>, ) -> Result { let layout = SectionLayout::new(request.elements, request.calibration)?; let section = OpenOptions::new() .read(true) .write(true) .create_new(true) .open(request.destination) .map_err(|error| error.to_string())?; let result = set_len(§ion, layout.section_bytes) .map_err(|error| error.to_string()) .and_then(|()| encode_section_contents(reader, request, &layout)); drop(section); if result.is_err() { let _ = fs::remove_file(request.destination); } result } impl SectionLayout { fn new(elements: u64, calibration: &kar_codec::Calibration) -> Result { validate_calibration(elements, calibration)?; let levels = calibration.books.len(); let words = elements.div_ceil(32); let values = SectionLayoutValues::calculate(words, levels)?; Ok(Self { levels, words, books_start: values.books_start, planes_start: values.planes_start, plane_stride: values.plane_stride, section_bytes: values.section_bytes, }) } } impl SectionLayoutValues { fn calculate(words: u64, levels: usize) -> Result { 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 books_end = books_start .checked_add(books_bytes) .ok_or("KAR books overflow")?; let planes_start = round_up(books_end, 16)?; let plane_stride = plane_stride(words)?; let planes_bytes = plane_stride .checked_mul(levels as u64) .ok_or("KAR planes overflow")?; let planes_end = planes_start .checked_add(planes_bytes) .ok_or("KAR section overflow")?; Ok(Self { books_start, planes_start, plane_stride, section_bytes: round_up(planes_end, 256)?, }) } } fn plane_stride(words: u64) -> Result { let stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; if stride > u32::MAX as u64 { return Err("KAR plane stride exceeds format limit".into()); } Ok(stride) } fn validate_calibration(elements: u64, calibration: &kar_codec::Calibration) -> Result<(), 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()); } Ok(()) } fn encode_section_contents( reader: &mut R, request: &SectionRequest<'_>, layout: &SectionLayout, ) -> Result { let (source_digest, derived_digest, relative_l2) = encode_stream_values(reader, request, layout)?; sync_file(request.destination)?; let digest = hash_file(request.destination)?; Ok(SectionResult { bytes: layout.section_bytes, digest, source_digest, derived_digest, relative_l2, }) } fn encode_stream_values( reader: &mut R, request: &SectionRequest<'_>, layout: &SectionLayout, ) -> Result<([u8; 32], [u8; 32], f64), String> { let mut encoder = SectionEncoder::new(request.destination, request.calibration, layout)?; let mut source_hash = Sha256::new(); let mut derived_hash = Sha256::new(); let decoded_bytes = gguf_f32_stream::visit( reader, request.absolute_offset, request.source_kind, request.source_bytes, |raw, f32_bytes| { source_hash.update(raw); derived_hash.update(f32_bytes); encoder.push(f32_bytes, request.elements) }, )?; let relative_l2 = encoder.finish(request.elements, decoded_bytes, layout)?; Ok(( source_hash.finalize().into(), derived_hash.finalize().into(), relative_l2, )) } fn sync_file(path: &Path) -> Result<(), String> { OpenOptions::new() .read(true) .write(true) .open(path) .and_then(|file| file.sync_all()) .map_err(|error| error.to_string()) } impl<'a> SectionEncoder<'a> { fn new( path: &Path, calibration: &'a kar_codec::Calibration, layout: &SectionLayout, ) -> Result { let scale_writer = writer_at(path, 0)?; let plane_writers = (0..layout.levels) .map(|level| { writer_at( path, layout.planes_start + level as u64 * layout.plane_stride, ) }) .collect::, _>>()?; Ok(Self { path: path.to_path_buf(), calibration, scale_writer, plane_writers, pending: [0.0; 32], filled: 0, seen: 0, groups: 0, error_sum: 0.0, reference_sum: 0.0, }) } fn push(&mut self, bytes: &[u8], elements: u64) -> Result<(), String> { for word in 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)?; } } Ok(()) } fn write_pending(&mut self, count: usize) -> Result<(), String> { let mut output = GroupOutput { calibration: self.calibration, scales: &mut self.scale_writer, planes: &mut self.plane_writers, error_sum: &mut self.error_sum, reference_sum: &mut self.reference_sum, }; write_group(&self.pending[..count], &mut output)?; self.filled = 0; self.groups += 1; Ok(()) } fn finish( &mut self, elements: u64, decoded_bytes: u64, layout: &SectionLayout, ) -> Result { if self.seen != elements || decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? { return Err("GGUF decoded tensor shape mismatch".into()); } if self.filled != 0 { self.write_pending(self.filled)?; } if self.groups != layout.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())?; } self.write_books(layout.books_start)?; if self.reference_sum == 0.0 { Ok(self.error_sum.sqrt()) } else { Ok((self.error_sum / self.reference_sum).sqrt()) } } fn write_books(&self, offset: u64) -> Result<(), String> { let mut writer = writer_at(&self.path, offset)?; write_book_values(&mut writer, &self.calibration.books)?; writer.flush().map_err(|error| error.to_string())?; Ok(()) } } fn write_book_values(writer: &mut W, books: &[Vec]) -> Result<(), String> { for bits in books.iter().flatten() { writer .write_all(&bits.to_le_bytes()) .map_err(|error| error.to_string())?; } Ok(()) } struct GroupOutput<'a> { calibration: &'a kar_codec::Calibration, scales: &'a mut BufWriter, planes: &'a mut [BufWriter], error_sum: &'a mut f64, reference_sum: &'a mut f64, } struct PackValue<'a> { position: usize, value: f32, weights: &'a [f32], final_book: &'a [u16], rounded_scale: f32, words: &'a mut [u32; 8], } fn write_group(weights: &[f32], output: &mut GroupOutput<'_>) -> Result<(), String> { output.write(weights) } impl GroupOutput<'_> { fn write(&mut self, weights: &[f32]) -> Result<(), String> { let mut normalized = [0.0f32; 32]; let scale = kar_codec::normalize_group_into(weights, &mut normalized)?; self.scales .write_all(&scale.to_le_bytes()) .map_err(|error| error.to_string())?; let words = self.pack_words(weights, &normalized, scale)?; self.write_words(words) } fn pack_words( &mut self, weights: &[f32], normalized: &[f32; 32], scale: u16, ) -> Result<[u32; 8], String> { let mut words = [0u32; 8]; let final_book = self .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() { self.pack_value(PackValue { position, value: *value, weights, final_book, rounded_scale, words: &mut words, }); } Ok(words) } fn pack_value(&mut self, value: PackValue<'_>) { let index = self .calibration .boundaries .partition_point(|boundary| *boundary < value.value); for (level, word) in value.words[..self.planes.len()].iter_mut().enumerate() { let bit = (index >> (self.planes.len() - 1 - level)) & 1; *word |= (bit as u32) << value.position; } if let Some(original) = value.weights.get(value.position) { let rebuilt = kar_codec::f16_bits_to_f32(value.final_book[index]) * value.rounded_scale; let delta = f64::from(*original) - f64::from(rebuilt); *self.error_sum += delta * delta; *self.reference_sum += f64::from(*original).powi(2); } } fn write_words(&mut self, words: [u32; 8]) -> Result<(), String> { for (writer, word) in self.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}; fn reject_section_size(_: &File, _: u64) -> std::io::Result<()> { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) } #[test] fn plane_stride_rejects_overflow_and_format_limit() { assert_eq!(plane_stride(1), Ok(16)); assert_eq!(plane_stride(u64::MAX), Err("KAR planes overflow".into())); assert_eq!( plane_stride(1_073_741_824), Err("KAR plane stride exceeds format limit".into()) ); } #[test] fn failed_stream_encode_removes_partial_section() { let root = std::env::temp_dir().join(format!( "strata-stream-failure-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )); fs::create_dir(&root).unwrap(); let output = root.join("partial.section"); let calibration = kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], }; let result = encode_section( &mut Cursor::new(vec![0; 4]), &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 8, elements: 2, calibration: &calibration, destination: &output, }, ); assert!(result.is_err()); assert!(!output.exists()); fs::remove_dir_all(root).unwrap(); } #[test] fn all_zero_stream_has_defined_error_and_extra_values_are_rejected() { let root = test_dir("zero-and-overrun"); let calibration = test_calibration(); assert_zero_encoding_is_finite(&root, &calibration); assert_invalid_stream_shape(&root, &calibration, 12, 2, "beyond its shape"); assert_invalid_stream_shape(&root, &calibration, 4, 2, "shape mismatch"); assert!(sync_file(&root.join("missing.section")).is_err()); assert_set_len_failure_for_zero_fixture(&root, &calibration); fs::remove_dir_all(root).unwrap(); } fn assert_zero_encoding_is_finite(root: &Path, calibration: &kar_codec::Calibration) { let path = root.join("zero.section"); let summary = encode_fixture(Cursor::new(vec![0u8; 128]), &path, calibration, 128, 32).unwrap(); assert!(summary.relative_l2.is_finite() && summary.relative_l2 < 1e-6); assert!(sync_file(&path).is_ok()); } fn assert_invalid_stream_shape( root: &Path, calibration: &kar_codec::Calibration, bytes: u64, elements: u64, expected: &str, ) { let path = root.join(format!("invalid-{elements}-{bytes}.section")); let error = encode_fixture( Cursor::new(vec![0u8; bytes as usize]), &path, calibration, bytes, elements, ) .err() .unwrap(); assert!(error.contains(expected)); assert!(!path.exists()); } fn encode_fixture( mut reader: R, destination: &Path, calibration: &kar_codec::Calibration, source_bytes: u64, elements: u64, ) -> Result { encode_section( &mut reader, &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes, elements, calibration, destination, }, ) } fn assert_set_len_failure_for_zero_fixture(root: &Path, calibration: &kar_codec::Calibration) { let path = root.join("cannot-size.section"); let mut source = Cursor::new(vec![0u8; 128]); let request = SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 128, elements: 32, calibration, destination: &path, }; assert!(encode_section_with_set_len(&mut source, &request, reject_section_size).is_err()); assert!(!path.exists()); } #[test] fn section_encoder_accepts_borrowed_and_file_readers() { let root = test_dir("reader-types"); let calibration = test_calibration(); let bytes = vec![0u8; 128]; let mut borrowed = Cursor::new(&bytes); assert!(encode_reader(&mut borrowed, &root.join("borrowed.section"), &calibration).is_ok()); let source = root.join("source.bin"); fs::write(&source, &bytes).unwrap(); let mut file = File::open(source).unwrap(); assert!(encode_reader(&mut file, &root.join("file.section"), &calibration).is_ok()); fs::remove_dir_all(root).unwrap(); } fn encode_reader( reader: &mut R, path: &Path, calibration: &kar_codec::Calibration, ) -> Result { encode_section( reader, &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 128, elements: 32, calibration, destination: path, }, ) } fn assert_section_size_failure( reader: &mut R, destination: &Path, calibration: &kar_codec::Calibration, ) { let error = encode_section_with_set_len( reader, &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 128, elements: 32, calibration, destination, }, reject_section_size, ) .err() .unwrap(); assert!(error.to_lowercase().contains("denied"), "{error}"); assert!(!destination.exists()); } #[test] fn section_sizing_errors_clean_up_for_each_supported_reader() { let root = test_dir("set-len-errors"); let bytes = vec![0u8; 128]; let calibration = test_calibration(); let mut owned = Cursor::new(bytes.clone()); assert_section_size_failure(&mut owned, &root.join("owned.section"), &calibration); let mut borrowed = Cursor::new(&bytes); assert_section_size_failure(&mut borrowed, &root.join("borrowed.section"), &calibration); let input = root.join("source.bin"); fs::write(&input, bytes).unwrap(); let mut file = File::open(input).unwrap(); assert_section_size_failure(&mut file, &root.join("file.section"), &calibration); fs::remove_dir_all(root).unwrap(); } #[test] fn file_backed_encoder_matches_cursor_bytes() { let root = test_dir("file-parity"); let calibration = test_calibration(); let request = |destination| SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 128, elements: 32, calibration: &calibration, destination, }; let mut cursor = Cursor::new(vec![0u8; 128]); let cursor_path = root.join("cursor.section"); let memory = encode_section(&mut cursor, &request(&cursor_path)).unwrap(); let source = root.join("source.bin"); fs::write(&source, [0u8; 128]).unwrap(); let disk_path = root.join("file.section"); let disk = encode_section(&mut File::open(source).unwrap(), &request(&disk_path)).unwrap(); assert_eq!(disk.bytes, memory.bytes); assert_eq!(disk.digest, memory.digest); fs::remove_dir_all(root).unwrap(); } #[test] fn encoder_rejects_decoded_byte_count_mismatch() { let root = test_dir("decoded-size"); let calibration = test_calibration(); let layout = SectionLayout::new(1, &calibration).unwrap(); let path = root.join("section.bin"); File::create(&path) .unwrap() .set_len(layout.section_bytes) .unwrap(); let mut encoder = SectionEncoder::new(&path, &calibration, &layout).unwrap(); encoder.push(&1.0f32.to_le_bytes(), 1).unwrap(); assert_eq!( encoder.finish(1, 0, &layout).unwrap_err(), "GGUF decoded tensor shape mismatch" ); fs::remove_dir_all(root).unwrap(); } #[test] fn section_encoder_finishes_and_writes_canonical_codebooks() { let root = test_dir("finish-success"); let path = root.join("section.bin"); let calibration = test_calibration(); let layout = SectionLayout::new(32, &calibration).unwrap(); File::create(&path) .unwrap() .set_len(layout.section_bytes) .unwrap(); let mut encoder = SectionEncoder::new(&path, &calibration, &layout).unwrap(); let values = (0..32).map(|index| (index as f32 - 15.5) / 16.0); let bytes = values.flat_map(f32::to_le_bytes).collect::>(); encoder.push(&bytes, 32).unwrap(); assert!( encoder .finish(32, bytes.len() as u64, &layout) .unwrap() .is_finite() ); let archive = fs::read(&path).unwrap(); let expected = calibration .books .iter() .flatten() .flat_map(|bits| bits.to_le_bytes()) .collect::>(); let end = layout.books_start as usize + expected.len(); assert_eq!(&archive[layout.books_start as usize..end], expected); fs::remove_dir_all(root).unwrap(); } #[test] fn plane_writer_offset_failure_is_returned() { let root = test_dir("plane-open"); let calibration = test_calibration(); let path = root.join("section.bin"); File::create(&path).unwrap(); let layout = SectionLayout { levels: 2, words: 1, books_start: 16, planes_start: u64::MAX, plane_stride: 16, section_bytes: 256, }; assert!(SectionEncoder::new(&path, &calibration, &layout).is_err()); fs::remove_dir_all(root).unwrap(); } struct FailingWriter; impl Write for FailingWriter { fn write(&mut self, _: &[u8]) -> std::io::Result { Err(std::io::Error::other("injected book write failure")) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[test] fn book_value_writer_propagates_io_errors() { let error = write_book_values(&mut FailingWriter, &test_calibration().books).unwrap_err(); assert!(error.contains("injected book write failure")); } #[cfg(unix)] #[test] fn file_book_writer_propagates_device_write_errors() { let Ok(file) = OpenOptions::new().write(true).open("/dev/full") else { return; }; let mut writer = BufWriter::with_capacity(1, file); assert!(write_book_values(&mut writer, &test_calibration().books).is_err()); } #[cfg(unix)] #[test] fn encoder_reports_plane_flush_failure_after_buffered_group_write() { let Ok(first) = OpenOptions::new().write(true).open("/dev/full") else { return; }; let Ok(second) = OpenOptions::new().write(true).open("/dev/full") else { return; }; let root = test_dir("plane-flush"); let calibration = test_calibration(); let layout = SectionLayout::new(32, &calibration).unwrap(); let mut encoder = flush_failure_encoder(&root, &calibration, first, second); let bytes = (0..32) .flat_map(|n| (n as f32).to_le_bytes()) .collect::>(); encoder.push(&bytes, 32).unwrap(); assert!(encoder.finish(32, bytes.len() as u64, &layout).is_err()); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] fn flush_failure_encoder<'a>( root: &Path, calibration: &'a kar_codec::Calibration, first: File, second: File, ) -> SectionEncoder<'a> { let path = root.join("section.bin"); let layout = SectionLayout::new(32, calibration).unwrap(); File::create(&path) .unwrap() .set_len(layout.section_bytes) .unwrap(); SectionEncoder { path, calibration, scale_writer: BufWriter::new(File::create(root.join("scales.bin")).unwrap()), plane_writers: vec![BufWriter::new(first), BufWriter::new(second)], pending: [0.0; 32], filled: 0, seen: 0, groups: 0, error_sum: 0.0, reference_sum: 0.0, } } #[cfg(unix)] #[test] fn group_output_propagates_scale_and_plane_write_failures() { let Some(full) = OpenOptions::new().write(true).open("/dev/full").ok() else { return; }; let root = test_dir("group-output-errors"); let calibration = test_calibration(); let weights = [0.25f32; 32]; assert_scale_writer_error(full, &root, &calibration, &weights); assert_plane_writer_error(&root, &calibration, &weights); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] fn assert_scale_writer_error( full: File, root: &Path, calibration: &kar_codec::Calibration, weights: &[f32; 32], ) { let mut scales = BufWriter::with_capacity(1, full); let mut planes = vec![BufWriter::new( File::create(root.join("planes.bin")).unwrap(), )]; let mut error_sum = 0.0; let mut reference_sum = 0.0; assert!( GroupOutput { calibration, scales: &mut scales, planes: &mut planes, error_sum: &mut error_sum, reference_sum: &mut reference_sum } .write(weights) .is_err() ); } #[cfg(unix)] fn assert_plane_writer_error( root: &Path, calibration: &kar_codec::Calibration, weights: &[f32; 32], ) { let full = OpenOptions::new().write(true).open("/dev/full").unwrap(); let mut scales = BufWriter::new(File::create(root.join("scales.bin")).unwrap()); let mut planes = vec![BufWriter::with_capacity(1, full)]; let mut error_sum = 0.0; let mut reference_sum = 0.0; assert!( GroupOutput { calibration, scales: &mut scales, planes: &mut planes, error_sum: &mut error_sum, reference_sum: &mut reference_sum } .write(weights) .is_err() ); } fn test_dir(label: &str) -> std::path::PathBuf { let path = std::env::temp_dir().join(format!("strata-stream-{label}-{}", std::process::id())); let _ = fs::remove_dir_all(&path); fs::create_dir(&path).unwrap(); path } fn test_calibration() -> kar_codec::Calibration { kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], } } #[test] fn calibration_validation_rejects_each_invalid_stream_shape() { let valid = test_calibration(); assert!(validate_calibration(1, &valid).is_ok()); assert!(validate_calibration(0, &valid).is_err()); assert_invalid_calibrations(&valid); assert_excessive_calibration_levels(); } fn assert_invalid_calibrations(valid: &kar_codec::Calibration) { for calibration in [ kar_codec::Calibration { boundaries: vec![], books: vec![], }, kar_codec::Calibration { boundaries: vec![f32::NAN], books: vec![vec![0x3c00, 0x3c00]], }, kar_codec::Calibration { boundaries: vec![1.0, 0.0, 2.0], books: valid.books.clone(), }, kar_codec::Calibration { boundaries: valid.boundaries.clone(), books: vec![vec![0x3c00]], }, kar_codec::Calibration { boundaries: vec![-0.5, 0.0, 0.5], books: vec![vec![0x7c00, 0x3800], valid.books[1].clone()], }, ] { assert!(validate_calibration(1, &calibration).is_err()); } } fn assert_excessive_calibration_levels() { let too_many = (0..9).map(|level| vec![0x3c00; 1 << (level + 1)]).collect(); assert!( validate_calibration( 1, &kar_codec::Calibration { boundaries: vec![0.0; 511], books: too_many, } ) .is_err() ); } #[test] fn calibration_validation_rejects_wrong_sized_book_on_valid_boundaries() { let mut calibration = test_calibration(); calibration.books[0].pop(); assert_eq!( validate_calibration(1, &calibration).unwrap_err(), "invalid streamed KAR calibration" ); } fn rejects_existing_destination( reader: &mut R, path: &Path, calibration: &kar_codec::Calibration, ) { fs::write(path, b"owned output").unwrap(); let result = encode_section( reader, &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: 4, elements: 1, calibration, destination: path, }, ); assert!(result.is_err()); assert_eq!(fs::read(path).unwrap(), b"owned output"); fs::remove_file(path).unwrap(); } #[test] fn existing_destination_is_rejected_for_supported_reader_shapes() { let root = test_dir("existing-destination"); let calibration = test_calibration(); let borrowed = vec![0u8; 4]; rejects_existing_destination( &mut Cursor::new(vec![0u8; 4]), &root.join("owned-vector.section"), &calibration, ); rejects_existing_destination( &mut Cursor::new(&borrowed), &root.join("borrowed-vector.section"), &calibration, ); let source = root.join("source.bin"); fs::write(&source, [0u8; 4]).unwrap(); rejects_existing_destination( &mut File::open(source).unwrap(), &root.join("file-reader.section"), &calibration, ); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn section_encoder_surfaces_flush_and_group_count_failures() { if OpenOptions::new().write(true).open("/dev/full").is_err() { return; } let calibration = test_calibration(); let correct = SectionLayout::new(32, &calibration).unwrap(); let mut wrong = SectionLayout::new(32, &calibration).unwrap(); wrong.words += 1; let mut count_encoder = SectionEncoder::new(Path::new("/dev/null"), &calibration, &wrong).unwrap(); count_encoder.push(&[0u8; 128], 32).unwrap(); assert!( count_encoder .finish(32, 128, &wrong) .unwrap_err() .contains("group count") ); let mut failing = SectionEncoder::new(Path::new("/dev/full"), &calibration, &correct).unwrap(); failing.push(&[0u8; 128], 32).unwrap(); assert!(failing.finish(32, 128, &correct).is_err()); assert!(failing.write_books(0).is_err()); } #[test] fn streamed_section_matches_existing_writer_and_forms_verified_archive() { let root = test_dir("parity-archive"); let weights = parity_weights(); let source = raw_f32_bytes(&weights); let calibration = test_calibration(); let expected = kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); let source_digest: [u8; 32] = Sha256::digest(&source).into(); let reference = create_reference_nested_section(&root, source_digest, &calibration, &expected); let output = root.join("streamed.section"); let streamed = encode_parity_section(&source, &output, &weights, &calibration); assert_parity_output(&output, &reference, &streamed, source_digest); let archive = root.join("model.kar"); write_parity_archive(&archive, &output, &streamed, source_digest, &source); assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); fs::remove_dir_all(root).unwrap(); } fn parity_weights() -> Vec { (0..33) .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) .collect() } fn raw_f32_bytes(weights: &[f32]) -> Vec { weights .iter() .flat_map(|value| value.to_le_bytes()) .collect() } fn create_reference_nested_section( root: &Path, source_digest: [u8; 32], calibration: &kar_codec::Calibration, expected: &kar_codec::EncodedPlanes, ) -> std::path::PathBuf { let books = calibration .books .iter() .map(Vec::as_slice) .collect::>(); let planes = expected .planes .iter() .map(Vec::as_slice) .collect::>(); let path = root.join("reference.section"); let tensor = parity_reference_tensor(source_digest, expected, &books, &planes); kar_writer::write_nested_section(&path, &tensor).unwrap(); path } fn parity_reference_tensor<'a>( source_digest: [u8; 32], expected: &'a kar_codec::EncodedPlanes, books: &'a [&'a [u16]], planes: &'a [&'a [u32]], ) -> kar_writer::Tensor<'a> { 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, planes, }, } } fn encode_parity_section( source: &[u8], output: &Path, weights: &[f32], calibration: &kar_codec::Calibration, ) -> SectionResult { encode_section( &mut Cursor::new(source), &SectionRequest { absolute_offset: 0, source_kind: 0, source_bytes: source.len() as u64, elements: weights.len() as u64, calibration, destination: output, }, ) .unwrap() } fn assert_parity_output( output: &Path, reference: &Path, streamed: &SectionResult, source_digest: [u8; 32], ) { 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()); } fn write_parity_archive( archive: &Path, output: &Path, streamed: &SectionResult, source_digest: [u8; 32], source: &[u8], ) { let identity = kar_writer::SourceIdentity { name: "streamed-test", architecture: "synthetic", builder: "test-streamed-g32-l2", digest: source_digest, total_elements: 33, bytes: source.len() as u64, }; let tensor = parity_file_tensor(output, streamed, source_digest); kar_writer::write_archive(archive, &identity, &[tensor]).unwrap(); } fn parity_file_tensor<'a>( output: &'a Path, streamed: &SectionResult, source_digest: [u8; 32], ) -> kar_writer::Tensor<'a> { 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, }, } } #[test] fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { let source = iq3_source_blocks(257); let calibration = test_calibration(); 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_iq3_section(&path, &source, &calibration); assert_iq3_identity(&result, &source, 257); fs::remove_file(path).unwrap(); } fn iq3_source_blocks(blocks: usize) -> Vec { let mut block = [0u8; iq3_s::BLOCK_BYTES]; block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); block.repeat(blocks) } fn encode_iq3_section( path: &Path, source: &[u8], calibration: &kar_codec::Calibration, ) -> SectionResult { encode_section( &mut Cursor::new(source), &SectionRequest { absolute_offset: 0, source_kind: 21, source_bytes: source.len() as u64, elements: (257 * iq3_s::BLOCK_ELEMENTS) as u64, calibration, destination: path, }, ) .unwrap() } fn assert_iq3_identity(result: &SectionResult, source: &[u8], blocks: usize) { assert_eq!( result.source_digest.as_slice(), Sha256::digest(source).as_slice() ); let virtual_f32 = 1.0f32.to_le_bytes().repeat(blocks * iq3_s::BLOCK_ELEMENTS); assert_eq!( result.derived_digest.as_slice(), Sha256::digest(&virtual_f32).as_slice() ); assert_eq!(result.relative_l2, 0.25); } }