Files
leleka/scripts/offline/gen_goldens.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 debfbd0941 test(tokenizer): committed oracle differential, per-codepoint pre-tokenizer check, batch CLI
- crates/tokenizer pre_tokenize + model pre-tokenize-batch/tokenize-batch/detokenize-batch (debug/differential)
- scripts/offline/diff_tokenizer.py: every Unicode scalar x 13 contexts vs Python regex (0 real mismatches;
  14k strings differ only where regex 2026.9.10 has Unicode 17 and regex-syntax/unicodedata 16), a synthetic
  GGUF with BPE-trained merges past the heap path, 5-file extraction compare, encode/decode fuzz
- golden crates/tokenizer/tests/fixtures/tokenizer_oracle.json + integration test
- stricter-by-design: duplicate merges, missing chat template, negative special ids

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:32:23 +02:00

142 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""Regenerate the small committed golden fixtures that the Rust tests compare against.
Every golden is produced by the UNMODIFIED Python oracle under engine/strata (or numpy / the pinned gguf-py where
the oracle delegates to them). Re-run after changing a generator, review the diff, commit.
STRATA_GGUF_PY=<pinned llama.cpp>/gguf-py python scripts/offline/gen_goldens.py [name ...]
Output directory: control-plane/tests/fixtures/offline/. Deterministic (fixed seeds); no model data.
"""
import json
import struct
import sys
from pathlib import Path
import numpy as np
REPO = Path(__file__).resolve().parents[2]
OUT = REPO / 'control-plane/tests/fixtures/offline'
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
GENERATORS = {}
def golden(fn):
GENERATORS[fn.__name__] = fn
return fn
@golden
def f16_bf16_vectors():
"""f32 bits -> numpy F16 (RNE, overflow -> inf) and gguf-py BF16 (ggml_compute_fp32_to_bf16) bits."""
rng = np.random.default_rng(20261014)
edge = [0x00000000, 0x80000000, 0x00000001, 0x007FFFFF, 0x33000000, 0x33000001, 0x33800000, 0x34000000,
0x387FC000, 0x38800000, 0x477FE000, 0x477FEFFF, 0x477FF000, 0x477FF001, 0x47800000, 0x7F7FFFFF,
0x7F800000, 0xFF800000, 0x7FC00000, 0x7F800001, 0x3F800000, 0x3F808000, 0x3F818000, 0x3F7F8000,
0x7F7F8000, 0xBF808000, 0x00008000, 0x00018000, 0x80008000]
random = rng.integers(0, 2**32, size=3600, dtype=np.uint64).astype(np.uint32)
# concentrate half of the random patterns where F16 is normal/subnormal and ties are likely
near = (rng.integers(0, 2, 400, dtype=np.uint32) << 31) | rng.integers(0x32000000, 0x47900000, 400, dtype=np.uint32)
bits = np.concatenate([np.array(edge, np.uint32), random, near.astype(np.uint32)])
values = bits.view(np.float32)
with np.errstate(over='ignore', invalid='ignore'):
f16 = values.astype(np.float16).view(np.uint16)
from gguf import quants, GGMLQuantizationType as Q
bf16 = quants.quantize(values, Q.BF16).view(np.uint16)
out = bytearray()
for b, h, g in zip(bits, f16, bf16):
out += struct.pack('<IHH', int(b), int(h), int(g))
(OUT / 'f16_bf16_vectors.golden').write_bytes(bytes(out))
@golden
def gguf_headers():
"""Header-only random GGUF files (hex) with what tools/gguf_reader.py parses from each, plus its geometry table.
Tensor payloads are not stored: the Rust test appends zeros (header readers never read them)."""
import random
import tempfile
import diff_gguf_header as D
import gguf_reader as G
rng = random.Random(20261014)
cases = []
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for i in range(24):
path = D.rand_case(rng, root, i)
want = G.GGUFFile(path)
data = path.read_bytes()
cases.append({
'header_hex': data[:want.data_start].hex(),
'payload_bytes': len(data) - want.data_start,
'data_start': want.data_start,
'metadata': want.metadata,
'tensors': [{'name': t.name, 'dimensions': t.shape, 'type': t.type_id,
'offset': want.data_start + t.offset, 'bytes': t.expected_bytes()}
for t in want.tensors]})
geometry = {str(i): {'name': G.GGML_TYPES[i], 'elements': G.BLOCK_GEOMETRY[G.GGML_TYPES[i]][0],
'bytes': G.BLOCK_GEOMETRY[G.GGML_TYPES[i]][1]}
for i in sorted(G.GGML_TYPES) if G.GGML_TYPES[i] in G.BLOCK_GEOMETRY}
(OUT / 'gguf_headers.json').write_text(json.dumps({'cases': cases, 'geometry': geometry}, separators=(',', ':')) + '\n')
@golden
def tokenizer_oracle():
"""Synthetic byte-level BPE vocabulary + what the unmodified tools/strata_tokenizer.py produces for it:
pre-tokenizer splits (sampled code points), encode with/without special parsing, decode."""
import random
import unicodedata
import diff_tokenizer as D
import regex
import strata_tokenizer as T
rng = random.Random(20261014)
tokens, merges = D.train_bpe(rng, 300)
types = [1] * len(tokens)
for text, ty in D.SPECIALS:
tokens.append(text)
types.append(ty)
tk = T.Tokenizer(tokens, merges, types, 'qwen35', {})
texts = [t for t in D.BOUNDARY if len(t) <= 1200] + [D.fuzz_text(rng) for _ in range(120)]
texts = [t for t in texts if len(t) <= 1200]
cases = [{'text': t, 'plain': tk.encode(t), 'special': tk.encode(t, parse_special=True)} for t in texts]
id_lists = [c['special'] for c in cases[:40]] + [[rng.randrange(len(tokens)) for _ in range(rng.randint(0, 20))]
for _ in range(60)]
decodes = []
for ids in id_lists:
try:
decodes.append({'ids': ids, 'text': tk.decode(ids)})
except KeyError:
decodes.append({'ids': ids, 'text': None})
pattern = regex.compile(T.QWEN35_PATTERN)
splits = []
for c in range(0, 0x110000, 4001):
if 0xD800 <= c <= 0xDFFF or unicodedata.category(chr(c)) == 'Cn':
continue
for ctx in ('{c}', 'a{c}', '{c}a', ' {c}', '{c}\n'):
text = ctx.format(c=chr(c))
splits.append({'text': text, 'pieces': pattern.findall(text)})
for t in texts:
if len(t) <= 200:
splits.append({'text': t, 'pieces': pattern.findall(t)})
out = {'tokens': tokens, 'merges': merges, 'token_types': types, 'cases': cases, 'decodes': decodes,
'pre_tokenizer': splits, 'regex_version': regex.__version__}
target = REPO / 'crates/tokenizer/tests/fixtures'
target.mkdir(parents=True, exist_ok=True)
(target / 'tokenizer_oracle.json').write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')) + '\n',
encoding='utf-8')
def main():
OUT.mkdir(parents=True, exist_ok=True)
names = sys.argv[1:] or list(GENERATORS)
for name in names:
GENERATORS[name]()
print('wrote', name)
if __name__ == '__main__':
import _paths
_paths.add_gguf_py()
main()