diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index 8c047c2f..5351c0a5 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -49,6 +49,12 @@ pub struct VerifiedRangeDecoder { impl VerifiedRangeDecoder { pub fn open(path: &Path) -> Result { verify(path)?; + Self::open_previously_verified(path) + } + + /// Only for callers that have already verified the exact archive bytes. + pub(crate) fn open_previously_verified(path: &Path) -> Result { + inspect(path)?; let mut file = File::open(path).map_err(|error| error.to_string())?; let header = read_region(&mut file, 0, HEADER_BYTES)?; let directory_bytes = u64::from(u32_at(&header, 32)) * RECORD_BYTES as u64; @@ -103,6 +109,11 @@ pub fn inspect(path: &Path) -> Result { Ok(summary) } +pub fn inspect_with_sources(path: &Path) -> Result<(Summary, Vec), String> { + let (summary, _, _, sources) = inspect_inner(path)?; + Ok((summary, sources)) +} + pub fn verify(path: &Path) -> Result { Ok(verify_with_sources(path)?.0) } diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs new file mode 100644 index 00000000..32f588a8 --- /dev/null +++ b/control-plane/src/kar_overlay.rs @@ -0,0 +1,661 @@ +//! Experimental higher-precision KAR records for selected tensors of an +//! already verified base archive. This does not install a serving overlay. + +use std::{ + collections::{HashMap, HashSet}, + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Component, Path, PathBuf}, +}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::{gguf, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer, model::Manifest}; + +#[derive(Deserialize)] +struct Candidates { + schema: String, + source_archive_sha256: String, + proposed_levels: u8, + records: Vec, +} + +#[derive(Deserialize)] +struct Candidate { + name: String, + elements: u64, +} + +#[derive(Deserialize)] +struct BaseProvenance { + schema: String, + archive_sha256: String, + derived_f32_sha256: String, + derived_f32_bytes: u64, + shards: Vec, + tensors: Vec, +} + +#[derive(Deserialize)] +struct BaseShard { + name: String, + gguf_sha256: String, + gguf_bytes: u64, +} + +#[derive(Deserialize)] +struct BaseTensor { + name: String, + source_kind: u32, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Deserialize)] +struct OverlayProvenance { + schema: String, + base_archive_sha256: String, + overlay_archive_sha256: String, + levels: u8, + records: Vec, +} + +#[derive(Deserialize)] +struct OverlayRecord { + name: String, + f32_sha256: String, + relative_l2: f64, +} + +#[derive(Serialize)] +pub struct Comparison { + pub schema: &'static str, + pub base_archive_sha256: String, + pub overlay_archive_sha256: String, + pub verification: &'static str, + pub records: Vec, +} + +#[derive(Serialize)] +pub struct ComparedRecord { + pub name: String, + pub elements: u64, + pub base_relative_l2: f64, + pub overlay_relative_l2: f64, +} + +struct Location { + path: PathBuf, + absolute: u64, + kind: u32, + source_bytes: u64, + dimensions: Vec, +} + +struct Prepared { + name: String, + dimensions: Vec, + source_offset: u64, + f32_sha256: [u8; 32], + section_path: PathBuf, + section_bytes: u64, + section_sha256: [u8; 32], + relative_l2: f64, +} + +struct Staging(PathBuf); + +impl Drop for Staging { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +struct PendingArchive { + path: PathBuf, + committed: bool, +} + +impl Drop for PendingArchive { + fn drop(&mut self) { + if !self.committed { + let _ = fs::remove_file(&self.path); + } + } +} + +pub struct Summary { + pub archive_bytes: u64, + pub archive_sha256: [u8; 32], + pub record_count: usize, + pub maximum_relative_l2: f64, + pub provenance_path: PathBuf, +} + +pub fn prepare( + manifest: &Manifest, + source_dir: &Path, + base_archive: &Path, + candidate_path: &Path, + destination: &Path, +) -> Result { + let sidecar = destination.with_file_name(format!( + "{}.provenance.json", + destination + .file_name() + .ok_or("overlay destination has no file name")? + .to_string_lossy() + )); + if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(&sidecar).is_ok() { + return Err("overlay archive or provenance destination already exists".into()); + } + let candidates_bytes = fs::read(candidate_path).map_err(|error| error.to_string())?; + let candidates: Candidates = + serde_json::from_slice(&candidates_bytes).map_err(|error| error.to_string())?; + if candidates.schema != "strata-next/proposed-kar-precision-candidates-v1" + || !(1..=8).contains(&candidates.proposed_levels) + || candidates.records.is_empty() + { + return Err("invalid KAR overlay candidate policy".into()); + } + let base_sidecar = base_archive.with_file_name(format!( + "{}.provenance.json", + base_archive + .file_name() + .ok_or("base archive has no file name")? + .to_string_lossy() + )); + let base: BaseProvenance = + serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if base.schema != "strata-next/sharded-stream-provenance-v4" + || candidates.source_archive_sha256 != base.archive_sha256 + { + return Err("candidate policy differs from base KAR provenance".into()); + } + let base_digest = parse_digest(&base.archive_sha256)?; + let source_digest = parse_digest(&base.derived_f32_sha256)?; + let base_summary = kar::inspect(base_archive)?; + if base_summary.source_digest != source_digest + || base_summary.source_bytes != base.derived_f32_bytes + { + return Err("base KAR header differs from provenance".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() { + return Err("source manifest differs from base provenance".into()); + } + let mut locations = HashMap::new(); + let mut architecture = None::; + for (entry, recorded) in manifest_files.iter().zip(&base.shards) { + if entry.name != recorded.name + || entry.size != recorded.gguf_bytes + || entry.sha256 != recorded.gguf_sha256 + || !matches!( + Path::new(&entry.name).components().next(), + Some(Component::Normal(_)) + ) + || Path::new(&entry.name).components().count() != 1 + { + return Err("source manifest differs from base shard identity".into()); + } + let path = source_dir.join(&entry.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != entry.size { + return Err("source shard length changed since base preparation".into()); + } + if let Some(arch) = index.summary.architecture { + if architecture.as_deref().is_some_and(|old| old != arch) { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert(arch); + } + for tensor in index.tensors { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if locations + .insert( + tensor.name, + Location { + path: path.clone(), + absolute, + kind: tensor.kind, + source_bytes: tensor.bytes, + dimensions: tensor.dimensions, + }, + ) + .is_some() + { + return Err("duplicate GGUF tensor name".into()); + } + } + } + let base_tensors = base + .tensors + .iter() + .map(|tensor| (tensor.name.as_str(), tensor)) + .collect::>(); + if base_tensors.len() != base.tensors.len() { + return Err("duplicate tensor in base provenance".into()); + } + let staging = Staging(destination.with_file_name(format!( + "{}.overlay-sections-{}", + destination.file_name().unwrap().to_string_lossy(), + std::process::id() + ))); + fs::create_dir(&staging.0).map_err(|error| error.to_string())?; + let mut prepared = Vec::with_capacity(candidates.records.len()); + let mut seen = HashSet::new(); + for candidate in &candidates.records { + if !seen.insert(candidate.name.as_str()) { + return Err("duplicate KAR overlay candidate".into()); + } + let location = locations.get(&candidate.name).ok_or_else(|| { + format!( + "{}: candidate is not an unsplit GGUF tensor", + candidate.name + ) + })?; + let original = base_tensors + .get(candidate.name.as_str()) + .ok_or("candidate is missing from base provenance")?; + let elements = location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("candidate tensor shape overflow")?; + if location.kind != original.source_kind + || elements != candidate.elements + || original.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + { + return Err(format!( + "{}: candidate geometry differs from base", + candidate.name + )); + } + let source_sha256 = parse_digest(&original.source_sha256)?; + let f32_sha256 = parse_digest(&original.f32_sha256)?; + let mut source = File::open(&location.path).map_err(|error| error.to_string())?; + let sample = kar_sample::sample_normalized( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + elements, + source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + let calibration = kar_codec::fit_topdown(&sample, candidates.proposed_levels) + .map_err(|error| format!("{}: {error}", candidate.name))?; + let section_path = staging.0.join(format!("{:06}.section", prepared.len())); + let section = kar_stream_encode::encode_section( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + elements, + &calibration, + §ion_path, + )?; + if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 { + return Err(format!("{}: candidate source changed", candidate.name)); + } + prepared.push(Prepared { + name: candidate.name.clone(), + dimensions: location.dimensions.clone(), + source_offset: original.derived_offset, + f32_sha256, + section_path, + section_bytes: section.bytes, + section_sha256: section.digest, + relative_l2: section.relative_l2, + }); + } + let tensors = prepared + .iter() + .map(|entry| kar_writer::Tensor { + name: &entry.name, + dims: &entry.dimensions, + source_dtype: 0, + source_digest: entry.f32_sha256, + source_offset: entry.source_offset, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: candidates.proposed_levels, + levels: candidates.proposed_levels, + path: &entry.section_path, + offset: 0, + bytes: entry.section_bytes, + digest: entry.section_sha256, + }, + }) + .collect::>(); + let candidate_sha256: [u8; 32] = Sha256::digest(&candidates_bytes).into(); + let builder = format!( + "strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}", + candidates.proposed_levels, + &base.archive_sha256[..16], + &hex::encode(candidate_sha256)[..16] + ); + let source = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v4-overlay", + architecture: architecture.as_deref().ok_or("GGUF architecture missing")?, + builder: &builder, + digest: source_digest, + total_elements: base.derived_f32_bytes / 4, + bytes: base.derived_f32_bytes, + }; + let archive = kar_writer::write_archive(destination, &source, &tensors)?; + let mut pending = PendingArchive { + path: destination.to_path_buf(), + committed: false, + }; + let archive_sha256 = hash_file(destination)?; + let (verified, records) = kar::verify_with_sources(destination)?; + if verified != archive + || records.len() != prepared.len() + || records.iter().zip(&prepared).any(|(record, entry)| { + record.name != entry.name + || record.digest != entry.f32_sha256 + || record.offset != entry.source_offset + }) + { + return Err("overlay archive source records failed verification".into()); + } + let provenance = serde_json::json!({ + "schema": "strata-next/kar-overlay-provenance-v1", + "base_archive_sha256": hex::encode(base_digest), + "candidate_policy_sha256": hex::encode(candidate_sha256), + "overlay_archive_sha256": hex::encode(archive_sha256), + "derived_f32_sha256": hex::encode(source_digest), + "levels": candidates.proposed_levels, + "records": prepared.iter().map(|entry| serde_json::json!({ + "name": entry.name, + "derived_offset": entry.source_offset, + "f32_sha256": hex::encode(entry.f32_sha256), + "section_bytes": entry.section_bytes, + "relative_l2": entry.relative_l2, + })).collect::>(), + "serving_status": "experimental-not-approved", + }); + write_provenance(&sidecar, &provenance)?; + pending.committed = true; + Ok(Summary { + archive_bytes: archive.archive_bytes, + archive_sha256, + record_count: prepared.len(), + maximum_relative_l2: prepared + .iter() + .map(|entry| entry.relative_l2) + .fold(0.0f64, f64::max), + provenance_path: sidecar, + }) +} + +/// Compare complete selected tensors against the verified source bytes. +/// The large base archive is assumed unchanged since its earlier full verify; +/// every selected GGUF tensor and the small overlay are checked in this run. +pub fn compare( + manifest: &Manifest, + source_dir: &Path, + base_archive: &Path, + overlay_archive: &Path, +) -> Result { + let base_sidecar = base_archive.with_file_name(format!( + "{}.provenance.json", + base_archive + .file_name() + .ok_or("base archive has no file name")? + .to_string_lossy() + )); + let overlay_sidecar = overlay_archive.with_file_name(format!( + "{}.provenance.json", + overlay_archive + .file_name() + .ok_or("overlay archive has no file name")? + .to_string_lossy() + )); + let base: BaseProvenance = + serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + let overlay: OverlayProvenance = + serde_json::from_reader(File::open(overlay_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if base.schema != "strata-next/sharded-stream-provenance-v4" + || overlay.schema != "strata-next/kar-overlay-provenance-v1" + || overlay.base_archive_sha256 != base.archive_sha256 + || overlay.levels < 2 + || overlay.records.is_empty() + || hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256 + { + return Err("overlay provenance differs from base or overlay archive".into()); + } + let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?; + let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?; + if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)? + || overlay_summary.source_digest != base_summary.source_digest + || base_summary.source_bytes != base.derived_f32_bytes + || overlay_sources.len() != overlay.records.len() + { + return Err("KAR source identity differs from overlay provenance".into()); + } + let base_tensors = base + .tensors + .iter() + .map(|tensor| (tensor.name.as_str(), tensor)) + .collect::>(); + let base_records = base_sources + .iter() + .map(|record| (record.name.as_str(), record)) + .collect::>(); + let selected = overlay + .records + .iter() + .map(|record| record.name.as_str()) + .collect::>(); + if selected.len() != overlay.records.len() { + return Err("duplicate overlay tensor name".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() { + return Err("source manifest differs from base provenance".into()); + } + let mut locations = HashMap::new(); + for (entry, shard) in manifest_files.iter().zip(&base.shards) { + if entry.name != shard.name + || entry.size != shard.gguf_bytes + || entry.sha256 != shard.gguf_sha256 + { + return Err("source manifest differs from base provenance".into()); + } + let path = source_dir.join(&entry.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != entry.size { + return Err("GGUF shard length changed".into()); + } + for tensor in index.tensors { + if selected.contains(tensor.name.as_str()) { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if locations + .insert( + tensor.name, + Location { + path: path.clone(), + absolute, + kind: tensor.kind, + source_bytes: tensor.bytes, + dimensions: tensor.dimensions, + }, + ) + .is_some() + { + return Err("duplicate selected GGUF tensor".into()); + } + } + } + } + let mut base_decoder = kar::VerifiedRangeDecoder::open_previously_verified(base_archive)?; + let mut overlay_decoder = kar::VerifiedRangeDecoder::open_previously_verified(overlay_archive)?; + let mut compared = Vec::with_capacity(overlay.records.len()); + for (record, overlay_source) in overlay.records.iter().zip(&overlay_sources) { + let original = base_tensors + .get(record.name.as_str()) + .ok_or("selected tensor absent from base provenance")?; + let base_source = base_records + .get(record.name.as_str()) + .ok_or("selected tensor absent from base KAR directory")?; + let location = locations + .get(&record.name) + .ok_or("selected tensor absent from GGUF source")?; + let f32_digest = parse_digest(&record.f32_sha256)?; + let elements = location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("GGUF tensor shape overflow")?; + if overlay_source.name != record.name + || base_source.digest != f32_digest + || overlay_source.digest != f32_digest + || base_source.dimensions != location.dimensions + || overlay_source.dimensions != location.dimensions + || f32_digest != parse_digest(&original.f32_sha256)? + || base_source.offset != original.derived_offset + || overlay_source.offset != original.derived_offset + || location.kind != original.source_kind + || original.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + { + return Err(format!("{}: selected source mapping differs", record.name)); + } + let mut source = File::open(&location.path).map_err(|error| error.to_string())?; + let mut raw_hash = Sha256::new(); + let mut f32_hash = Sha256::new(); + let mut position = 0usize; + let mut reference_sum = 0.0f64; + let mut base_error = 0.0f64; + let mut overlay_error = 0.0f64; + let decoded_bytes = crate::gguf_f32_stream::visit( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + |raw, f32_bytes| { + raw_hash.update(raw); + f32_hash.update(f32_bytes); + let count = f32_bytes.len() / 4; + let base_values = base_decoder.decode_range(&record.name, 2, position, count)?; + let overlay_values = + overlay_decoder.decode_range(&record.name, overlay.levels, position, count)?; + for ((word, base_value), overlay_value) in f32_bytes + .as_chunks::<4>() + .0 + .iter() + .zip(&base_values) + .zip(&overlay_values) + { + let original = f64::from(f32::from_le_bytes(*word)); + reference_sum += original * original; + base_error += (original - f64::from(*base_value)).powi(2); + overlay_error += (original - f64::from(*overlay_value)).powi(2); + } + position += count; + Ok(()) + }, + )?; + if decoded_bytes != elements * 4 + || position as u64 != elements + || raw_hash.finalize().as_slice() != parse_digest(&original.source_sha256)? + || f32_hash.finalize().as_slice() != f32_digest + { + return Err(format!( + "{}: selected GGUF source digest mismatch", + record.name + )); + } + let denominator = if reference_sum == 0.0 { + 1.0 + } else { + reference_sum + }; + let base_relative_l2 = (base_error / denominator).sqrt(); + let overlay_relative_l2 = (overlay_error / denominator).sqrt(); + if !base_relative_l2.is_finite() + || !overlay_relative_l2.is_finite() + || (overlay_relative_l2 - record.relative_l2).abs() > 1e-6 + { + return Err(format!( + "{}: overlay reconstruction differs from encoding", + record.name + )); + } + compared.push(ComparedRecord { + name: record.name.clone(), + elements, + base_relative_l2, + overlay_relative_l2, + }); + } + Ok(Comparison { + schema: "strata-next/kar-overlay-comparison-v1", + base_archive_sha256: base.archive_sha256, + overlay_archive_sha256: overlay.overlay_archive_sha256, + verification: "prior-full-base-verification-assumed; selected-source-digests-and-overlay-verified-now", + records: compared, + }) +} + +pub fn write_comparison(path: &Path, comparison: &Comparison) -> Result<(), String> { + let value = serde_json::to_value(comparison).map_err(|error| error.to_string())?; + write_provenance(path, &value) +} + +fn parse_digest(value: &str) -> Result<[u8; 32], String> { + hex::decode(value) + .map_err(|error| error.to_string())? + .try_into() + .map_err(|_| "SHA-256 digest is not 32 bytes".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()) +} + +fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| error.to_string())?; + let result = (|| -> Result<(), String> { + serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?; + file.write_all(b"\n").map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string()) + })(); + if result.is_err() { + let _ = fs::remove_file(path); + } + result +} diff --git a/control-plane/src/kar_quality.rs b/control-plane/src/kar_quality.rs index 7f83963d..4b58873c 100644 --- a/control-plane/src/kar_quality.rs +++ b/control-plane/src/kar_quality.rs @@ -1,12 +1,14 @@ //! Sampled reconstruction diagnostics for a verified sharded KAR archive. //! These measurements do not substitute for a full-model quality gate. -use std::{fs::File, io::Write, path::Path}; +use std::{collections::HashMap, fs::File, io::Write, path::Path}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::{ - derived_mixed, gguf, gguf_f32_stream, kar::VerifiedRangeDecoder, model::Manifest, + derived_mixed, gguf, gguf_f32_stream, + kar::{self, VerifiedRangeDecoder}, + model::Manifest, prepare_preview, stream_parts, }; @@ -19,9 +21,59 @@ pub struct Report { pub derived_f32_sha256: String, pub levels: u8, pub method: &'static str, + pub verification: &'static str, pub records: Vec, } +#[derive(Deserialize)] +struct Provenance { + schema: String, + archive_sha256: String, + derived_f32_sha256: String, + derived_f32_bytes: u64, + levels: u8, + shards: Vec, + tensors: Vec, + partitioned_tensors: Vec, +} + +#[derive(Deserialize)] +struct ProvenanceShard { + name: String, + gguf_sha256: String, + gguf_bytes: u64, + tensor_count: usize, +} + +#[derive(Deserialize)] +struct ProvenanceTensor { + name: String, + source_kind: u32, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Deserialize)] +struct ProvenancePartition { + parent_name: String, + source_kind: u32, + parts: Vec, +} + +#[derive(Deserialize)] +struct ProvenancePart { + name: String, + dimensions: Vec, + source_byte_offset: u64, + source_bytes: u64, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + #[derive(Serialize)] pub struct RecordError { pub name: String, @@ -66,8 +118,239 @@ pub fn analyze( return Err("KAR source digest changed after verification".into()); } let parts = stream_parts::plan_shards(&identity, source_dir)?; - let mut decoder = VerifiedRangeDecoder::open(archive_path)?; - let mut records = Vec::with_capacity(summary.tensor_count as usize); + sample_records( + source_dir, + &identity, + &parts, + VerifiedRangeDecoder::open(archive_path)?, + levels, + archive_sha256, + "full-derived-source-and-archive-verification", + ) +} + +/// Reuse a prior full verification of immutable source shards and archive. +/// Checks metadata and provenance mappings, then reads only sampled payloads. +pub fn analyze_previously_verified( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, +) -> Result { + let provenance_path = archive_path.with_file_name(format!( + "{}.provenance.json", + archive_path + .file_name() + .ok_or("KAR archive has no file name")? + .to_string_lossy() + )); + let provenance: Provenance = + serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if provenance.schema != "strata-next/sharded-stream-provenance-v4" + || provenance.levels != levels + || !(1..=8).contains(&levels) + { + return Err("KAR sampled analysis requires v4 provenance and matching levels".into()); + } + let (summary, sources) = kar::inspect_with_sources(archive_path)?; + let derived_sha256 = parse_digest(&provenance.derived_f32_sha256)?; + parse_digest(&provenance.archive_sha256)?; + if summary.source_digest != derived_sha256 + || summary.source_bytes != provenance.derived_f32_bytes + || summary.max_planes > levels + { + return Err("KAR metadata differs from recorded provenance".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != provenance.shards.len() { + return Err("source manifest differs from recorded shard list".into()); + } + let mut identity = derived_mixed::ShardedIdentity { + derived_sha256, + derived_bytes: provenance.derived_f32_bytes, + shards: Vec::with_capacity(provenance.shards.len()), + tensors: Vec::with_capacity(provenance.tensors.len()), + }; + for (manifest_file, recorded) in manifest_files.iter().zip(&provenance.shards) { + if manifest_file.name != recorded.name + || manifest_file.size != recorded.gguf_bytes + || manifest_file.sha256 != recorded.gguf_sha256 + { + return Err("source manifest differs from recorded provenance".into()); + } + let path = source_dir.join(&recorded.name); + if File::open(path) + .and_then(|file| file.metadata()) + .map_err(|error| error.to_string())? + .len() + != recorded.gguf_bytes + { + return Err("source shard length changed since prior verification".into()); + } + identity.shards.push(derived_mixed::ShardIdentity { + name: recorded.name.clone(), + gguf_sha256: parse_digest(&recorded.gguf_sha256)?, + gguf_bytes: recorded.gguf_bytes, + tensor_count: recorded.tensor_count, + }); + } + for tensor in &provenance.tensors { + identity.tensors.push(derived_mixed::TensorIdentity { + name: tensor.name.clone(), + source_kind: tensor.source_kind, + source_sha256: parse_digest(&tensor.source_sha256)?, + derived_offset: tensor.derived_offset, + derived_bytes: tensor.derived_bytes, + f32_sha256: parse_digest(&tensor.f32_sha256)?, + }); + } + let partitioned = provenance + .partitioned_tensors + .iter() + .map(|entry| (entry.parent_name.as_str(), entry)) + .collect::>(); + if partitioned.len() != provenance.partitioned_tensors.len() { + return Err("duplicate KAR partition parent".into()); + } + let mut parts = Vec::with_capacity(identity.tensors.len()); + let mut number = 0usize; + for shard in &identity.shards { + let index = + gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?; + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes + { + return Err("GGUF shard metadata changed since prior verification".into()); + } + for tensor in &index.tensors { + let recorded = identity + .tensors + .get(number) + .ok_or("GGUF tensor count differs from provenance")?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("GGUF tensor shape overflow")?; + if recorded.name != tensor.name + || recorded.source_kind != tensor.kind + || recorded.derived_bytes != elements * 4 + { + return Err("GGUF tensor metadata differs from provenance".into()); + } + let group = if let Some(split) = partitioned.get(tensor.name.as_str()) { + if split.source_kind != tensor.kind || split.parts.len() < 2 { + return Err("invalid KAR partition metadata".into()); + } + split + .parts + .iter() + .map(|part| { + Ok(stream_parts::PartIdentity { + name: part.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: part.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: part.source_byte_offset, + source_bytes: part.source_bytes, + source_sha256: parse_digest(&part.source_sha256)?, + derived_offset: part.derived_offset, + derived_bytes: part.derived_bytes, + f32_sha256: parse_digest(&part.f32_sha256)?, + }) + }) + .collect::, String>>()? + } else { + vec![stream_parts::PartIdentity { + name: tensor.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: tensor.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: 0, + source_bytes: tensor.bytes, + source_sha256: recorded.source_sha256, + derived_offset: recorded.derived_offset, + derived_bytes: recorded.derived_bytes, + f32_sha256: recorded.f32_sha256, + }] + }; + let mut source_cursor = 0u64; + let mut derived_cursor = recorded.derived_offset; + for part in &group { + let part_elements = part + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("KAR part shape overflow")?; + if part.source_byte_offset != source_cursor + || part.derived_offset != derived_cursor + || part.derived_bytes != part_elements * 4 + { + return Err("KAR part offsets or shape differ from provenance".into()); + } + source_cursor = source_cursor + .checked_add(part.source_bytes) + .ok_or("KAR part source overflow")?; + derived_cursor = derived_cursor + .checked_add(part.derived_bytes) + .ok_or("KAR part derived overflow")?; + } + if source_cursor != tensor.bytes + || derived_cursor != recorded.derived_offset + recorded.derived_bytes + { + return Err("KAR parts do not cover GGUF parent".into()); + } + parts.push(group); + number += 1; + } + } + if number != identity.tensors.len() + || partitioned.len() != parts.iter().filter(|group| group.len() > 1).count() + || sources.len() != parts.iter().map(Vec::len).sum::() + { + return Err("KAR record count differs from provenance".into()); + } + for (record, part) in sources.iter().zip(parts.iter().flatten()) { + if record.name != part.name + || record.dimensions != part.dimensions + || record.dtype != 0 + || record.digest != part.f32_sha256 + || record.offset != part.derived_offset + { + return Err("KAR directory differs from recorded source mapping".into()); + } + } + sample_records( + source_dir, + &identity, + &parts, + VerifiedRangeDecoder::open_previously_verified(archive_path)?, + levels, + provenance.archive_sha256, + "previous-full-verification-assumed; metadata-checked-now", + ) +} + +fn parse_digest(value: &str) -> Result<[u8; 32], String> { + hex::decode(value) + .map_err(|error| error.to_string())? + .try_into() + .map_err(|_| "SHA-256 digest is not 32 bytes".into()) +} + +fn sample_records( + source_dir: &Path, + identity: &derived_mixed::ShardedIdentity, + parts: &[Vec], + mut decoder: VerifiedRangeDecoder, + levels: u8, + archive_sha256: String, + verification: &'static str, +) -> Result { + let mut records = Vec::with_capacity(parts.iter().map(Vec::len).sum()); let mut number = 0usize; for shard in &identity.shards { let path = source_dir.join(&shard.name); @@ -153,7 +436,7 @@ pub fn analyze( number += 1; } } - if number != parts.len() || records.len() != summary.tensor_count as usize { + if number != parts.len() || records.len() != parts.iter().map(Vec::len).sum::() { return Err("KAR source records changed during analysis".into()); } Ok(Report { @@ -161,7 +444,8 @@ pub fn analyze( archive_sha256, derived_f32_sha256: hex::encode(identity.derived_sha256), levels, - method: "first-middle-last-aligned-4096-v1", + method: "nonoverlapping-first-middle-last-aligned-4096-v2", + verification, records, }) } @@ -175,7 +459,13 @@ fn sample_windows(elements: u64, block_elements: u64) -> Result= 3 * count { + vec![0, end / 2 / block_elements * block_elements, end] + } else if elements >= 2 * count { + vec![0, end] + } else { + vec![0] + }; let mut result = Vec::new(); for start in starts { if result @@ -215,6 +505,8 @@ mod tests { #[test] fn sampled_windows_are_bounded_and_distinct() { assert_eq!(sample_windows(256, 256).unwrap().len(), 1); + assert_eq!(sample_windows(5000, 1).unwrap().len(), 1); + assert_eq!(sample_windows(8192, 256).unwrap().len(), 2); let windows = sample_windows(32_000, 256).unwrap(); assert_eq!(windows.len(), 3); assert!(windows.iter().all(|window| { diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 7fa8326e..54f649b0 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -11,6 +11,7 @@ mod iq3s_grid; pub mod kar; pub mod kar_codec; pub mod kar_fixture; +pub mod kar_overlay; pub mod kar_quality; pub mod kar_sample; pub mod kar_stream_encode; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 1481b8b5..84a73e25 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -3,8 +3,8 @@ use std::{env, io::Read, path::Path, sync::Arc}; use tokio::sync::{mpsc, watch}; use strata_control::{ - app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_quality, - model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets, worker, + app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_overlay, + kar_quality, model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets, worker, }; #[tokio::main] @@ -406,6 +406,72 @@ async fn main() -> Result<(), Box> { println!("samples are not a full-tensor or model-quality gate"); Ok(()) } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, output_flag, report_path, assume_flag] + if model == "model" + && action == "analyze-sharded-kar" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" + && levels_flag == "--levels" + && output_flag == "--output" + && assume_flag == "--assume-verified" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let report = kar_quality::analyze_previously_verified( + &manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, + )?; + kar_quality::write_report(Path::new(report_path), &report)?; + println!("sampled KAR reconstruction report: {report_path}"); + println!("records: {}", report.records.len()); + println!("archive SHA-256 from previously verified provenance: {}", report.archive_sha256); + println!("full archive and source hashes were not recomputed in this run"); + println!("samples are not a full-tensor or model-quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, candidates_flag, candidates_path, output_flag, destination] + if model == "model" + && action == "prepare-kar-overlay" + && source_flag == "--source-dir" + && base_flag == "--base" + && candidates_flag == "--candidates" + && output_flag == "--output" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let result = kar_overlay::prepare( + &manifest, + Path::new(source_dir), + Path::new(base_archive), + Path::new(candidates_path), + Path::new(destination), + )?; + println!("EXPERIMENTAL KAR precision overlay: {destination}"); + println!("records: {}; bytes: {}", result.record_count, result.archive_bytes); + println!("overlay SHA-256: {}", hex::encode(result.archive_sha256)); + println!("maximum selected-record relative L2: {:.8}", result.maximum_relative_l2); + println!("provenance: {}", result.provenance_path.display()); + println!("not eligible for serving without model-quality and GPU gates"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, overlay_flag, overlay_archive, output_flag, report_path] + if model == "model" + && action == "compare-kar-overlay" + && source_flag == "--source-dir" + && base_flag == "--base" + && overlay_flag == "--overlay" + && output_flag == "--output" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let comparison = kar_overlay::compare( + &manifest, + Path::new(source_dir), + Path::new(base_archive), + Path::new(overlay_archive), + )?; + kar_overlay::write_comparison(Path::new(report_path), &comparison)?; + println!("complete selected-tensor L2/L3 comparison: {report_path}"); + println!("records: {}", comparison.records.len()); + println!("not a full-model quality or GPU performance result"); + Ok(()) + } [model, action, path, manifest_flag, manifest_spec, source_flag, source_dir] if model == "model" && action == "verify-kar" && manifest_flag == "--manifest" && source_flag == "--source-dir" => { diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index c686f556..3fc7da6d 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -1671,6 +1671,20 @@ mod tests { .iter() .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) ); + let reused = crate::kar_quality::analyze_previously_verified( + &manifest, + &directory, + &streamed_output, + 2, + ) + .unwrap(); + assert!( + reused + .records + .iter() + .zip(&sampled.records) + .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) + ); assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); let streamed_record: serde_json::Value = @@ -1738,6 +1752,15 @@ mod tests { .iter() .all(|record| record.relative_l2 == 0.0) ); + let reused = + crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2) + .unwrap(); + assert!( + reused + .records + .iter() + .all(|record| record.relative_l2 == 0.0) + ); assert_eq!( verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), result.archive @@ -1745,6 +1768,90 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + #[test] + fn selected_overlay_reconstructs_source_and_cleans_staging() { + let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .collect::>(); + let dense = values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let files = [ + ("a.gguf", one_shard("dense", 0, 256, &dense)), + ( + "b.gguf", + one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let base = directory.join("base.kar"); + let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); + let policy = directory.join("candidates.json"); + fs::write( + &policy, + serde_json::to_vec(&serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": hex::encode(prepared.archive_digest), + "proposed_levels": 3, + "records": [{"name": "dense", "elements": 256}], + })) + .unwrap(), + ) + .unwrap(); + let overlay = directory.join("overlay.kar"); + let result = + crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); + assert_eq!(result.record_count, 1); + assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); + assert!(result.maximum_relative_l2.is_finite()); + let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); + let error_sum = decoded + .iter() + .zip(&values) + .map(|(actual, expected)| f64::from(actual - expected).powi(2)) + .sum::(); + let reference_sum = values + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::(); + assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); + assert!(result.provenance_path.exists()); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 1); + assert_eq!(comparison.records[0].name, "dense"); + assert!( + (comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7 + ); + assert!( + !directory + .join(format!( + "overlay.kar.overlay-sections-{}", + std::process::id() + )) + .exists() + ); + fs::remove_dir_all(directory).unwrap(); + } + #[test] fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { let directory = diff --git a/docs/build-validation.md b/docs/build-validation.md index 119ae23e..2112aa39 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -133,3 +133,14 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Read 18 independent 1,536,036-byte KAR expert sections from the verified full archive (gate/up/down records at layers 0, 3, 14, 24, 37, and 45 for experts 0, 127, and 511). On the same 18 blocks, mean compressed/raw ratios were 0.988025 for LZ4 HC (`lz4 -9`, 1.10.0), 0.935372 for Deflate (`zlib` level 9), and 0.915421 for xz (`xz -9e`, XZ Utils 5.8.4). Median xz ratio was 0.914897, with a range of 0.904669–0.930424. One block per codec decompressed byte-identically. These are CPU encoding and size observations only, without a CUDA decoder, PCIe measurement, or end-to-end A/B result. - A separate sparse scan of 26 aligned 32 MiB windows spaced 2 GiB across the archive gave mean xz ratio 0.895215, median 1.000051, and range 0.418332–1.000051. The large spread shows that a full-archive size cannot be inferred reliably from a few windows; no complete outer-compressed archive was produced. - The streamed Rust preparer now retains relative L2, source kind, and section bytes per KAR record in its result and prints the worst 20 when creating a new archive. A forced-split fixture checked that all records are represented and their maximum equals the summary maximum. The existing full archive was created before this diagnostic and has no per-record report; reusing it will not fabricate one. All 65 Rust tests, Clippy with warnings denied, and `git diff --check` passed locally. + +## 2026-10-03 — sampled distortion of the existing complete archive + +- Added `model analyze-sharded-kar` and a reusable verified CPU range decoder. The strict mode checks complete source derivation, archive payloads, and provenance. Its first full-model run was stopped after about 13 minutes because repeated derivation of the 707,775,598,080-byte virtual F32 stream made it unnecessarily expensive; it had produced no report or intermediate model files. A separate `--assume-verified` mode uses the earlier independent full verification of the immutable archive and source shards, checks current metadata and provenance mapping, and reads only sample windows. Synthetic compressed and RAW archives gave identical sampled relative L2 in strict and fast modes. The fast mode does **not** rehash source or archive payloads and says so in its output. +- The fast real-model run produced `/Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.sampled-distortion.json` outside Git: 1,225 records, 12,276,608 sampled values, 546,787 JSON bytes, report SHA-256 `1452b55705b9f723747df7dba47fd0484ae8b4140b0022cacceefb16970b5bbf`, bound to the previously verified archive SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. Each record uses up to three nonoverlapping GGUF-block-aligned windows of at most 4,096 values (beginning, middle, end). The median sampled relative L2 is 0.363209; 22 records are at least 0.5 and 207 at least 0.4. The largest sampled value is 0.77458222 in `blk.0.ffn_gate_inp.weight`; 0.74248190 and 0.73494266 occur in the same tensor family at blocks 30 and 14. A window's relative L2 can exceed the earlier full-record maximum of 0.68008092 because it measures a different subset, and it is not a full-record bound or model-quality result. +- The 22 records at or above 0.5 contain 43,008,000 values. Adding one KAR bit plane only to these records would nominally add 5.13 MiB of plane bits before alignment and metadata; a serving loader and GPU path still need to apply this mixed-rate overlay. An external proposal list, `/Users/para/.local/share/strata-next/qwen-iq3-s-l3-candidates.json`, has SHA-256 `6c82c80c8edfb7a8b0e83c8ebd690339843b83a9dce0020967e7146cbcb41120`. It is a diagnostic proposal, not an approved precision policy or proof of improved model quality. The split `per_layer_token_embd.weight` sampled at 0.33714705 and 0.33125633; `token_embd.weight` at 0.33737772 and `output.weight` at 0.37104131. + +## 2026-10-03 — selected L3 overlay and paired tensor comparison + +- `model prepare-kar-overlay` encoded the 22 proposed unsplit records from the original GGUF shards at KAR level 3. Each selected physical GGUF and virtual F32 digest matched the full base provenance during encoding; the KAR writer and an independent pass verified the overlay records and payloads. The overlay is `/Users/para/.local/share/strata-next/qwen-iq3-s-l3-overlay.kar`, **18,827,008 bytes** (17.955 MiB), SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`, with 22 records. The corresponding base archive sections occupy 13,445,632 bytes, so the standalone overlay file exceeds those sections by 5,381,376 bytes, including its own header/directory/alignment. The overlay provenance is 6,039 bytes, SHA-256 `403eeca17d09bd51b3c5f6bae2587c62c483707e346577ab3df6feed2a2a7958`. Private staging sections were removed. +- `model compare-kar-overlay` decoded every value of the same 22 tensors from the base L2 and overlay L3 archives, compared both to pinned GGUF dequantization, and recomputed each selected source tensor's physical and F32 SHA-256. Its external report `/Users/para/.local/share/strata-next/qwen-iq3-s-l2-vs-l3-overlay.json` is 4,226 bytes, SHA-256 `6413b353381749c5d0cc0eb91ed5bf93e6b8a9c36fd7f6db9942fd20a7478e97`. All 22 full-record relative L2 errors decreased. The median across selected records was 0.50734744 at L2 and 0.22607999 at L3; the largest selected-record error decreased from 0.62459845 to 0.28435756. For `blk.0.ffn_gate_inp.weight`, the paired full-record values were 0.62459845 and 0.28435756. This is a numerical weight reconstruction result, **not** a model-quality result or a GPU/PCIe performance result. The large base archive's earlier full verification is assumed by this comparison, while the selected source tensors and small overlay were freshly checked. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 60baea27..52f005af 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -40,7 +40,9 @@ The `kar_stream_encode` primitive writes one canonical nested section directly f `model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` now connects the bounded visitor, deterministic 65,536-value calibration sample, file-backed section encoder, and KAR-2 archive writer across manifest-pinned GGUF shards. It has no 64 MiB preview cap or per-tensor allocation. If a tensor cannot supply a valid nested calibration, it is copied as virtual F32 into a RAW section instead of being discarded. Every streamed tensor's physical and virtual digest is checked against an independently derived identity, every shard is hashed again after preparation, and the archive and separate preparation-policy provenance are published without replacing existing files. Oversized tensors are split into adjacent records with checked source and virtual offsets and part hashes. `model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N` independently verifies the shards, virtual tensor source records, archive payload CRCs, and sidecar binding. A small forced-split test reconstructs both records on CPU. Both real target shards and selected KAR slices are verified; full-model rate choice, quality, and Linux GPU loader still need validation. This command is experimental and its output is not eligible for serving. -The streamed preparer tracks relative L2 and encoded bytes per KAR record and prints the twenty records with the largest relative L2 on a newly created archive. This ranks candidates for more precision but is not a serving threshold or a full-model quality score; a split parent tensor appears as multiple records. The existing 51.50 GiB archive predates this report and still has only its recorded maximum of 0.68008092. A selective precision policy can encode sensitive records at more KAR levels, retain an exact representation, or add independently addressable residual blocks. Residuals need archive integrity checks and must be included in transfer, VRAM, and CUDA decode budgets. Choose the policy after per-class distortion measurements and the separate model-quality gate; a lossless outer codec cannot repair KAR quantization error. +The streamed preparer tracks relative L2 and encoded bytes per KAR record and prints the twenty records with the largest relative L2 on a newly created archive. The existing 51.50 GiB archive predates that recording and has only its full-record maximum of 0.68008092. `model analyze-sharded-kar` can now compare small source/archive windows for every record in that existing archive; its `--assume-verified` mode uses the earlier full source/archive verification and marks that assumption in the report. This ranks candidates for more precision but is not a full-record error bound or a model-quality score; a split parent tensor appears as multiple records. A selective precision policy can encode sensitive records at more KAR levels, retain an exact representation, or add independently addressable residual blocks. Residuals need archive integrity checks and must be included in transfer, VRAM, and CUDA decode budgets. Choose the policy after per-class distortion measurements and the separate model-quality gate; a lossless outer codec cannot repair KAR quantization error. + +An experimental KAR overlay now carries higher-precision replacement records for a selected subset without rebuilding the full archive. Its provenance binds the base archive and candidate policy digests; selected physical and virtual source digests are checked during encoding. The overlay is independently verified, and the CPU comparison command measures paired full-record error against both archives. A serving loader must still select overlay records by name, verify both artifacts together, and account for their VRAM residency and transfer before this can affect inference. An overlay is not an additive residual: it replaces the selected base record when enabled. The CPU quality oracle can decode up to one million values from an arbitrary nested tensor offset with bounded memory, reading only the needed scales and plane words after archive verification. `cargo run --release --example compare-kar-range -- FILE.gguf FILE.kar LEVEL START COUNT` compares this archived output against pinned ggml dequantization of a one-tensor GGUF sample. On source-verified real slices, independent level-2 archive reconstruction gave relative L2 around 0.33–0.34 for sampled IQ3_S and IQ4_NL ranges; level 3 reduced one IQ4_NL range to 0.165. This is a numerical roundtrip check on selected ranges, not an agent-quality gate. diff --git a/docs/model-assets.md b/docs/model-assets.md index 0dbced2f..5c541185 100644 --- a/docs/model-assets.md +++ b/docs/model-assets.md @@ -21,7 +21,9 @@ For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR `model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes one bounded nested tensor from the archive and prints an FNV-1a checksum of the F32 output. On Linux, compare `output_fnv1a64` with the same field from `strata-kar-gpu-smoke FILE.kar TENSOR LEVEL ITERATIONS`. This checks CPU and CUDA reconstruction byte for byte on a fixture; it is not a full-model quality gate. -`model analyze-sharded-kar FILE.kar --manifest SPEC --source-dir DIR --levels N --output REPORT.json` verifies a streamed archive and its source shards, then compares bounded GGUF and KAR samples for every archive record. The report binds to the archive SHA-256 and records relative L2 for aligned windows of up to 4,096 values at the beginning, middle, and end of each record. It reads the existing archive and shards without creating another model copy. The report is a diagnostic for selective precision; sparse samples can miss a local failure, and the result is neither a full-tensor error bound nor a model-quality gate. +`model analyze-sharded-kar FILE.kar --manifest SPEC --source-dir DIR --levels N --output REPORT.json` verifies a streamed archive and its source shards, then compares bounded GGUF and KAR samples for every archive record. Append `--assume-verified` only when the exact source shards, archive, and provenance were fully verified earlier and have remained immutable: this fast mode checks their structure and mapping but does not rehash all bytes or rederive the 708 GB virtual F32 stream. The JSON records which verification mode was used, the archive digest, and relative L2 for up to three nonoverlapping, aligned windows of at most 4,096 values at the beginning, middle, and end of each record. It reads existing files without creating another model copy. Sparse samples can miss a local failure; neither mode is a full-tensor error bound or model-quality gate. + +`model prepare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --candidates CANDIDATES.json --output OVERLAY.kar` is an experimental way to re-encode only selected unsplit records at a higher KAR level. It checks each selected GGUF tensor's physical and derived F32 digests against the base provenance, verifies the resulting KAR, writes an overlay provenance sidecar, and removes staging sections. `model compare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --overlay OVERLAY.kar --output REPORT.json` decodes all selected values from both archives against the GGUF source, rechecks selected source digests and overlay CRCs, and records paired full-record relative L2. The base archive's earlier full verification is assumed; it is not rehashed by the comparison. No serving loader applies this overlay yet, and lower tensor error alone does not pass the model-quality gate. `model smoke-fixture --output FILE.kar` writes a deterministic 32-element KAR-2 archive named `smoke.expert` and prints its archive digest and two-level CPU decode checksum. It refuses to overwrite an existing file. This model-free artifact lets the Linux CUDA decoder be checked before the target model is available. diff --git a/docs/roadmap.md b/docs/roadmap.md index f3546252..3faf6f00 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -109,6 +109,6 @@ Pull requests and main commits run Rust format, Clippy, tests, synthetic replay, ## Current status -P0 has local CI assets and a v4 Linux/arm64 musl static CLI that ran from `scratch` and verified a real-data KAR sample; hosted Actions and x86_64 validation still need a GitHub repository and runner. P1 has `model fetch` and `model verify`; both real shards passed their manifest SHA-256 values. P2 has bounded GGUF indexing, real-tokenizer parity against upstream, pinned ggml CPU decoding with checked block geometry, and an experimental bounded-memory sharded GGUF-to-KAR path. Streamed policy v4 partitions the giant per-layer tensor so its bit-plane stride fits KAR-2. The complete level-2 archive was produced from both verified shards: 55,295,529,472 bytes from 83,617,662,656 source bytes (66.13%); an independent verifier passed source identity, KAR records, payload CRCs, archive hash, and provenance. Its maximum tensor relative L2 error was 0.68008092. This measurement establishes disk size and structural integrity only and does not pass the model-level quality gate. Sampled IQ3_S values matched pinned ggml bit for bit, and selected archived ranges were independently decoded and compared with GGUF values. The Responses route has a restricted non-streaming text preview backed by the worker queue and synthetic tests. Live streaming, tool calls, full-model quality, CUDA decode, GPU baseline, and a complete single-file GPU runtime remain pending. +P0 has local CI assets and a v4 Linux/arm64 musl static CLI that ran from `scratch` and verified a real-data KAR sample; hosted Actions and x86_64 validation still need a GitHub repository and runner. P1 has `model fetch` and `model verify`; both real shards passed their manifest SHA-256 values. P2 has bounded GGUF indexing, real-tokenizer parity against upstream, pinned ggml CPU decoding with checked block geometry, and an experimental bounded-memory sharded GGUF-to-KAR path. Streamed policy v4 partitions the giant per-layer tensor so its bit-plane stride fits KAR-2. The complete level-2 archive was produced from both verified shards: 55,295,529,472 bytes from 83,617,662,656 source bytes (66.13%); an independent verifier passed source identity, KAR records, payload CRCs, archive hash, and provenance. Its maximum tensor relative L2 error was 0.68008092. A separate 18,827,008-byte level-3 overlay for 22 high-distortion records reduced paired full-record relative L2 for every selected tensor, but no serving loader applies it yet. These numerical results do not pass the model-level quality gate. Sampled IQ3_S values matched pinned ggml bit for bit, and selected archived ranges were independently decoded and compared with GGUF values. The Responses route has a restricted non-streaming text preview backed by the worker queue and synthetic tests. Live streaming, tool calls, full-model quality, CUDA decode, GPU baseline, and a complete single-file GPU runtime remain pending. References: [NVIDIA CUDA 13.0 release notes](https://docs.nvidia.com/cuda/archive/13.0.0/cuda-toolkit-release-notes/index.html), [NVIDIA driver components](https://docs.nvidia.com/deploy/cuda-compatibility/latest/why-cuda-compatibility.html), and [Rust musl target support](https://doc.rust-lang.org/rustc/platform-support.html).