diff --git a/control-plane/README.md b/control-plane/README.md index e5f86336..16db5c52 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -1,6 +1,6 @@ # Control plane -For small, experimental sharded fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` acquires and verifies the sources, creates a KAR-2 preview, and verifies it again. It reuses an existing archive only when its payload, provenance, source identity, and requested level count verify. The 64 MiB input limit remains; this command cannot prepare the target model for serving. +For small, experimental sharded fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` acquires and verifies the sources, creates a KAR-2 preview, and verifies it again. It reuses an existing archive only when its payload, provenance, source identity, and requested level count verify. `model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes an archived tensor on CPU and reports a checksum suitable for comparison with the CUDA smoke tool. The 64 MiB input limit remains; these commands cannot prepare the target model for serving. The repository pins Rust 1.99.0 in [`rust-toolchain.toml`](../rust-toolchain.toml). `rustup` selects it automatically from this checkout. The `strata-next` executable defaults to `serve` and also supports `doctor`, `model fetch MANIFEST --output DIR`, `model verify MANIFEST --output DIR`, `model inspect FILE.gguf`, `model index FILE.gguf [--hash]`, `model derive-iq3-identity FILE.gguf`, `model derive-mixed-identity FILE.gguf`, `model derive-sharded-identity MANIFEST --source-dir DIR`, `model prepare-f32-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N`, `model inspect-kar FILE.kar`, `model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]`, `model verify-iq3-preview FILE.kar --source FILE.gguf`, `model verify-mixed-preview FILE.kar --source FILE.gguf`, `model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR`, `model extract-tokenizer FILE.gguf --output DIR`, `model tokenize TOKENIZER_DIR TEXT [--special]`, and `model detokenize TOKENIZER_DIR IDS`. Use `model tokenize TOKENIZER_DIR --stdin [--special]` for long text or control bytes. The IQ3, mixed, and sharded identity commands hash virtual F32 streams with bounded memory. Preview preparation commands write provenance sidecars, which the corresponding verification commands recompute and check against the archives. No preview archive is approved for serving. `model inspect-kar` checks bounded KAR-2 metadata, header CRC, directory digest, tensor shapes, and section bounds; `model verify-kar` also scans payload CRC-32 checksums. With a manifest and source directory it verifies each physical source shard and the archive's concatenated source digest. Neither command decodes KAR weights or measures quality. `scripts/check-local.sh` runs formatting, Clippy, Rust tests, protocol replay, and the CPU engine tests. diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index c755bfd8..97641a0f 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -9,7 +9,7 @@ use std::{ use sha2::{Digest, Sha256}; -use crate::model::Manifest; +use crate::{kar_codec, model::Manifest}; const HEADER_BYTES: usize = 256; const RECORD_BYTES: usize = 192; @@ -46,6 +46,105 @@ pub fn verify(path: &Path) -> Result { Ok(verify_with_sources(path)?.0) } +/// Independently reconstruct one bounded nested tensor from the archived bytes. +/// This is a CPU validation path for preview archives, not a serving decoder. +pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result, String> { + verify(path)?; + let mut file = File::open(path).map_err(|error| error.to_string())?; + let header = read_region(&mut file, 0, HEADER_BYTES)?; + let directory_offset = u64_at(&header, 24); + let directory_bytes = u64::from(u32_at(&header, 32)) * RECORD_BYTES as u64; + let string_offset = u64_at(&header, 40); + let string_bytes = u64_at(&header, 48); + let directory = read_region( + &mut file, + directory_offset, + usize::try_from(directory_bytes).map_err(|_| "KAR directory is too large")?, + )?; + let names = read_region( + &mut file, + string_offset, + usize::try_from(string_bytes).map_err(|_| "KAR string table is too large")?, + )?; + let (records, _) = directory.as_chunks::(); + let record = records + .iter() + .find(|record| { + let start = u32_at(*record, 0) as usize; + let end = start + u16_at(*record, 4) as usize; + names.get(start..end) == Some(name.as_bytes()) + }) + .ok_or_else(|| format!("KAR tensor not found: {name}"))?; + if record[7] != 0 { + return Err("CPU preview decoder requires a nested tensor".into()); + } + let stored = record[42]; + if level == 0 || level > stored { + return Err(format!("KAR tensor stores 1..={stored} levels")); + } + let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; + if elements > 1_000_000 { + return Err("CPU preview decoder is limited to one million elements".into()); + } + let group = u16_at(record, 46); + let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?; + let scale_bytes = read_region( + &mut file, + u64_at(record, 64), + usize::try_from(u64_at(record, 72)).map_err(|_| "KAR scales are too large")?, + )?; + let scales = scale_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let book_offset = u64_at(record, 80) + .checked_add((1u64 << (u32::from(level) + 1)) - 4) + .ok_or("KAR book offset overflow")?; + let book_bytes = read_region(&mut file, book_offset, (1usize << level) * 2)?; + let book = book_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let plane_stride = u64::from(u32_at(record, 104)); + let plane_bytes = padded / 32 * 4; + let mut planes = Vec::with_capacity(usize::from(level)); + for plane in 0..u64::from(level) { + let offset = u64_at(record, 96) + .checked_add( + plane + .checked_mul(plane_stride) + .ok_or("KAR plane offset overflow")?, + ) + .ok_or("KAR plane offset overflow")?; + let bytes = read_region(&mut file, offset, plane_bytes)?; + planes.push( + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + .collect::>(), + ); + } + let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); + let mut output = vec![0.0f32; elements]; + kar_codec::decode_range(&scales, &book, &plane_refs, group, 0, &mut output)?; + Ok(output) +} + +pub fn f32_fnv1a64(values: &[f32]) -> u64 { + values + .iter() + .flat_map(|value| value.to_le_bytes()) + .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3) + }) +} + pub fn verify_with_sources(path: &Path) -> Result<(Summary, Vec), String> { let (summary, mut file, sections, sources) = inspect_inner(path)?; let mut buffer = vec![0; 8 * 1024 * 1024]; diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs index 666683ad..1f0b1823 100644 --- a/control-plane/src/kar_codec.rs +++ b/control-plane/src/kar_codec.rs @@ -410,6 +410,12 @@ mod tests { let _ = fs::remove_file(&path); kar_writer::write_archive(&path, &source, &tensor).unwrap(); assert_eq!(kar::verify(&path).unwrap().tensor_count, 1); + let archived = kar::decode_preview_tensor(&path, "expert", 2).unwrap(); + assert_eq!(&archived[3..8], &[0.75, -0.75, -0.25, 0.25, 0.75]); + assert_eq!(kar::f32_fnv1a64(&[1.0]), 0x4b72_477f_9c5c_2f98); + let coarse = kar::decode_preview_tensor(&path, "expert", 1).unwrap(); + assert_eq!(&coarse[3..8], &[0.5, -0.5, -0.5, 0.5, 0.5]); + assert!(kar::decode_preview_tensor(&path, "expert", 3).is_err()); fs::remove_file(path).unwrap(); } diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 790a7808..6cf529ed 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -227,6 +227,15 @@ async fn main() -> Result<(), Box> { println!("not eligible for serving without a full-model quality gate"); Ok(()) } + [model, action, path, tensor, level] + if model == "model" && action == "checksum-kar-preview" => + { + let values = kar::decode_preview_tensor(Path::new(path), tensor, level.parse()?)?; + println!("tensor={tensor} elements={} level={level}", values.len()); + println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values)); + println!("first={} last={}", values[0], values[values.len() - 1]); + Ok(()) + } [model, action, path] if model == "model" && action == "inspect-kar" => { let summary = kar::inspect(Path::new(path))?; println!("KAR-2: {path}"); @@ -359,7 +368,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [serve|doctor|--ggml-license|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect-kar FILE.kar|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + _ => Err("usage: strata-next [serve|doctor|--ggml-license|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect-kar FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), } } diff --git a/docs/model-assets.md b/docs/model-assets.md index 6f859954..e1cb9f40 100644 --- a/docs/model-assets.md +++ b/docs/model-assets.md @@ -17,6 +17,8 @@ The executable carries its HTTPS trust roots, so `model fetch` does not need a C For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` runs fetch, source verification, experimental KAR-2 preparation, and archive verification in one command. On rerun it hashes the source shards and verifies the archive payload, provenance, and level count before reusing the file. A damaged or mismatched archive fails closed and is never overwritten automatically. This preview is limited to 64 MiB of GGUF input; the embedded `qwen-iq3-s` manifest is deliberately rejected before download. It does not provide full-model conversion or an approved serving artifact. +`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. + The acquisition stage downloads GGUF files; the native tokenizer stage extracts and uses tokenizer assets. Before fetching, the CLI checks available filesystem space against the remaining bytes in all manifest shards and checks again after the server chooses resume or restart. This avoids starting a transfer that already cannot fit; filesystem quotas or concurrent writers can still cause a later write failure. The upstream `iq_pack.py` format conversion, KAR-2 preparation, compressed GPU loading, and model startup still need native implementations and differential validation. See [compressed runtime contract](compressed-runtime.md) for the target `fetch` → `verify` → `prepare` → GPU decode sequence and `with-key`/`without-key` cache profiles. Model bytes belong on an external volume and never in Git or CI artifacts. `model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid.