233 lines
9.8 KiB
Python
233 lines
9.8 KiB
Python
#!/usr/bin/env python3
|
|
"""GGUF header differential: leleka-api (`model inspect`, `model inspect-metadata`, `model index`) vs the
|
|
unmodified tools/gguf_reader.py on randomized synthetic GGUF v3 files, plus geometry-table parity and the
|
|
"Rust is stricter by design" rejection list.
|
|
|
|
python scripts/offline/diff_gguf_header.py <leleka-api> [--cases N] [--seed S]
|
|
|
|
Random files cover all 13 metadata value types, arrays of every element type, unicode strings, `general.alignment`,
|
|
split keys and 1-4 dimensional tensors of every block geometry both sides know. Pure stdlib + the oracle.
|
|
"""
|
|
import json
|
|
import random
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
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 gguf_reader as G # noqa: E402 (the oracle, unchanged)
|
|
from ggufgen import write_gguf, string # noqa: E402
|
|
|
|
SCALAR_KINDS = ['u8', 'i8', 'u16', 'i16', 'u32', 'i32', 'f32', 'bool', 'u64', 'i64', 'f64']
|
|
RANGES = {'u8': (0, 255), 'i8': (-128, 127), 'u16': (0, 65535), 'i16': (-32768, 32767), 'u32': (0, 2**32 - 1),
|
|
'i32': (-2**31, 2**31 - 1), 'u64': (0, 2**64 - 1), 'i64': (-2**63, 2**63 - 1)}
|
|
GEOM = {name: g for name, g in G.BLOCK_GEOMETRY.items()}
|
|
TYPE_IDS = {name: i for i, name in G.GGML_TYPES.items() if name in GEOM}
|
|
|
|
|
|
def rand_string(rng):
|
|
alphabet = 'abcXYZ019 _-./äöüéßçñΩλπЖ中文日本語한국어😀🧪́'
|
|
return ''.join(rng.choice(alphabet) for _ in range(rng.randint(0, 24)))
|
|
|
|
|
|
def rand_scalar(rng, kind):
|
|
if kind == 'bool':
|
|
return rng.random() < 0.5
|
|
if kind == 'f32':
|
|
return struct.unpack('<f', struct.pack('<f', rng.uniform(-1e6, 1e6) * rng.choice([1, 1e-9, 1e9])))[0]
|
|
if kind == 'f64':
|
|
return rng.uniform(-1e300, 1e300) if rng.random() < 0.2 else rng.uniform(-1e6, 1e6)
|
|
if kind == 'str':
|
|
return rand_string(rng)
|
|
lo, hi = RANGES[kind]
|
|
return rng.choice([lo, hi, 0 if lo <= 0 else lo, rng.randint(lo, hi), rng.randint(lo, hi)])
|
|
|
|
|
|
def rand_metadata(rng):
|
|
out, used = [], set()
|
|
for i in range(rng.randint(0, 36)):
|
|
key = f'{rng.choice(["general", "x.y", "tokenizer.ggml", "m"])}.k{i}_{rng.randint(0, 99)}'
|
|
if key in used:
|
|
continue
|
|
used.add(key)
|
|
if rng.random() < 0.25:
|
|
element = rng.choice(SCALAR_KINDS + ['str'])
|
|
out.append((key, ('array', element), [rand_scalar(rng, element) for _ in range(rng.randint(0, 12))]))
|
|
else:
|
|
kind = rng.choice(SCALAR_KINDS + ['str'])
|
|
out.append((key, kind, rand_scalar(rng, kind)))
|
|
return out, used
|
|
|
|
|
|
def rand_case(rng, root, index):
|
|
meta, used = rand_metadata(rng)
|
|
alignment = rng.choice([8, 16, 32, 32, 32, 64, 128, 256, 1024, 4096])
|
|
if alignment != 32 or rng.random() < 0.3:
|
|
meta.insert(rng.randint(0, len(meta)), ('general.alignment', 'u32', alignment))
|
|
if rng.random() < 0.4 and 'general.architecture' not in used:
|
|
meta.append(('general.architecture', 'str', rng.choice(['qwen4exp', 'llama', rand_string(rng) or 'x'])))
|
|
if rng.random() < 0.3:
|
|
n = rng.randint(1, 4)
|
|
meta += [('split.no', 'u16', rng.randint(0, n - 1)), ('split.count', 'u16', n), ('split.tensors.count', 'i32', rng.randint(1, 50))]
|
|
rng.shuffle(meta)
|
|
tensors = []
|
|
names = set()
|
|
for t in range(rng.randint(1, 9)):
|
|
type_name = rng.choice(sorted(TYPE_IDS))
|
|
elems, size = GEOM[type_name]
|
|
dims = [elems * rng.randint(1, 4)] + [rng.randint(1, 5) for _ in range(rng.randint(0, 3))]
|
|
name = rng.choice(['blk.', 'x.', '']) + f't{t}_{rng.randint(0, 9)}.weight'
|
|
if name in names:
|
|
continue
|
|
names.add(name)
|
|
count = 1
|
|
for d in dims:
|
|
count *= d
|
|
raw = bytes(rng.randrange(256) for _ in range(count // elems * size))
|
|
tensors.append((name, dims, TYPE_IDS[type_name], raw))
|
|
path = root / f'case{index}.gguf'
|
|
write_gguf(path, tensors, meta, alignment=alignment)
|
|
return path
|
|
|
|
|
|
def run(binary, *args):
|
|
r = subprocess.run([binary, 'model', *args], capture_output=True, text=True, timeout=30)
|
|
return r
|
|
|
|
|
|
def compare(binary, path):
|
|
want = G.GGUFFile(path)
|
|
bad = []
|
|
r = run(binary, 'inspect-metadata', str(path))
|
|
if r.returncode:
|
|
return [f'inspect-metadata failed: {r.stderr.strip()[-200:]}']
|
|
got = json.loads(r.stdout)
|
|
if got != want.metadata:
|
|
for k in want.metadata:
|
|
if got.get(k) != want.metadata[k]:
|
|
bad.append(f'metadata {k!r}: {want.metadata[k]!r} vs {got.get(k)!r}')
|
|
break
|
|
if set(got) != set(want.metadata):
|
|
bad.append('metadata keys differ')
|
|
r = run(binary, 'index', str(path))
|
|
if r.returncode:
|
|
return bad + [f'index failed: {r.stderr.strip()[-200:]}']
|
|
rows = [json.loads(line) for line in r.stdout.splitlines()]
|
|
if len(rows) != len(want.tensors):
|
|
bad.append('tensor count differs')
|
|
else:
|
|
for t, row in zip(want.tensors, rows):
|
|
expect = {'name': t.name, 'dimensions': t.shape, 'type': t.type_id,
|
|
'offset': want.data_start + t.offset, 'bytes': t.expected_bytes()}
|
|
if row != expect:
|
|
bad.append(f'tensor {t.name}: {expect} vs {row}')
|
|
break
|
|
r = run(binary, 'inspect', str(path))
|
|
text = r.stdout
|
|
if f'data starts at byte {want.data_start}' not in text or \
|
|
f'tensors: {len(want.tensors)}; metadata: {len(want.metadata)}' not in text:
|
|
bad.append(f'inspect summary differs: {text!r}')
|
|
return bad
|
|
|
|
|
|
def geometry_parity(binary):
|
|
"""Rust block_geometry vs BLOCK_GEOMETRY, through `model index` of one-tensor files for every type id."""
|
|
bad, root = [], Path(tempfile.mkdtemp(prefix='strata-geom-'))
|
|
for type_id in range(0, 64):
|
|
name = G.GGML_TYPES.get(type_id)
|
|
geom = GEOM.get(name) if name else None
|
|
elems, size = geom if geom else (1, 4)
|
|
path = root / f'g{type_id}.gguf'
|
|
write_gguf(path, [('w', [elems * 2, 3], type_id, bytes(2 * 3 * size))])
|
|
r = run(binary, 'index', str(path))
|
|
rust_ok = r.returncode == 0
|
|
if rust_ok:
|
|
row = json.loads(r.stdout.splitlines()[0])
|
|
if geom is None:
|
|
# Rust-only kinds: I8 (24) is the engine's FP8 PLE table form, in gguf_reader.hpp
|
|
if type_id != 24:
|
|
bad.append(f'type {type_id} ({name}) accepted by rust but absent from BLOCK_GEOMETRY')
|
|
elif row['bytes'] != 2 * 3 * size:
|
|
bad.append(f'type {type_id} {name}: bytes {row["bytes"]} != {2 * 3 * size}')
|
|
elif geom is not None:
|
|
bad.append(f'type {type_id} {name} is in BLOCK_GEOMETRY but rust refuses it: {r.stderr.strip()[-100:]}')
|
|
return bad
|
|
|
|
|
|
def stricter_cases(binary, root):
|
|
"""Inputs the Python reader parses (or ignores) that the Rust reader refuses on purpose."""
|
|
bad = []
|
|
base_t = [('w', [32], 0, bytes(128))]
|
|
|
|
def must_reject(label, path, command='index'):
|
|
r = run(binary, command, str(path))
|
|
if r.returncode == 0:
|
|
bad.append(f'{label}: rust accepted')
|
|
|
|
def build(label, tensors=base_t, meta=(), **kw):
|
|
p = root / (label.replace(' ', '_').replace(':', '') + '.gguf')
|
|
write_gguf(p, tensors, list(meta), **kw)
|
|
return p
|
|
|
|
must_reject('duplicate metadata key', build('dupkey', meta=[('a', 'u32', 1), ('a', 'u32', 2)]))
|
|
must_reject('alignment not a power of two', build('align3', meta=[('general.alignment', 'u32', 48)], alignment=48))
|
|
must_reject('alignment as u64', build('align64', meta=[('general.alignment', 'u64', 64)], alignment=64))
|
|
must_reject('zero tensors', build('notensor', tensors=[]))
|
|
must_reject('unknown tensor type', build('badtype', tensors=[('w', [32], 31, bytes(128))]))
|
|
must_reject('duplicate tensor name', build('duptensor', tensors=base_t + base_t))
|
|
p = build('trunc')
|
|
p.write_bytes(p.read_bytes()[:-1])
|
|
must_reject('tensor payload truncated by one byte', p)
|
|
p = build('badutf', meta=[('k', 'str', 'abc')])
|
|
p.write_bytes(p.read_bytes().replace(b'abc', b'\xff\xfe\xfd'))
|
|
must_reject('invalid UTF-8 string value (metadata dump)', p, 'inspect-metadata')
|
|
p = build('ver2')
|
|
b = bytearray(p.read_bytes())
|
|
b[4:8] = struct.pack('<I', 2)
|
|
p.write_bytes(bytes(b))
|
|
must_reject('version 2', p)
|
|
p.write_bytes(b'GGUX' + bytes(b[4:]))
|
|
must_reject('bad magic', p)
|
|
p = build('hdrtrunc')
|
|
p.write_bytes(p.read_bytes()[:30])
|
|
must_reject('truncated header', p)
|
|
# Python and Rust must agree these are errors
|
|
for label in ('ver2', 'hdrtrunc'):
|
|
try:
|
|
G.GGUFFile(root / f'{label}.gguf')
|
|
bad.append(f'{label}: oracle accepted')
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
return bad
|
|
|
|
|
|
def main():
|
|
args = sys.argv[1:]
|
|
cases = int(args[args.index('--cases') + 1]) if '--cases' in args else 400
|
|
seed = int(args[args.index('--seed') + 1]) if '--seed' in args else 20261014
|
|
binary = str(Path(args[0]).resolve())
|
|
rng = random.Random(seed)
|
|
root = Path(tempfile.mkdtemp(prefix='strata-gguf-diff-'))
|
|
failures = []
|
|
for i in range(cases):
|
|
path = rand_case(rng, root, i)
|
|
problems = compare(binary, path)
|
|
if problems:
|
|
failures.append(f'case {i}: ' + '; '.join(problems))
|
|
path.unlink()
|
|
failures += ['geometry: ' + b for b in geometry_parity(binary)]
|
|
failures += ['stricter: ' + b for b in stricter_cases(binary, root)]
|
|
for f in failures[:40]:
|
|
print('FAIL', f[:600])
|
|
print(json.dumps({'random_cases': cases, 'seed': seed, 'failures': len(failures),
|
|
'oracle': 'tools/gguf_reader.py (unmodified)'}))
|
|
return 1 if failures else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|