Add deterministic KAR CUDA smoke fixture

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 22:40:15 +02:00
parent be8e79930c
commit d07e0d05d8
6 changed files with 106 additions and 7 deletions
+1 -1
View File
@@ -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. `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.
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 smoke-fixture --output FILE.kar` creates a deterministic model-free archive, and `model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes it on CPU 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.
+85
View File
@@ -0,0 +1,85 @@
//! Deterministic, model-free archive for CPU/CUDA decode parity checks.
use std::path::Path;
use sha2::{Digest, Sha256};
use crate::{kar, kar_codec, kar_writer};
pub struct FixtureSummary {
pub archive: kar::Summary,
pub archive_digest: [u8; 32],
pub decoded_fnv1a64: u64,
}
pub fn write(destination: &Path) -> Result<FixtureSummary, String> {
let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(8);
let encoded = kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2)?;
let book1 = [0xb800u16, 0x3800];
let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00];
let books: [&[u16]; 2] = [&book1, &book2];
let planes = encoded.planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let mut source_bytes = Vec::with_capacity(weights.len() * 4);
for weight in &weights {
source_bytes.extend_from_slice(&weight.to_le_bytes());
}
let source_digest: [u8; 32] = Sha256::digest(&source_bytes).into();
let source = kar_writer::SourceIdentity {
name: "strata-next-smoke-f32",
architecture: "synthetic",
builder: "strata-next/smoke-topdown-g32-l2-v1",
digest: source_digest,
total_elements: weights.len() as u64,
bytes: source_bytes.len() as u64,
};
let tensor = [kar_writer::Tensor {
name: "smoke.expert",
dims: &[32],
source_dtype: 0,
source_digest,
source_offset: 0,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &encoded.scales,
books: &books,
planes: &planes,
},
}];
let archive = kar_writer::write_archive(destination, &source, &tensor)?;
let decoded = kar::decode_preview_tensor(destination, "smoke.expert", 2)?;
let archive_digest =
Sha256::digest(std::fs::read(destination).map_err(|e| e.to_string())?).into();
Ok(FixtureSummary {
archive,
archive_digest,
decoded_fnv1a64: kar::f32_fnv1a64(&decoded),
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn archive_fixture_decodes_from_published_bytes_and_rejects_overwrite() {
let path = std::env::temp_dir().join(format!(
"strata-kar-fixture-{}-{}.kar",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let created = write(&path).unwrap();
assert_eq!(created.archive.tensor_count, 1);
let decoded = kar::decode_preview_tensor(&path, "smoke.expert", 2).unwrap();
assert_eq!(&decoded[..4], &[-0.75, -0.25, 0.25, 0.75]);
assert_eq!(created.decoded_fnv1a64, kar::f32_fnv1a64(&decoded));
assert!(write(&path).is_err());
std::fs::remove_file(path).unwrap();
}
}
+1
View File
@@ -8,6 +8,7 @@ pub mod iq3_s;
mod iq3s_grid;
pub mod kar;
pub mod kar_codec;
pub mod kar_fixture;
pub mod kar_writer;
pub mod model;
pub mod model_pipeline;
+13 -3
View File
@@ -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, model, model_pipeline,
prepare_preview, tokenizer, tokenizer_assets, worker,
app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, model,
model_pipeline, prepare_preview, tokenizer, tokenizer_assets, worker,
};
#[tokio::main]
@@ -17,6 +17,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
doctor::report()?;
Ok(())
}
[model, action, flag, output]
if model == "model" && action == "smoke-fixture" && flag == "--output" =>
{
let result = kar_fixture::write(Path::new(output))?;
println!("KAR-2 smoke fixture: {output}");
println!("tensor=smoke.expert elements=32 level=2");
println!("archive_sha256={}", hex::encode(result.archive_digest));
println!("output_fnv1a64={:x}", result.decoded_fnv1a64);
Ok(())
}
[model, action, manifest, flag, output]
if model == "model" && flag == "--output" && action == "fetch" =>
{
@@ -368,7 +378,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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 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()),
_ => Err("usage: strata-next [serve|doctor|--ggml-license|model smoke-fixture --output FILE.kar|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()),
}
}
+2
View File
@@ -19,6 +19,8 @@ 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 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.
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.
+4 -3
View File
@@ -2,13 +2,14 @@
`vendor/libkar.h` and `vendor/libkar.cu` are copied unchanged from local `koference` commit `806d2398ae1daaceb2917242911e5680cbfb3608`, paths `r08/code/libkar.h` and `r08/code/libkar.cu`. Their SHA-256 values are `1d725069fd2c275423f5db70fb4190e7d51760e0c48a2a5ebe8c91993936ca92` and `331babd2a2f260abb7de602d414edd97399542ec1bccb23ffcdfad69dc0ade28` respectively. Keep these bytes and upstream provenance traceable when making local changes.
On Linux with CUDA 13 and a supported NVIDIA GPU:
On Linux with CUDA 13 and a supported NVIDIA GPU, create a model-free fixture and compare its CPU and GPU decode checksums:
```sh
strata-next model smoke-fixture --output /tmp/strata-smoke.kar
cmake -S gpu/kar -B artifacts/kar-gpu-build -G Ninja -DCMAKE_CUDA_ARCHITECTURES=120
cmake --build artifacts/kar-gpu-build --target strata-kar-gpu-smoke
artifacts/kar-gpu-build/strata-kar-gpu-smoke /path/to/model.kar TENSOR_NAME 2 30
strata-next model checksum-kar-preview /path/to/model.kar TENSOR_NAME 2
artifacts/kar-gpu-build/strata-kar-gpu-smoke /tmp/strata-smoke.kar smoke.expert 2 30
strata-next model checksum-kar-preview /tmp/strata-smoke.kar smoke.expert 2
```
The smoke program validates the KAR container and payload CRCs, reserves a chosen tensor's compressed level prefix in VRAM, decodes it on a CUDA stream, and reports a warm kernel median over the requested iterations. Compare `output_fnv1a64` with the native CPU command above using the same archive, tensor, and level. This is a **kernel smoke measurement**, not an end-to-end inference comparison or a model quality result. It does not yet link the decoder into Strata's serving path. Use the original model digest, archive digest, driver/CUDA versions, GPU, tensor, cache state, and iteration count when recording results.