Decode bounded KAR tensor ranges and validate real archive roundtrip

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 00:17:52 +02:00
parent c0739fca17
commit 9b6787a77d
5 changed files with 220 additions and 9 deletions
@@ -0,0 +1,89 @@
//! Independently decode a bounded KAR range and compare it with GGUF values.
//! The one-tensor GGUF and KAR inputs stay outside Git. This is a CPU diagnostic.
use std::{
env,
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
use strata_control::{ggml_bridge, gguf, kar};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = env::args().skip(1);
let usage = "usage: compare-kar-range FILE.gguf FILE.kar LEVEL START COUNT";
let source_path = args.next().ok_or(usage)?;
let archive_path = args.next().ok_or(usage)?;
let level: u8 = args.next().ok_or(usage)?.parse()?;
let start: usize = args.next().ok_or(usage)?.parse()?;
let count: usize = args.next().ok_or(usage)?.parse()?;
if args.next().is_some() || count == 0 || count > 1_000_000 {
return Err(usage.into());
}
let source_path = Path::new(&source_path);
let archive_path = Path::new(&archive_path);
let index = gguf::tensor_index(source_path)?;
if index.tensors.len() != 1 {
return Err("diagnostic source must contain exactly one tensor".into());
}
let tensor = &index.tensors[0];
let (block_elements, block_bytes) = match tensor.kind {
20 => (32usize, 18usize),
21 => (256, 110),
_ => return Err("diagnostic supports IQ4_NL and IQ3_S sources".into()),
};
let end = start.checked_add(count).ok_or("GGUF range overflow")?;
let elements = tensor
.dimensions
.iter()
.try_fold(1usize, |n, d| n.checked_mul(usize::try_from(*d).ok()?))
.ok_or("GGUF element count overflow")?;
if end > elements {
return Err("GGUF range exceeds tensor".into());
}
let reconstructed = kar::decode_tensor_range(archive_path, &tensor.name, level, start, count)?;
let first_block = start / block_elements;
let final_block = end.div_ceil(block_elements);
let first_block_bytes = first_block
.checked_mul(block_bytes)
.and_then(|n| u64::try_from(n).ok())
.ok_or("GGUF offset overflow")?;
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|n| n.checked_add(first_block_bytes))
.ok_or("GGUF offset overflow")?;
let mut source = File::open(source_path)?;
source.seek(SeekFrom::Start(absolute))?;
let mut block = vec![0u8; block_bytes];
let mut decoded = vec![0.0f32; block_elements];
let mut error_sum = 0.0f64;
let mut reference_sum = 0.0f64;
let mut maximum_absolute_error = 0.0f64;
for number in first_block..final_block {
source.read_exact(&mut block)?;
ggml_bridge::decode_into(tensor.kind, &block, &mut decoded)?;
let begin = start.max(number * block_elements);
let finish = end.min((number + 1) * block_elements);
for position in begin..finish {
let reference = f64::from(decoded[position - number * block_elements]);
let value = f64::from(reconstructed[position - start]);
let error = (reference - value).abs();
error_sum += error * error;
reference_sum += reference * reference;
maximum_absolute_error = maximum_absolute_error.max(error);
}
}
let relative_l2 = if reference_sum == 0.0 {
error_sum.sqrt()
} else {
(error_sum / reference_sum).sqrt()
};
println!(
"{}: {count} archived F32 values decoded at level {level}, start {start}; relative L2 {relative_l2:.8}, maximum absolute error {maximum_absolute_error:.8}",
tensor.name
);
Ok(())
}
+124 -7
View File
@@ -49,6 +49,29 @@ pub fn verify(path: &Path) -> Result<Summary, String> {
/// 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<Vec<f32>, String> {
decode_tensor_inner(path, name, level, 0, None)
}
/// Decode at most one million values from an arbitrary offset of a nested
/// tensor. Only the relevant scales and plane words are read into memory.
/// This is a CPU quality oracle, not a serving implementation.
pub fn decode_tensor_range(
path: &Path,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Result<Vec<f32>, String> {
decode_tensor_inner(path, name, level, start, Some(count))
}
fn decode_tensor_inner(
path: &Path,
name: &str,
level: u8,
start: usize,
count: Option<usize>,
) -> Result<Vec<f32>, String> {
verify(path)?;
let mut file = File::open(path).map_err(|error| error.to_string())?;
let header = read_region(&mut file, 0, HEADER_BYTES)?;
@@ -83,15 +106,45 @@ pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f
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 count = count.unwrap_or(elements);
let end = start
.checked_add(count)
.ok_or("KAR decode range overflow")?;
if count == 0 || count > 1_000_000 || end > elements {
return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into());
}
let group = u16_at(record, 46);
let group_size = usize::from(group);
if group_size == 0 {
return Err("KAR group is zero".into());
}
let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?;
let base_group = start / group_size;
let end_group = end.div_ceil(group_size);
let base_element = base_group
.checked_mul(group_size)
.ok_or("KAR decode base overflow")?;
let local_padded = (end_group - base_group)
.checked_mul(group_size)
.ok_or("KAR decode padded size overflow")?;
if base_element
.checked_add(local_padded)
.is_none_or(|end| end > padded)
{
return Err("KAR decode range exceeds padded tensor".into());
}
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")?,
u64_at(record, 64)
.checked_add(
(base_group as u64)
.checked_mul(2)
.ok_or("KAR scale offset overflow")?,
)
.ok_or("KAR scale offset overflow")?,
(end_group - base_group)
.checked_mul(2)
.ok_or("KAR scale byte count overflow")?,
)?;
let scales = scale_bytes
.as_chunks::<2>()
@@ -110,7 +163,13 @@ pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect::<Vec<_>>();
let plane_stride = u64::from(u32_at(record, 104));
let plane_bytes = padded / 32 * 4;
let plane_bytes = local_padded / 32 * 4;
let plane_base = u64::try_from(
(base_element / 32)
.checked_mul(4)
.ok_or("KAR plane offset overflow")?,
)
.map_err(|_| "KAR plane offset overflow")?;
let mut planes = Vec::with_capacity(usize::from(level));
for plane in 0..u64::from(level) {
let offset = u64_at(record, 96)
@@ -119,6 +178,7 @@ pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f
.checked_mul(plane_stride)
.ok_or("KAR plane offset overflow")?,
)
.and_then(|offset| offset.checked_add(plane_base))
.ok_or("KAR plane offset overflow")?;
let bytes = read_region(&mut file, offset, plane_bytes)?;
planes.push(
@@ -131,8 +191,15 @@ pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f
);
}
let plane_refs = planes.iter().map(Vec::as_slice).collect::<Vec<_>>();
let mut output = vec![0.0f32; elements];
kar_codec::decode_range(&scales, &book, &plane_refs, group, 0, &mut output)?;
let mut output = vec![0.0f32; count];
kar_codec::decode_range(
&scales,
&book,
&plane_refs,
group,
start - base_element,
&mut output,
)?;
Ok(output)
}
@@ -523,6 +590,7 @@ fn round_up(value: u64, alignment: u64) -> Option<u64> {
mod tests {
use super::*;
use crate::model::ModelFile;
use crate::{kar_codec, kar_writer};
use std::fs;
fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
@@ -679,4 +747,53 @@ mod tests {
assert!(inspect(&path).unwrap_err().contains("length"));
fs::remove_file(path).unwrap();
}
#[test]
fn bounded_archive_range_decode_crosses_scale_and_plane_groups() {
let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24);
let encoded =
kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap();
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 source = kar_writer::SourceIdentity {
name: "range-fixture",
architecture: "synthetic",
builder: "strata-next/kar-range-test",
digest: Sha256::digest(b"source").into(),
total_elements: 96,
bytes: 384,
};
let tensor = [kar_writer::Tensor {
name: "expert",
dims: &[96],
source_dtype: 0,
source_digest: Sha256::digest(b"weights").into(),
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 path =
std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id()));
let _ = fs::remove_file(&path);
kar_writer::write_archive(&path, &source, &tensor).unwrap();
let full = decode_preview_tensor(&path, "expert", 2).unwrap();
for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] {
assert_eq!(
decode_tensor_range(&path, "expert", 2, start, count).unwrap(),
full[start..start + count]
);
}
assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err());
assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err());
fs::remove_file(path).unwrap();
}
}
+2
View File
@@ -108,3 +108,5 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- `cargo run --locked --release --example compare-iq3-s -- <external-sample-gguf> 262144` compared every block in the sampled real IQ3_S slice: **262,144 blocks / 67,108,864 F32 values were bit-identical** between the independent Rust decoder and the pinned ggml C decoder. This is a non-lossy decoder parity check on source bytes from the incomplete first shard; the complete shard still needs manifest SHA-256 verification.
- Built the committed static-CLI Dockerfile on an arm64 Linux container with `RUST_TARGET=aarch64-unknown-linux-musl`. The resulting single `strata-next` ELF is 14 MiB (`file` reports `statically linked`), SHA-256 `3faa76d410f08134cb39bc77009674ffba8e9a3190bfa7af0099028ed5282285`. The `scratch` image ran `--version` successfully and independently verified the real-slice level-2 KAR archive through a read-only bind mount, including manifest source hashes, provenance, source records, and payload CRCs. This validates the Linux/arm64 static control-plane/CLI artifact, not the x86_64 release path or a CUDA-enabled inference runtime. Hosted GitHub Actions still has not run because this checkout has no GitHub repository or remote.
- The same reproducible sampler has an `--profile expert` option using the same 28,835,840-byte IQ3_S slice plus a 28,800,000-byte leading slice of the much larger `blk.0.ffn_down_exps.weight` IQ4_NL tensor (absolute GGUF offset 913,711,104). The two minimal GGUF inputs total 57,636,160 bytes. Level 2 produced a verified 36,973,056-byte KAR-2 archive (64.1491% of sampled input), SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, with maximum tensor relative L2 **0.33925502**. Level 3 produced a verified 51,761,664-byte archive (89.8076%), SHA-256 `1f94757878575541d3a1568e7ba8d9e680ba6afed2c1199ae63d4c342a6203f8`, with maximum tensor relative L2 **0.16425464**. These are rates for selected slices from an incomplete shard, not an estimate with validated uncertainty for the full model, and neither rate is approved for serving.
- The first complete Qwen shard was fetched and matched its manifest SHA-256 `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`. Repeating `scripts/measure-real-sample.py --profile expert --levels 2 --source-sha256 <digest>` on this verified file reproduced the same two slice digests, 36,973,056-byte archive, archive SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, and maximum relative L2 0.33925502. The second source shard is still downloading.
- Added bounded CPU decode of an arbitrary nested KAR tensor range, reading only the relevant scales and bit-plane words after archive verification. A 96-element synthetic archive test covers ranges crossing group boundaries. On the verified-source level-2 expert sample, `compare-kar-range` independently decoded three one-million-value archive ranges and compared them with pinned ggml source decoding: IQ3_S at starts 0 and 33,000,013 had relative L2 0.32941509 and 0.32867352; IQ4_NL at start 25,000,017 had 0.34136948. The same IQ4_NL range from the level-3 archive had 0.16519821. This checks stored archive reconstruction on selected ranges, not GPU execution or model-level quality.
+3 -1
View File
@@ -34,7 +34,9 @@ The experimental `kar_sample` primitive normalizes these streamed values in reus
The `kar_stream_encode` primitive writes one canonical nested section directly from bounded GGUF chunks using the supplied calibration. It keeps only a group, source chunk, and buffered file writers in memory, hashes both physical and virtual sources, and computes tensor relative L2. A synthetic section matches the existing in-memory writer byte for byte and passes KAR-2 archive verification; an IQ3_S stream crossing a chunk boundary preserves source and derived digests.
`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. `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 two-shard F32/IQ3_S test also reconstructs one tensor from the archive on CPU. Real target shards, rate choice, full-model quality, and the Linux GPU loader still need validation. This command is experimental and its output is not eligible for serving.
`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. `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 two-shard F32/IQ3_S test also reconstructs one tensor from the archive on CPU. The first real target shard is verified and selected slices were prepared; the second shard, 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 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.
`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.
+2 -1
View File
@@ -61,6 +61,7 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [x] Stream pre-encoded NESTED sections into KAR-2 with checked section geometry, finite f16 values, zero padding, and digest verification.
- [x] Encode a synthetic f32 tensor to native KAR scales and bit planes using supplied calibration; keep the lossy path experimental.
- [x] Decode a selected KAR bit-plane prefix into a caller-sized CPU buffer for numerical tests.
- [x] Decode a bounded arbitrary range of a large nested KAR tensor from stored archive bytes and compare selected real GGUF ranges with pinned ggml values.
- [x] Fit experimental top-down nested boundaries and f16 books from a supplied normalized sample; match pinned koference synthetic oracles.
- [x] Wire a small F32 GGUF through native calibration, encoding, reconstruction check, and verified KAR publication under an explicit preview command.
- [x] Spool each preview tensor as a canonical NESTED section and assemble the archive from file-backed sections; clean staging after success or failure.
@@ -106,6 +107,6 @@ Pull requests and main commits run Rust format, Clippy, tests, synthetic replay,
## Current status
P0 has local CI assets and a 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`; the real two-shard model download is in progress. P2 has bounded GGUF indexing, native tokenization, pinned ggml CPU decoding of all target quantized kinds, and an experimental bounded-memory sharded GGUF-to-KAR path with source and archive verification. Real-data slices produced verified KAR archives: a small IQ4_NL slice gave 72.2% input size and 0.405 maximum relative L2 error at level 2, while level 3 grew to 101.1%; a larger expert IQ4_NL slice gave 64.1%/0.339 at level 2 and 89.8%/0.164 at level 3. The sampled IQ3_S values matched the pinned ggml decoder bit for bit, but the full source shard is not yet SHA-256 verified. 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 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`; the first real shard passed its manifest SHA-256 and the second is downloading. P2 has bounded GGUF indexing, native tokenization, pinned ggml CPU decoding of all target quantized kinds, and an experimental bounded-memory sharded GGUF-to-KAR path with source and archive verification. Real-data slices produced verified KAR archives: a small IQ4_NL slice gave 72.2% input size and 0.405 maximum relative L2 error at level 2, while level 3 grew to 101.1%; a larger expert IQ4_NL slice gave 64.1%/0.339 at level 2 and 89.8%/0.164 at level 3. The 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).