Compute mixed GGUF virtual F32 identity

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 21:19:08 +02:00
parent 11234d9da4
commit d08ebf788b
7 changed files with 280 additions and 5 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 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 verify-iq3-preview FILE.kar --source FILE.gguf`, `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, which the verification command recomputes and checks against the archive. 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 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 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 verify-iq3-preview FILE.kar --source FILE.gguf`, `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, which the verification command recomputes and checks against the archive. `derive-mixed-identity` computes the same kind of virtual stream for a GGUF mixing IQ3_S with F32/F16/BF16; it does not yet prepare KAR. 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.
+251
View File
@@ -0,0 +1,251 @@
//! Versioned virtual F32 identity for a single GGUF containing IQ3_S plus
//! F32, F16, or BF16 tensors. Preparation only; no serving quality approval.
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
use sha2::{Digest, Sha256};
use crate::{gguf, iq3_s, kar_codec};
const BUFFER_BYTES: usize = 256 * iq3_s::BLOCK_BYTES;
#[derive(Debug)]
pub struct TensorIdentity {
pub name: String,
pub source_kind: u32,
pub source_sha256: [u8; 32],
pub derived_offset: u64,
pub derived_bytes: u64,
pub f32_sha256: [u8; 32],
}
#[derive(Debug)]
pub struct Identity {
pub gguf_sha256: [u8; 32],
pub derived_sha256: [u8; 32],
pub derived_bytes: u64,
pub tensors: Vec<TensorIdentity>,
}
/// `strata-next/gguf-mixed-to-f32-le-v1`: concatenate tensor values in GGUF
/// directory order, each converted to little-endian IEEE F32. Preserve F32
/// source bits; expand F16 and BF16 with the Rust conversion below; dequantize
/// IQ3_S with the pinned ggml grid. Do not include header or alignment bytes.
pub fn fingerprint(path: &Path) -> Result<Identity, String> {
let index = gguf::tensor_index(path).map_err(|error| error.to_string())?;
if index.tensors.is_empty()
|| !index.tensors.iter().any(|tensor| tensor.kind == 21)
|| !index.tensors.iter().any(|tensor| tensor.kind != 21)
|| index
.tensors
.iter()
.any(|tensor| !matches!(tensor.kind, 0 | 1 | 21 | 30))
{
return Err("mixed derivation requires IQ3_S and F32/F16/BF16 tensors only".into());
}
let gguf_sha256 = hash_file(path)?;
let mut source = File::open(path).map_err(|error| error.to_string())?;
let mut derived = Sha256::new();
let mut derived_bytes = 0u64;
let mut tensors = Vec::with_capacity(index.tensors.len());
let mut buffer = vec![0u8; BUFFER_BYTES];
for tensor in &index.tensors {
let (block_bytes, block_elements) = match tensor.kind {
0 => (4usize, 1usize),
1 | 30 => (2, 1),
21 => (iq3_s::BLOCK_BYTES, iq3_s::BLOCK_ELEMENTS),
_ => unreachable!(),
};
if !tensor.bytes.is_multiple_of(block_bytes as u64) {
return Err(format!(
"{}: source tensor is not block-aligned",
tensor.name
));
}
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
source
.seek(SeekFrom::Start(absolute))
.map_err(|error| error.to_string())?;
let offset = derived_bytes;
let mut source_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let mut remaining = tensor.bytes;
while remaining != 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
source_hash.update(&buffer[..count]);
match tensor.kind {
0 => {
f32_hash.update(&buffer[..count]);
derived.update(&buffer[..count]);
}
1 | 30 => {
for pair in buffer[..count].as_chunks::<2>().0 {
let bits = u16::from_le_bytes(*pair);
let value = if tensor.kind == 1 {
kar_codec::f16_bits_to_f32(bits)
} else {
f32::from_bits(u32::from(bits) << 16)
};
let bytes = value.to_le_bytes();
f32_hash.update(bytes);
derived.update(bytes);
}
}
21 => {
for block in buffer[..count].as_chunks::<{ iq3_s::BLOCK_BYTES }>().0 {
for value in iq3_s::decode_block(block)? {
let bytes = value.to_le_bytes();
f32_hash.update(bytes);
derived.update(bytes);
}
}
}
_ => unreachable!(),
}
let expanded = (count / block_bytes)
.checked_mul(block_elements * 4)
.ok_or("mixed derived byte count overflow")?;
derived_bytes = derived_bytes
.checked_add(expanded as u64)
.ok_or("mixed derived byte count overflow")?;
remaining -= count as u64;
}
let tensor_bytes = derived_bytes - offset;
let shape_bytes = tensor
.dimensions
.iter()
.try_fold(4u64, |product, dim| product.checked_mul(*dim))
.ok_or("mixed derived tensor shape overflow")?;
if tensor_bytes != shape_bytes {
return Err(format!(
"{}: derived tensor size differs from shape",
tensor.name
));
}
tensors.push(TensorIdentity {
name: tensor.name.clone(),
source_kind: tensor.kind,
source_sha256: source_hash.finalize().into(),
derived_offset: offset,
derived_bytes: tensor_bytes,
f32_sha256: f32_hash.finalize().into(),
});
}
if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size
|| hash_file(path)? != gguf_sha256
{
return Err("GGUF source changed during mixed derivation".into());
}
Ok(Identity {
gguf_sha256,
derived_sha256: derived.finalize().into(),
derived_bytes,
tensors,
})
}
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();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = source
.read(&mut buffer)
.map_err(|error| error.to_string())?;
if count == 0 {
break;
}
digest.update(&buffer[..count]);
}
Ok(digest.finalize().into())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn string(out: &mut Vec<u8>, value: &str) {
out.extend_from_slice(&(value.len() as u64).to_le_bytes());
out.extend_from_slice(value.as_bytes());
}
#[test]
fn hashes_mixed_types_in_directory_order_without_gguf_padding() {
let cases = [
("bf16", 30u32, 192u64, 2u64),
("f32", 0, 128, 2),
("iq3", 21, 0, 256),
("f16", 1, 160, 2),
];
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&(cases.len() as u64).to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
for (name, kind, offset, elements) in cases {
string(&mut gguf, name);
gguf.extend_from_slice(&1u32.to_le_bytes());
gguf.extend_from_slice(&elements.to_le_bytes());
gguf.extend_from_slice(&kind.to_le_bytes());
gguf.extend_from_slice(&offset.to_le_bytes());
}
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
let data_start = gguf.len();
let mut iq3 = [0u8; iq3_s::BLOCK_BYTES];
iq3[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
gguf.extend_from_slice(&iq3);
gguf.resize(data_start + 128, 0);
for value in [3.0f32, -2.0] {
gguf.extend_from_slice(&value.to_le_bytes());
}
gguf.resize(data_start + 160, 0);
for bits in [0x3400u16, 0x4000] {
gguf.extend_from_slice(&bits.to_le_bytes());
}
gguf.resize(data_start + 192, 0);
for bits in [0x3f00u16, 0xbf80] {
gguf.extend_from_slice(&bits.to_le_bytes());
}
let path =
std::env::temp_dir().join(format!("strata-mixed-identity-{}.gguf", std::process::id()));
fs::write(&path, &gguf).unwrap();
let identity = fingerprint(&path).unwrap();
assert_eq!(identity.tensors.len(), 4);
assert_eq!(identity.tensors[0].name, "bf16");
assert_eq!(identity.tensors[1].derived_offset, 8);
assert_eq!(identity.tensors[2].derived_offset, 16);
assert_eq!(identity.tensors[3].derived_offset, 1040);
assert_eq!(identity.derived_bytes, 1048);
let mut expected = Vec::new();
for value in [0.5f32, -1.0, 3.0, -2.0] {
expected.extend_from_slice(&value.to_le_bytes());
}
for _ in 0..256 {
expected.extend_from_slice(&1.0f32.to_le_bytes());
}
for value in [0.25f32, 2.0] {
expected.extend_from_slice(&value.to_le_bytes());
}
assert_eq!(
identity.derived_sha256.as_slice(),
Sha256::digest(&expected).as_slice()
);
assert_eq!(
identity.tensors[2].source_sha256.as_slice(),
Sha256::digest(iq3).as_slice()
);
assert!(crate::derived_iq3::fingerprint(&path).is_err());
fs::remove_file(path).unwrap();
}
}
+1
View File
@@ -1,6 +1,7 @@
pub mod app;
pub mod config;
pub mod derived_iq3;
pub mod derived_mixed;
pub mod doctor;
pub mod gguf;
pub mod iq3_s;
+21 -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, doctor, gguf, kar, model, prepare_preview, tokenizer,
tokenizer_assets, worker,
app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, model, prepare_preview,
tokenizer, tokenizer_assets, worker,
};
#[tokio::main]
@@ -71,6 +71,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}))?);
Ok(())
}
[model, action, path] if model == "model" && action == "derive-mixed-identity" => {
let identity = derived_mixed::fingerprint(Path::new(path))?;
println!("{}", serde_json::to_string_pretty(&serde_json::json!({
"derivation": "strata-next/gguf-mixed-to-f32-le-v1",
"gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}))?);
Ok(())
}
[model, action, source, output_flag, destination, levels_flag, levels]
if model == "model"
&& action == "prepare-f32-preview"
@@ -212,7 +230,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 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 verify-iq3-preview FILE.kar --source FILE.gguf|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 derive-mixed-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 verify-iq3-preview FILE.kar --source FILE.gguf|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()),
}
}
+1
View File
@@ -91,3 +91,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- 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.
- Added `model verify-iq3-preview` to recompute the original and virtual F32 identities, check KAR per-tensor source records and payload CRCs, and compare the provenance sidecar with the archive hash. The synthetic IQ3 preview verified; changing the sidecar's archive digest caused rejection, and restoring it passed again. A separate `cargo build --locked` CLI smoke generated and verified a temporary one-tensor archive: virtual F32 SHA-256 `9d1f76b4ef22e4b0e1f7e8d13cd3ff91516c884e9b8aa8107c8932bfd64fed85`, archive SHA-256 `c4d4e843165aa2599206458f0550c24eaafe95c3dacffec5e736950e16d1769c`. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check passed. This is identity/integrity verification, not an assessment of model quality or GPU behavior.
- Added `model derive-mixed-identity` for one GGUF containing IQ3_S and F32/F16/BF16 tensors. A four-tensor fixture with directory order different from physical order matched the independently assembled F32 byte-stream SHA-256, including half and bfloat conversions, and the all-IQ3-only derivation rejected it. The command uses a fixed 28,160-byte source buffer and writes no expanded file. All 44 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed KAR preparation, real-model parity, and GPU quality remain open.
+2
View File
@@ -24,6 +24,8 @@ KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be
`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. `model verify-iq3-preview FILE.kar --source FILE.gguf` recomputes the virtual source, checks every KAR tensor's F32 source record, scans payload CRCs, and compares the sidecar to the source and archive. 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, real tensor parity, and the full-model quality gate remain open. Neither preview archive is eligible for serving.
`model derive-mixed-identity FILE.gguf` extends the virtual F32 identity to a single GGUF containing IQ3_S plus F32, F16, or BF16 tensors. It preserves F32 bit patterns, expands F16 and BF16 to F32, and uses the pinned IQ3_S decoder. The versioned `gguf-mixed-to-f32-le-v1` digest covers values in tensor-directory order and excludes GGUF headers and padding. The command reports original type and source digest per tensor. Mixed-model KAR preparation and provenance verification are the next steps; this command only computes identity.
## 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.
+3 -1
View File
@@ -67,7 +67,9 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [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.
- [x] Convert a small all-IQ3_S GGUF to an experimental KAR preview with virtual F32 source identity and an original-source provenance sidecar.
- [x] Recompute the IQ3-derived source against the original GGUF and verify each KAR source record, archive payload CRC, and provenance sidecar.
- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors; extend the virtual source to mixed-type and multiple GGUF shards.
- [x] Define and compute a versioned virtual F32 source for a single GGUF mixing IQ3_S with F32, F16, and BF16 tensors.
- [ ] Prepare and verify a KAR preview from the mixed virtual source; then extend it to multiple GGUF shards.
- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors.
- [ ] 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.