test(dequant): bit-exact parity of 23 block types vs pinned gguf-py and iq_fixture
scripts/offline/diff_dequant.py (live, 32 rows x 3 seeds through export-tensor-f32) and a committed golden with an integration test over the production visitor. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
debfbd0941
commit
f2ec56325c
@@ -0,0 +1,62 @@
|
||||
//! Dequantization versus the pinned gguf-py (`quants.dequantize`, llama.cpp 3cf03257) and `tools/iq_fixture.py`.
|
||||
//!
|
||||
//! `tests/fixtures/offline/dequant_oracle.json` holds one seeded 256-value row of each of 23 block types and the
|
||||
//! oracle's float32 bits (`scripts/offline/gen_goldens.py dequant_oracle`; `scripts/offline/diff_dequant.py` runs
|
||||
//! 32 rows x 3 seeds live). The production visitor (`gguf_f32_stream::visit`: independent Rust decoders where they
|
||||
//! exist, the pinned ggml C bridge otherwise) must reproduce every float bit for bit. Q8_K has no gguf-py
|
||||
//! dequantizer; its reference is `d * qs`.
|
||||
use serde_json::Value;
|
||||
use std::io::Cursor;
|
||||
use strata_control::{gguf, gguf_f32_stream};
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_block_type_decodes_bit_exactly_like_gguf_py() {
|
||||
let golden: Value =
|
||||
serde_json::from_str(include_str!("fixtures/offline/dequant_oracle.json")).unwrap();
|
||||
let types = golden["types"].as_array().unwrap();
|
||||
assert_eq!(types.len(), 23);
|
||||
for entry in types {
|
||||
let name = entry["name"].as_str().unwrap();
|
||||
let kind = entry["kind"].as_u64().unwrap() as u32;
|
||||
let blocks = unhex(entry["blocks_hex"].as_str().unwrap());
|
||||
let want = unhex(entry["f32_hex"].as_str().unwrap());
|
||||
let (elements, bytes) =
|
||||
gguf::block_geometry(kind).unwrap_or_else(|| panic!("{name}: geometry"));
|
||||
assert_eq!(
|
||||
blocks.len() as u64,
|
||||
golden["elements"].as_u64().unwrap() / elements * bytes,
|
||||
"{name}"
|
||||
);
|
||||
let mut got = Vec::new();
|
||||
gguf_f32_stream::visit(
|
||||
&mut Cursor::new(blocks.clone()),
|
||||
0,
|
||||
kind,
|
||||
blocks.len() as u64,
|
||||
|raw, f32| {
|
||||
assert_eq!(raw.len() as u64 / bytes * elements, f32.len() as u64 / 4);
|
||||
got.extend_from_slice(f32);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let differing = got
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(want.as_chunks::<4>().0)
|
||||
.filter(|(a, b)| a != b)
|
||||
.count();
|
||||
assert_eq!(
|
||||
(got.len(), differing),
|
||||
(want.len(), 0),
|
||||
"{name} (kind {kind})"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dequantization parity: `strata-next model export-tensor-f32` (the production visitor: independent Rust decoders
|
||||
for IQ2_S/IQ3_S/IQ3_XXS/IQ4_NL/IQ4_XS/Q2_0/Q4_K/Q5_K/Q6_K/Q8_0, the pinned ggml C bridge for the rest) against
|
||||
the gguf-py dequantizer of the pinned llama.cpp commit, bit for bit.
|
||||
|
||||
Fixtures are tools/iq_fixture.py's (10 types, seeded) plus the other block types gguf-py can dequantize (Q4_0, Q4_1,
|
||||
Q5_0, Q5_1, Q8_0, Q2_K, Q4_K, Q5_K, Q6_K, IQ1_S, MXFP4, NVFP4) and Q8_K (gguf-py has none: d * qs).
|
||||
|
||||
STRATA_GGUF_PY=<llama.cpp>/gguf-py python scripts/offline/diff_dequant.py <strata-next> [--seeds 3]
|
||||
"""
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import _paths # noqa: E402
|
||||
|
||||
_paths.add_gguf_py()
|
||||
import iq_fixture as F # noqa: E402 (the oracle's fixture generator, unchanged)
|
||||
from gguf import GGMLQuantizationType as Q # noqa: E402
|
||||
from gguf.quants import dequantize # noqa: E402
|
||||
from ggufgen import write_gguf # noqa: E402
|
||||
|
||||
# name -> (kind id, block elements, block bytes, [(offset, kind of scale)])
|
||||
EXTRA = {
|
||||
'Q4_0': (2, 32, 18, [(0, 'f16')]), 'Q4_1': (3, 32, 20, [(0, 'f16'), (2, 'f16')]),
|
||||
'Q5_0': (6, 32, 22, [(0, 'f16')]), 'Q5_1': (7, 32, 24, [(0, 'f16'), (2, 'f16')]),
|
||||
'Q8_0': (8, 32, 34, [(0, 'f16')]), 'Q2_K': (10, 256, 84, [(80, 'f16'), (82, 'f16')]),
|
||||
'Q4_K': (12, 256, 144, [(0, 'f16'), (2, 'f16')]), 'Q5_K': (13, 256, 176, [(0, 'f16'), (2, 'f16')]),
|
||||
'Q6_K': (14, 256, 210, [(208, 'f16')]), 'IQ1_S': (19, 256, 50, [(0, 'f16')]),
|
||||
'MXFP4': (39, 32, 17, [(0, 'e8m0')]), 'NVFP4': (40, 64, 36, [(0, 'ue4m3'), (1, 'ue4m3'), (2, 'ue4m3'), (3, 'ue4m3')]),
|
||||
'Q8_K': (15, 256, 292, [(0, 'f32')]),
|
||||
}
|
||||
|
||||
|
||||
def extra_blocks(name, rows, cols, rng):
|
||||
kind, elems, size, scales = EXTRA[name]
|
||||
n = rows * cols // elems
|
||||
raw = rng.randint(0, 256, (n, size)).astype(np.uint8)
|
||||
for at, how in scales:
|
||||
for b in range(n):
|
||||
if how == 'f16':
|
||||
raw[b, at:at + 2] = np.frombuffer(np.float16(rng.uniform(0.002, 0.08)).tobytes(), np.uint8)
|
||||
elif how == 'f32':
|
||||
raw[b, at:at + 4] = np.frombuffer(np.float32(rng.uniform(0.002, 0.5)).tobytes(), np.uint8)
|
||||
elif how == 'e8m0':
|
||||
raw[b, at] = rng.randint(110, 135)
|
||||
else:
|
||||
raw[b, at] = rng.randint(0x20, 0x50)
|
||||
flat = raw.reshape(-1)
|
||||
if name == 'Q8_K':
|
||||
out = np.empty((n, 256), np.float32)
|
||||
for b in range(n):
|
||||
d = np.frombuffer(raw[b, 0:4].tobytes(), np.float32)[0]
|
||||
out[b] = d * raw[b, 4:260].view(np.int8).astype(np.float32)
|
||||
ref = out.reshape(-1)
|
||||
else:
|
||||
ref = np.asarray(dequantize(flat, getattr(Q, name)), np.float32).reshape(-1)
|
||||
return kind, flat.tobytes(), ref
|
||||
|
||||
|
||||
def fixtures(seed, rows, cols):
|
||||
"""[(name, kind id, blocks bytes, expected float32 array)]"""
|
||||
out = []
|
||||
for name in F.KERNEL_IDS:
|
||||
blob, ref = F.build(name, rows, cols, seed)
|
||||
out.append((name, F.KERNEL_IDS[name], blob[12:], ref))
|
||||
rng = np.random.RandomState(seed)
|
||||
for name in EXTRA:
|
||||
kind, blocks, ref = extra_blocks(name, rows, cols, rng)
|
||||
out.append((name, kind, blocks, ref))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
binary = str(Path(args[0]).resolve())
|
||||
seeds = int(args[args.index('--seeds') + 1]) if '--seeds' in args else 3
|
||||
rows, cols = 32, 256
|
||||
root = Path(tempfile.mkdtemp(prefix='strata-dequant-'))
|
||||
bad, count = [], 0
|
||||
for seed in range(7, 7 + seeds):
|
||||
for name, kind, blocks, ref in fixtures(seed, rows, cols):
|
||||
path = root / f'{name}.gguf'
|
||||
write_gguf(path, [('w', [cols, rows], kind, blocks)])
|
||||
out = root / f'{name}.f32'
|
||||
out.unlink(missing_ok=True)
|
||||
r = subprocess.run([binary, 'model', 'export-tensor-f32', str(path), 'w', '--output', str(out)],
|
||||
capture_output=True, text=True)
|
||||
count += 1
|
||||
if r.returncode:
|
||||
bad.append(f'{name} seed {seed}: export failed: {r.stderr.strip()[-160:]}')
|
||||
continue
|
||||
got = np.frombuffer(out.read_bytes(), np.uint32)
|
||||
want = np.ascontiguousarray(ref, '<f4').view(np.uint32)
|
||||
if got.shape != want.shape or not np.array_equal(got, want):
|
||||
at = int(np.argmax(got != want)) if got.shape == want.shape else -1
|
||||
bad.append(f'{name} seed {seed}: {int(np.count_nonzero(got != want))} of {want.size} words differ '
|
||||
f'(first at {at}: gguf-py {want[at]:#010x} rust {got[at]:#010x})')
|
||||
for b in bad:
|
||||
print('FAIL', b)
|
||||
print(json.dumps({'fixtures': count, 'types': len(F.KERNEL_IDS) + len(EXTRA), 'failures': len(bad),
|
||||
'tolerance': 'bit-exact', 'oracle': 'pinned gguf-py dequantize + tools/iq_fixture.py'}))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -127,6 +127,17 @@ def tokenizer_oracle():
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
@golden
|
||||
def dequant_oracle():
|
||||
"""One 256-value row of every block type (seeded), with the pinned gguf-py dequantizer's float32 bits."""
|
||||
import diff_dequant as D
|
||||
rows = []
|
||||
for name, kind, blocks, ref in D.fixtures(7, 1, 256):
|
||||
rows.append({'name': name, 'kind': kind, 'blocks_hex': blocks.hex(),
|
||||
'f32_hex': np.ascontiguousarray(ref, '<f4').tobytes().hex()})
|
||||
(OUT / 'dequant_oracle.json').write_text(json.dumps({'elements': 256, 'types': rows}, separators=(',', ':')) + '\n')
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
names = sys.argv[1:] or list(GENERATORS)
|
||||
|
||||
Reference in New Issue
Block a user