Define virtual F32 identity for IQ3_S GGUF

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 21:05:37 +02:00
parent fa911ee017
commit 4b7c29f5a4
7 changed files with 212 additions and 6 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 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. `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 source shard and the archive's concatenated source digest. Neither command decodes 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 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 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.
+186
View File
@@ -0,0 +1,186 @@
//! Experimental identity for a virtual F32 stream decoded from one all-IQ3_S
//! GGUF. The bytes are never materialized on disk. This is a preparation aid,
//! not an approval to serve a lossy KAR archive.
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
use sha2::{Digest, Sha256};
use crate::{gguf, iq3_s};
const BLOCKS_PER_BATCH: usize = 256;
#[derive(Debug)]
pub struct TensorIdentity {
pub name: String,
pub derived_offset: u64,
pub derived_bytes: u64,
pub iq3_sha256: [u8; 32],
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>,
}
/// The virtual source is the concatenation, in GGUF tensor-directory order,
/// of each tensor's dequantized IEEE-754 little-endian F32 values. No GGUF
/// header, alignment padding, tensor name, or framing appears in that stream.
/// Tensor offsets and digests refer to this stream, never to IQ3_S file 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) {
return Err("IQ3 derivation currently requires a nonempty all-IQ3_S GGUF".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 block_buffer = vec![0u8; BLOCKS_PER_BATCH * iq3_s::BLOCK_BYTES];
for tensor in &index.tensors {
if !tensor.bytes.is_multiple_of(iq3_s::BLOCK_BYTES as u64) {
return Err(format!(
"{}: IQ3_S 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 iq3_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let mut remaining = tensor.bytes;
while remaining != 0 {
let count = remaining.min(block_buffer.len() as u64) as usize;
source
.read_exact(&mut block_buffer[..count])
.map_err(|error| error.to_string())?;
iq3_hash.update(&block_buffer[..count]);
for block in block_buffer[..count]
.as_chunks::<{ iq3_s::BLOCK_BYTES }>()
.0
{
let values = iq3_s::decode_block(block)?;
for value in values {
let bytes = value.to_le_bytes();
f32_hash.update(bytes);
derived.update(bytes);
}
}
let expanded = (count / iq3_s::BLOCK_BYTES)
.checked_mul(iq3_s::BLOCK_ELEMENTS * 4)
.ok_or("derived IQ3 byte count overflow")?;
derived_bytes = derived_bytes
.checked_add(expanded as u64)
.ok_or("derived IQ3 byte count overflow")?;
remaining -= count as u64;
}
tensors.push(TensorIdentity {
name: tensor.name.clone(),
derived_offset: offset,
derived_bytes: derived_bytes - offset,
iq3_sha256: iq3_hash.finalize().into(),
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 IQ3 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 virtual_f32_identity_uses_tensor_directory_order_and_rejects_bad_source() {
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&2u64.to_le_bytes());
gguf.extend_from_slice(&0u64.to_le_bytes());
for (name, offset) in [("second", 128u64), ("first", 0)] {
string(&mut gguf, name);
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(&offset.to_le_bytes());
}
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
let data_start = gguf.len();
let mut first = [0u8; iq3_s::BLOCK_BYTES];
first[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let mut second = first;
second[..2].copy_from_slice(&0x4000u16.to_le_bytes());
gguf.extend_from_slice(&first);
gguf.resize(data_start + 128, 0);
gguf.extend_from_slice(&second);
let path =
std::env::temp_dir().join(format!("strata-iq3-identity-{}.gguf", std::process::id()));
fs::write(&path, &gguf).unwrap();
let identity = fingerprint(&path).unwrap();
assert_eq!(
identity.gguf_sha256.as_slice(),
Sha256::digest(&gguf).as_slice()
);
assert_eq!(identity.derived_bytes, 2048);
assert_eq!(identity.tensors[0].name, "second");
assert_eq!(identity.tensors[1].name, "first");
assert_eq!(identity.tensors[1].derived_offset, 1024);
let mut expected = Sha256::new();
expected.update([2.0f32.to_le_bytes(); 256].concat());
expected.update([1.0f32.to_le_bytes(); 256].concat());
assert_eq!(
identity.derived_sha256.as_slice(),
expected.finalize().as_slice()
);
gguf[0] = b'X';
fs::write(&path, gguf).unwrap();
assert!(fingerprint(&path).is_err());
fs::remove_file(path).unwrap();
}
}
+1
View File
@@ -1,5 +1,6 @@
pub mod app;
pub mod config;
pub mod derived_iq3;
pub mod doctor;
pub mod gguf;
pub mod iq3_s;
+20 -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, doctor, gguf, kar, model, prepare_preview, tokenizer, tokenizer_assets,
worker,
app, config::Config, derived_iq3, doctor, gguf, kar, model, prepare_preview, tokenizer,
tokenizer_assets, worker,
};
#[tokio::main]
@@ -54,6 +54,23 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
{
print_tensor_index(Path::new(path), true)
}
[model, action, path] if model == "model" && action == "derive-iq3-identity" => {
let identity = derived_iq3::fingerprint(Path::new(path))?;
println!("{}", serde_json::to_string_pretty(&serde_json::json!({
"derivation": "strata-next/iq3_s-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,
"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<_>>(),
}))?);
Ok(())
}
[model, action, source, output_flag, destination, levels_flag, levels]
if model == "model"
&& action == "prepare-f32-preview"
@@ -164,7 +181,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 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 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()),
}
}
+1
View File
@@ -88,3 +88,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Connected a small synthetic F32 GGUF to `model prepare-f32-preview`: it produced a verified KAR-2 archive with source SHA-256 `f2bff437d5a53e8ddf7f43ee41acf3baebb7fb5f27eefb079f5bc1634def6f2c` and archive SHA-256 `fe049ca40305d5380caaa278f34a9149ae2d5761ea9544b58a0eb73775cd6810`. The separate `model verify-kar` command passed. A valid synthetic IQ3_S GGUF was rejected by the F32 preview, without creating an archive. All 40 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This is a bounded experimental integration path, not full-model preparation.
- 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.
+1 -1
View File
@@ -20,7 +20,7 @@ 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. The IQ3_S → F32 derivation must therefore have its own digest and provenance record, with the original GGUF shard digests linked separately, or the archive format must be versioned to represent quantized source types. The preview continues to reject IQ3_S until that identity contract is implemented; it must never label IQ3_S bytes as F32 source bytes.
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.
## GPU path
+2 -1
View File
@@ -64,7 +64,8 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [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.
- [x] Decode synthetic GGUF IQ3_S source blocks in native Rust with a pinned ggml grid and bounded output.
- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors, then define a provenance-safe IQ3_S → KAR source identity contract (derived F32 source or a versioned format extension).
- [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.
- [ ] 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.