From e795ff4a918453784b7a613caa0b164181ddda86 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 23:25:59 +0200 Subject: [PATCH] Consume staged KAR sections and accept sparse shard metadata --- control-plane/src/kar_writer.rs | 73 ++++++++++++++++++++++++++++ control-plane/src/prepare_preview.rs | 63 +++++++++++++----------- docs/build-validation.md | 2 + docs/compressed-runtime.md | 2 + 4 files changed, 112 insertions(+), 28 deletions(-) diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index a2dd97b8..e55065f3 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -89,6 +89,34 @@ pub fn write_archive( destination: &Path, source: &SourceIdentity<'_>, tensors: &[Tensor<'_>], +) -> Result { + write_archive_inner(destination, source, tensors, false) +} + +/// Consume caller-owned, private staging files as their sections are copied. +/// This bounds peak disk use during streamed model preparation. A failed build +/// must be restarted because some input sections may already be removed. +pub(crate) fn write_archive_consuming_files( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], +) -> Result { + if tensors.iter().any(|tensor| { + !matches!( + &tensor.data, + TensorData::RawFile { .. } | TensorData::NestedFile { .. } + ) + }) { + return Err("consuming KAR writer requires file-backed tensors".into()); + } + write_archive_inner(destination, source, tensors, true) +} + +fn write_archive_inner( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], + consume_files: bool, ) -> Result { if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 { return Err("KAR destination exists or tensor count is invalid".into()); @@ -277,6 +305,13 @@ pub fn write_archive( file.write_all(&names).map_err(|error| error.to_string())?; for entry in &mut placed { entry.payload_crc32 = write_section(&mut file, entry)?; + if consume_files { + let path = match &entry.tensor.data { + TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path, + _ => unreachable!(), + }; + fs::remove_file(path).map_err(|error| error.to_string())?; + } } if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes { return Err("KAR writer produced the wrong archive length".into()); @@ -1071,6 +1106,44 @@ mod tests { fs::remove_file(input).unwrap(); } + #[test] + fn consuming_writer_removes_staged_input_after_verified_copy() { + let raw = (0..32u32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let input = root.join("section.bin"); + let output = root.join("archive.kar"); + fs::write(&input, &raw).unwrap(); + let digest: [u8; 32] = Sha256::digest(&raw).into(); + let source = SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "consume-test", + digest, + total_elements: 32, + bytes: raw.len() as u64, + }; + let tensors = [Tensor { + name: "raw", + dims: &[32], + source_dtype: 0, + source_digest: digest, + source_offset: 0, + data: TensorData::RawFile { + path: &input, + offset: 0, + bytes: raw.len() as u64, + }, + }]; + let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap(); + assert!(!input.exists()); + assert_eq!(kar::verify(&output).unwrap(), summary); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn archive_bytes_match_pinned_koference_reference_writer() { // Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture. diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 5378a797..57aa18dd 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -190,18 +190,15 @@ pub fn prepare_sharded( for shard in &identity.shards { let path = source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - let shard_architecture = index - .summary - .architecture - .as_deref() - .ok_or("GGUF shard has no architecture")?; - if architecture - .as_deref() - .is_some_and(|expected| expected != shard_architecture) - { - return Err("GGUF shard architectures differ".into()); + if let Some(shard_architecture) = index.summary.architecture.as_deref() { + if architecture + .as_deref() + .is_some_and(|expected| expected != shard_architecture) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| shard_architecture.to_owned()); } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes { return Err("GGUF shard changed after identity derivation".into()); @@ -368,18 +365,15 @@ pub fn prepare_sharded_streamed( for shard in &identity.shards { let path = source_dir.join(&shard.name); let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - let shard_architecture = index - .summary - .architecture - .as_deref() - .ok_or("GGUF shard has no architecture")?; - if architecture - .as_deref() - .is_some_and(|expected| expected != shard_architecture) - { - return Err("GGUF shard architectures differ".into()); + if let Some(shard_architecture) = index.summary.architecture.as_deref() { + if architecture + .as_deref() + .is_some_and(|expected| expected != shard_architecture) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| shard_architecture.to_owned()); } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes { return Err("GGUF shard changed after identity derivation".into()); @@ -529,7 +523,8 @@ pub fn prepare_sharded_streamed( total_elements: identity.derived_bytes / 4, bytes: identity.derived_bytes, }; - let archive = kar_writer::write_archive(destination, &source_identity, &tensors)?; + let archive = + kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)?; let archive_digest = hash_file(destination)?; let provenance_path = provenance_path(destination)?; let mut provenance = sharded_provenance_value(&identity, archive_digest); @@ -1167,13 +1162,25 @@ mod tests { } fn one_shard(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec { + one_shard_with_arch(name, kind, elements, payload, true) + } + + fn one_shard_with_arch( + name: &str, + kind: u32, + elements: u64, + payload: &[u8], + include_architecture: bool, + ) -> Vec { let mut gguf = b"GGUF".to_vec(); gguf.extend_from_slice(&3u32.to_le_bytes()); gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); + gguf.extend_from_slice(&u64::from(include_architecture).to_le_bytes()); + if include_architecture { + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + } string(&mut gguf, name); gguf.extend_from_slice(&1u32.to_le_bytes()); gguf.extend_from_slice(&elements.to_le_bytes()); @@ -1455,7 +1462,7 @@ mod tests { *byte = (index as u8).wrapping_mul(3); } block[74] = 0x55; - let iq3 = one_shard("expert", 21, 256, &block); + let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); let mut manifest = Manifest { diff --git a/docs/build-validation.md b/docs/build-validation.md index f0b821cb..2b670a34 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -100,3 +100,5 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Added `model prepare-sharded-streamed` and `model verify-sharded-streamed`: the experimental path samples at most 65,536 normalized values per tensor, writes nested or exact RAW F32 sections from bounded GGUF chunks, checks per-tensor physical/virtual digests, rehashes each shard, assembles a KAR-2 archive, and binds a separate versioned sidecar. The two-shard F32/IQ3_S synthetic test verifies the archive, reconstructs a dense tensor on CPU, rejects a changed preparation level and pinned shard digest, and refuses to overwrite the archive. All 56 Rust tests and Clippy with warnings denied passed locally. The CLI reports actual archive bytes and accounted bits per weight. Real Qwen shards have not been converted, and no GPU quality or speed result exists. - Extended the existing static-CLI smoke script with two manifest-pinned synthetic shards. The local macOS CLI prepared and independently verified their streamed archive; its SHA-256 is pinned as `51688d265860172feca39e296f9142b1ed16800496bae4b06b4b8d8fa11d806e`. This script is wired into the Linux musl workflow, but hosted GitHub Actions has not run because this checkout has no remote repository. The fixture is synthetic and says nothing about full-model size or quality. - Added opt-in `model ensure-sharded-streamed`: fetches pinned GGUF shards, verifies source bytes, creates and verifies the streamed archive, then rehashes and checks source/provenance/payload on reuse. A local CLI smoke created and reused the synthetic two-shard archive and rejected a rerun with a changed level without modifying the existing file. Full 83.6 GB model preparation has not run; the local checkout had about 121 GiB free at this step, insufficient for source plus staged and final archive. No full-model size is reported yet. +- Began the pinned Qwen3.8 IQ3_S model download into a local model directory outside Git. Read only the header/directory bytes from the partially downloaded first shard and an HTTPS range of the second: 1,223 and 1 tensors respectively, 13 GGUF types, and 176,943,899,520 total elements. The second shard omits `general.architecture`. Summing the KAR-2 level-2 nested layout over these unverified directory entries gives 55,295,262,208 payload bytes (55.30 GB); this assumes every tensor uses nested encoding, excludes small container overhead, and is **not** an observed archive size or a quality result. The full shard hashes still need to match the manifest. +- The KAR writer now has an internal consuming mode for private file-backed sections: after each verified copy into its temporary archive, it removes that staged section, reducing peak disk use. The normal non-consuming writer remains available. A dedicated test verifies staged RAW removal and a valid published archive; the two-shard test now also covers a shard with no architecture metadata. Local targeted tests and Clippy with warnings denied pass. Real mixed quantization types beyond F32/F16/BF16/IQ3_S still need native decoding before the full archive can be prepared. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 845f8fb4..6873c587 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -38,6 +38,8 @@ The `kar_stream_encode` primitive writes one canonical nested section directly f `model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The real-model size remains unmeasured. Use an external model volume or the Linux GPU host for the first full preparation. +The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape. + ## GPU path For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim.