Add provenance-bound IQ3_S to KAR preview

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 21:10:31 +02:00
parent 4b7c29f5a4
commit 6d69ef8212
6 changed files with 239 additions and 22 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Control plane
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 prepare-f32-preview FILE.gguf --output FILE.kar --levels N`, `model inspect-kar FILE.kar`, `model verify-kar 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 identity command hashes a virtual F32 stream from a single all-IQ3_S GGUF with bounded memory; it creates no archive. `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.
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 prepare-f32-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N`, `model inspect-kar FILE.kar`, `model verify-kar 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 identity command hashes a virtual F32 stream from a single all-IQ3_S GGUF with bounded memory; its preview preparation command also writes an original-source provenance sidecar. Neither 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.
The Rust control plane provides process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and records worker readiness only after the engine emits `READY <max-context>`. An abandoned internal generation sends `STOP` and drains its terminal response before the next request; shutdown during generation sends `STOP` before `QUIT`. With tokenizer assets configured, `POST /v1/responses` can perform a restricted non-streaming text generation with `reasoning.effort: "none"`. It returns 503 while the worker is unavailable, 501 for unsupported live features or a missing tokenizer, and never fabricates a model response. Worker restart is not yet implemented.
+21 -1
View File
@@ -90,6 +90,26 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[model, action, source, output_flag, destination, levels_flag, levels]
if model == "model"
&& action == "prepare-iq3-preview"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let result = prepare_preview::prepare_iq3(
Path::new(source),
Path::new(destination),
levels.parse()?,
)?;
println!("EXPERIMENTAL IQ3_S-derived F32 KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("provenance: {}", result.provenance_path.unwrap().display());
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[model, action, path] if model == "model" && action == "inspect-kar" => {
let summary = kar::inspect(Path::new(path))?;
println!("KAR-2: {path}");
@@ -181,7 +201,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 inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model inspect-kar FILE.kar|model verify-kar 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 inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model inspect-kar FILE.kar|model verify-kar 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()),
}
}
+211 -18
View File
@@ -10,7 +10,7 @@ use std::{
use sha2::{Digest, Sha256};
use crate::{gguf, kar, kar_codec, kar_writer};
use crate::{derived_iq3, gguf, iq3_s, kar, kar_codec, kar_writer};
const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024;
const MAX_TENSORS: usize = 1000;
@@ -21,6 +21,7 @@ pub struct PreviewSummary {
pub archive: kar::Summary,
pub archive_digest: [u8; 32],
pub maximum_relative_l2: f64,
pub provenance_path: Option<PathBuf>,
}
struct PreparedTensor {
@@ -45,6 +46,23 @@ pub fn prepare_f32(
source_path: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare(source_path, destination, levels, false)
}
pub fn prepare_iq3(
source_path: &Path,
destination: &Path,
levels: u8,
) -> Result<PreviewSummary, String> {
prepare(source_path, destination, levels, true)
}
fn prepare(
source_path: &Path,
destination: &Path,
levels: u8,
iq3_source: bool,
) -> Result<PreviewSummary, String> {
if !(1..=8).contains(&levels) {
return Err("F32 preview requires 1..=8 KAR levels".into());
@@ -61,11 +79,24 @@ pub fn prepare_f32(
.architecture
.as_deref()
.ok_or("GGUF source has no architecture")?;
let source_name = source_path
let filename = source_path
.file_name()
.ok_or("GGUF source has no file name")?
.to_string_lossy();
let source_digest = hash_file(source_path)?;
let derived_identity = if iq3_source {
Some(derived_iq3::fingerprint(source_path)?)
} else {
None
};
let source_name = if iq3_source {
format!("{filename}#derived-f32-le-v1")
} else {
filename.to_string()
};
let original_digest = match &derived_identity {
Some(identity) => identity.gguf_sha256,
None => hash_file(source_path)?,
};
let staging_name = format!(
"{}.parts-{}",
destination
@@ -82,10 +113,11 @@ pub fn prepare_f32(
let mut maximum_relative_l2 = 0.0f64;
let mut prepared = Vec::with_capacity(index.tensors.len());
for (number, tensor) in index.tensors.iter().enumerate() {
if tensor.kind != 0 || tensor.dimensions.len() > 4 {
if tensor.kind != if iq3_source { 21 } else { 0 } || tensor.dimensions.len() > 4 {
return Err(format!(
"{}: F32 preview supports only F32 tensors with up to four dimensions",
tensor.name
"{}: preview supports only {} tensors with up to four dimensions",
tensor.name,
if iq3_source { "IQ3_S" } else { "F32" }
));
}
let elements = tensor
@@ -111,13 +143,32 @@ pub fn prepare_f32(
source_file
.read_exact(&mut raw)
.map_err(|error| error.to_string())?;
let tensor_digest = Sha256::digest(&raw).into();
let weights = raw
.as_chunks::<4>()
.0
.iter()
.map(|chunk| f32::from_le_bytes(*chunk))
.collect::<Vec<_>>();
let (weights, tensor_digest, source_offset) = if let Some(identity) = &derived_identity {
let derived = &identity.tensors[number];
if derived.name != tensor.name || Sha256::digest(&raw).as_slice() != derived.iq3_sha256
{
return Err("IQ3_S tensor differs from derived source identity".into());
}
let mut weights = vec![0.0f32; elements as usize];
iq3_s::decode_into(&raw, &mut weights)?;
let mut digest = Sha256::new();
for value in &weights {
digest.update(value.to_le_bytes());
}
if digest.finalize().as_slice() != derived.f32_sha256 {
return Err("decoded F32 tensor differs from derived source identity".into());
}
(weights, derived.f32_sha256, derived.derived_offset)
} else {
let digest = Sha256::digest(&raw).into();
let weights = raw
.as_chunks::<4>()
.0
.iter()
.map(|chunk| f32::from_le_bytes(*chunk))
.collect::<Vec<_>>();
(weights, digest, absolute)
};
drop(raw);
let normalized = kar_codec::normalize_for_calibration(&weights, 32)?;
let calibration = kar_codec::fit_topdown(&normalized.values, levels)?;
@@ -159,7 +210,7 @@ pub fn prepare_f32(
dims: &tensor.dimensions,
source_dtype: 0,
source_digest: tensor_digest,
source_offset: absolute,
source_offset,
data: kar_writer::TensorData::Nested {
group: 32,
nesting: 0,
@@ -176,7 +227,7 @@ pub fn prepare_f32(
name: tensor.name.clone(),
dims: tensor.dimensions.clone(),
source_digest: tensor_digest,
source_offset: absolute,
source_offset,
section_path,
section_bytes: section.bytes,
section_digest: section.digest,
@@ -187,7 +238,7 @@ pub fn prepare_f32(
.map_err(|error| error.to_string())?
.len()
!= index.summary.file_size
|| hash_file(source_path)? != source_digest
|| hash_file(source_path)? != original_digest
{
return Err("GGUF source changed during F32 preparation".into());
}
@@ -212,24 +263,90 @@ pub fn prepare_f32(
},
})
.collect::<Vec<_>>();
let builder = format!("strata-next/experimental-f32-topdown-v1:g32:l{levels}:sample-all");
let builder = format!(
"strata-next/experimental-{}-topdown-v1:g32:l{levels}:sample-all",
if iq3_source { "iq3-derived-f32" } else { "f32" }
);
let (source_digest, source_bytes) = derived_identity
.as_ref()
.map(|identity| (identity.derived_sha256, identity.derived_bytes))
.unwrap_or((original_digest, index.summary.file_size));
let source = kar_writer::SourceIdentity {
name: &source_name,
architecture,
builder: &builder,
digest: source_digest,
total_elements,
bytes: index.summary.file_size,
bytes: source_bytes,
};
let archive = kar_writer::write_archive(destination, &source, &tensors)?;
let archive_digest = hash_file(destination)?;
let provenance_path = if let Some(identity) = derived_identity {
let path = destination.with_file_name(format!(
"{}.provenance.json",
destination
.file_name()
.ok_or("KAR destination has no file name")?
.to_string_lossy()
));
let manifest = serde_json::json!({
"schema": "strata-next/iq3-preview-provenance-v1",
"derivation": "strata-next/iq3_s-to-f32-le-v1",
"original_gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"archive_sha256": hex::encode(archive_digest),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"iq3_sha256": hex::encode(tensor.iq3_sha256),
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
});
if let Err(error) = write_provenance(&path, &manifest) {
let _ = fs::remove_file(destination);
return Err(error);
}
Some(path)
} else {
None
};
Ok(PreviewSummary {
archive,
archive_digest,
maximum_relative_l2,
provenance_path,
})
}
fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
if fs::symlink_metadata(path).is_ok() {
return Err("provenance destination already exists".into());
}
let temporary = path.with_file_name(format!(
"{}.part",
path.file_name()
.ok_or("provenance path has no file name")?
.to_string_lossy()
));
let result = (|| {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.map_err(|error| error.to_string())?;
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
use std::io::Write;
file.write_all(b"\n").map_err(|error| error.to_string())?;
file.sync_all().map_err(|error| error.to_string())?;
fs::hard_link(&temporary, path).map_err(|error| error.to_string())?;
Ok(())
})();
let _ = fs::remove_file(&temporary);
result
}
fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
@@ -356,4 +473,80 @@ mod tests {
assert!(!output.exists());
fs::remove_file(source_path).unwrap();
}
#[test]
fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() {
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");
string(&mut gguf, "expert");
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&256u64.to_le_bytes());
gguf.extend_from_slice(&21u32.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
let mut block = [0u8; iq3_s::BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
for (index, byte) in block[2..66].iter_mut().enumerate() {
*byte = (index as u8).wrapping_mul(3);
}
block[74] = 0x55;
gguf.extend_from_slice(&block);
let base =
std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id()));
let source_path = base.with_extension("gguf");
let output = base.with_extension("kar");
let provenance = output.with_file_name(format!(
"{}.provenance.json",
output.file_name().unwrap().to_string_lossy()
));
let _ = fs::remove_file(&output);
let _ = fs::remove_file(&provenance);
fs::write(&source_path, gguf).unwrap();
let identity = derived_iq3::fingerprint(&source_path).unwrap();
let result = prepare_iq3(&source_path, &output, 2).unwrap();
assert_eq!(result.archive.source_digest, identity.derived_sha256);
assert_eq!(result.archive.source_bytes, identity.derived_bytes);
assert_eq!(
result.provenance_path.as_deref(),
Some(provenance.as_path())
);
assert_eq!(kar::verify(&output).unwrap(), result.archive);
let record: serde_json::Value =
serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap();
assert_eq!(
record["original_gguf_sha256"],
hex::encode(identity.gguf_sha256)
);
assert_eq!(
record["derived_f32_sha256"],
hex::encode(identity.derived_sha256)
);
assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest));
assert!(result.maximum_relative_l2.is_finite());
let blocked_output = base.with_file_name(format!(
"strata-preview-iq3-blocked-{}.kar",
std::process::id()
));
let blocked_provenance = blocked_output.with_file_name(format!(
"{}.provenance.json",
blocked_output.file_name().unwrap().to_string_lossy()
));
let _ = fs::remove_file(&blocked_output);
fs::write(&blocked_provenance, b"reserved").unwrap();
assert!(
prepare_iq3(&source_path, &blocked_output, 2)
.unwrap_err()
.contains("provenance destination already exists")
);
assert!(!blocked_output.exists());
fs::remove_file(blocked_provenance).unwrap();
fs::remove_file(provenance).unwrap();
fs::remove_file(output).unwrap();
fs::remove_file(source_path).unwrap();
}
}
+1
View File
@@ -89,3 +89,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Refactored the F32 preview to write each tensor's canonical NESTED section to a private staging directory, then assemble the KAR archive from file-backed sections. The native section bytes match the in-memory writer. A two-tensor fixture succeeds and leaves no staging directory; corrupting the second tensor to NaN fails after the first section and also cleans staging without publishing an archive. The preview source-size and per-tensor limits remain; IQ3_S source decoding and full-model quality remain open.
- Added a native IQ3_S CPU block decoder with the pinned ggml grid table (SHA-256 `bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`). A deterministic mixed 110-byte block produced 256 F32 values whose byte digest `cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec` matches an independent Python calculation from the upstream layout; constant, sign, multi-block, and malformed-scale cases also pass. All 41 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This has not been compared with a real tensor or GPU. The ggml MIT license is copied into the control binary and shown by `--ggml-license`.
- Added `model derive-iq3-identity` for a single all-IQ3_S GGUF. It hashes the original GGUF and a virtual contiguous little-endian F32 stream, with per-tensor original/derived digests and offsets, using a 256-block input buffer; no expanded file is written. A two-tensor fixture with reversed physical and directory order matched an independently assembled F32 stream digest. All 42 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed tensor types, shard sets, real-model parity, and KAR publication remain unverified.
- Added `model prepare-iq3-preview` for a small all-IQ3_S GGUF. A synthetic one-tensor input produced a KAR-2 archive with the virtual F32 source digest and a provenance sidecar binding the original GGUF, derived stream, and archive SHA-256 values. The archive passed payload verification. A preexisting sidecar blocked publication and the newly written archive was removed. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source decoder and compressed output have not passed a real-model quality gate or GPU test.
+3 -1
View File
@@ -20,7 +20,9 @@ An experimental native `kar_codec::encode_with_boundaries` converts one in-memor
The Rust `iq3_s` module now decodes one GGUF IQ3_S block (110 bytes, 256 F32 outputs) or a caller-sized sequence of complete blocks. Its 512-entry grid is copied from the pinned Strata/ggml tree, checked by SHA-256, and carries the ggml MIT notice in the binary through `--ggml-license`. Synthetic block output matches an independent Python calculation. Real tensor parity still needs the upstream CPU oracle and real-model fixtures.
KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be identified directly as a KAR-2 tensor source without violating that field. `model derive-iq3-identity FILE.gguf` now computes a versioned **virtual F32 source identity** for a single GGUF whose tensors are all IQ3_S. It streams dequantized little-endian F32 values in GGUF tensor-directory order, reports the derived stream and per-tensor digests/offsets alongside the original GGUF and IQ3 tensor digests, and does not materialize the expanded data. A future KAR writer can use F32 `source_dtype`, these derived offsets and digests, and the derived stream digest without pretending IQ3_S bytes are F32 bytes. The original GGUF digest belongs in a separate provenance manifest; the existing `verify-kar --manifest` checks physical source files and must not be used as proof of this virtual stream. Mixed-type shards, multi-shard identity, manifest publication and independent verification remain open. The F32 preparation preview continues to reject IQ3_S; no IQ3_S KAR is produced yet.
KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be identified directly as a KAR-2 tensor source without violating that field. `model derive-iq3-identity FILE.gguf` computes a versioned **virtual F32 source identity** for a single GGUF whose tensors are all IQ3_S. It streams dequantized little-endian F32 values in GGUF tensor-directory order, reports the derived stream and per-tensor digests/offsets alongside the original GGUF and IQ3 tensor digests, and does not materialize the expanded data. The original GGUF digest belongs in a separate provenance manifest; the existing `verify-kar --manifest` checks physical source files and must not be used as proof of this virtual stream.
`model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N` uses that identity to create a small, explicitly experimental KAR archive with F32 source dtype, virtual F32 tensor offsets/digests, and the derived stream digest. The original GGUF and IQ3 digests go into `FILE.kar.provenance.json`, published after the archive and bound to its SHA-256. If provenance publication fails, the new archive is removed. It shares the F32 preview's 64 MiB source, 1000 tensor, and 1 million elements per tensor limits; source types must all be IQ3_S. Mixed-type shards, multi-shard identity, independent archive/provenance verification, real tensor parity, and the full-model quality gate remain open. Neither preview archive is eligible for serving.
## GPU path
+2 -1
View File
@@ -65,7 +65,8 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [x] Spool each preview tensor as a canonical NESTED section and assemble the archive from file-backed sections; clean staging after success or failure.
- [x] Decode synthetic GGUF IQ3_S source blocks in native Rust with a pinned ggml grid and bounded output.
- [x] Define and compute a versioned virtual F32 stream identity for a bounded-memory, all-IQ3_S GGUF, retaining original GGUF and tensor digests separately.
- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors; extend the virtual source to mixed-type and multiple GGUF shards, publish a provenance manifest, and independently verify the derived identity against the future KAR archive.
- [x] Convert a small all-IQ3_S GGUF to an experimental KAR preview with virtual F32 source identity and an original-source provenance sidecar.
- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors; extend the virtual source to mixed-type and multiple GGUF shards, and independently verify the sidecar against the archive and original source.
- [ ] Feed the native writer from a bounded-memory GGUF tensor iterator and a native KAR encoder; implement `model prepare` on real shards.
- [ ] Make one-command `serve` fetch, verify, and prepare missing model assets, then reuse the verified compressed archive.
- [ ] Compare KAR reconstruction with its CPU oracle; run full-model quality before making the compressed path a default.