minijinja =2.24.0 (+ minijinja-contrib pycompat for str methods), configured like serve/frontend.py ChatTemplate: trim/lstrip blocks, no autoescape, raise_exception, Python tojson (json.dumps ensure_ascii=False) and str.strip trim. All 10 chat_golden.json cases render byte for byte straight through the template (tool_calls, tool messages, no generation prompt included). Ordered Json keeps object key order. scripts/offline/diff_chat_template.py: 12000 generated conversations vs jinja2 (identical renders, identical raise_exception messages); committed golden + test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
314 lines
16 KiB
Python
314 lines
16 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))
|
|
sys.path.insert(0, str(REPO / 'engine/strata'))
|
|
|
|
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')
|
|
|
|
|
|
@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')
|
|
|
|
|
|
@golden
|
|
def tools_oracle():
|
|
"""Tiny inputs and the Python tools' exact outputs for embd_bf16_pack, ple_fp8_pack, draft_vocab, make_profile,
|
|
plus the splitmix64 seed and output hashes for mtp_rt (its input is regenerated, it is megabytes)."""
|
|
import hashlib
|
|
import random
|
|
import runpy
|
|
import struct
|
|
import subprocess
|
|
import tempfile
|
|
import diff_tools as D
|
|
import make_profile as MP
|
|
tools = REPO / 'engine/strata/tools'
|
|
|
|
def py(script, *args):
|
|
r = subprocess.run([sys.executable, str(tools / script), *map(str, args)], capture_output=True, text=True)
|
|
assert r.returncode == 0, r.stderr
|
|
return r.stdout
|
|
|
|
out = {}
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
rng = D.SplitMix(17)
|
|
# ---- embd / ple: a checkpoint directory named `ckpt`
|
|
for kind, script, flag in (('embd', 'embd_bf16_pack.py', 'embd'), ('ple', 'ple_fp8_pack.py', 'ple')):
|
|
model = root / kind / 'ckpt'
|
|
D.checkpoint(model, kind, rng)
|
|
dest = root / kind / 'out.gguf'
|
|
py(script, '--model', model, '--out', dest)
|
|
out[kind] = {'files': {f.name: f.read_bytes().hex() for f in sorted(model.iterdir())},
|
|
'output': dest.read_bytes().hex()}
|
|
# ---- draft_vocab
|
|
gguf = root / 'vocab.gguf'
|
|
D.vocab_gguf(gguf)
|
|
base = [3, 40, 270, 7]
|
|
(root / 'base.bin').write_bytes(struct.pack('<4i', *base))
|
|
cases = []
|
|
for use_base, add in ((False, 'cjk'), (False, 'cyrillic'), (True, 'kana,hangul'), (True, 'han,cyrillic'),
|
|
(False, '')):
|
|
args = ['--gguf', gguf, '--add', add, '--out', root / 'd.bin', '--stats'] + (['--base', root / 'base.bin'] if use_base else [])
|
|
text = py('draft_vocab.py', *args)
|
|
cases.append({'base': base if use_base else None, 'add': add,
|
|
'output': (root / 'd.bin').read_bytes().hex(),
|
|
'printed': [l for l in text.splitlines() if not l.startswith('wrote ')]})
|
|
out['draft_vocab'] = {'gguf': gguf.read_bytes().hex(), 'cases': cases}
|
|
# ---- make_profile (8 experts: the profile is 3 KB)
|
|
rnd = random.Random(5)
|
|
n_expert = 8
|
|
base_pairs = list(dict.fromkeys((l, e) for e in rnd.sample(range(n_expert), 4) for l in rnd.sample(range(48), 5)))
|
|
MP.write_profile(root / 'base.prof', base_pairs, n_expert)
|
|
blob = bytearray()
|
|
for _ in range(30):
|
|
layer, k = rnd.randint(-1, 49), rnd.randint(0, 5)
|
|
blob += struct.pack('<ii', layer, k) + struct.pack('<%di' % k, *[rnd.randint(-1, n_expert) for _ in range(k)])
|
|
blob += struct.pack('<%df' % k, *[rnd.random() for _ in range(k)])
|
|
(root / 'trace.bin').write_bytes(bytes(blob))
|
|
profiles = []
|
|
for use_base in (True, False):
|
|
args = [root / 'trace.bin', '--n-expert', n_expert, '--out', root / 'p.bin'] + \
|
|
(['--base', root / 'base.prof'] if use_base else ['--no-base'])
|
|
text = py('make_profile.py', *args)
|
|
profiles.append({'base': use_base, 'output': (root / 'p.bin').read_bytes().hex(),
|
|
'summary': text.split(': ', 1)[1].strip()})
|
|
out['make_profile'] = {'n_expert': n_expert, 'base': (root / 'base.prof').read_bytes().hex(),
|
|
'trace': bytes(blob).hex(), 'runs': profiles}
|
|
# ---- mtp_rt (real H/FF geometry, 2 experts, input regenerated from the seed)
|
|
import io
|
|
import contextlib
|
|
seed, n_expert = 20261014, 2
|
|
D.mtp_fixture(root / 'mtp.gguf', seed, n_expert)
|
|
sys.argv = ['mtp_rt.py', '--gguf', str(root / 'mtp.gguf'), '--out', str(root / 'rt')]
|
|
module = runpy.run_path(str(tools / 'mtp_rt.py'), run_name='mtp_rt_probe')
|
|
module['main'].__globals__['NE'] = n_expert
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
assert module['main']() == 0
|
|
sha = lambda name: hashlib.sha256((root / 'rt' / name).read_bytes()).hexdigest()
|
|
out['mtp_rt'] = {'seed': seed, 'n_expert': n_expert, 'experts_bin_sha256': sha('experts.bin'),
|
|
'dense_bin_sha256': sha('dense.bin'), 'dense_txt': (root / 'rt/dense.txt').read_text()}
|
|
target = REPO / 'crates/offline-tools/tests/fixtures'
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
(target / 'tools_oracle.json').write_text(json.dumps(out, separators=(',', ':')) + '\n')
|
|
|
|
|
|
@golden
|
|
def setup_policy():
|
|
"""`import setup` answers over a grid: derived_factor/resolve_rope, ram_ctx, ctx_ram_need, resident_budget_gib and
|
|
the low_ram_* family. Floats are stored as their Python repr (shortest round-trip)."""
|
|
import setup
|
|
out = {'models': {k: {'ram_gb': v['ram_gb'], 'arena_gb': v['arena_gb']} for k, v in setup.MODELS.items()},
|
|
'contexts': setup.CONTEXTS}
|
|
ctxs = sorted({*setup.CONTEXTS, 1, 4096, 131071, 262143, 262144, 262145, 300000, 393216, 600000, 1048576})
|
|
out['derived_factor'] = [{'ctx': c, 'trained': t, 'result': setup.derived_factor(c, t)}
|
|
for c in ctxs for t in (262144, 131072, 100000)]
|
|
resolve = []
|
|
for c in ctxs:
|
|
for scaling in (None, 'none', 'linear', 'yarn'):
|
|
for scale in (None, 1.0, 1.5, 1.8, 2.0, 4.0):
|
|
try:
|
|
res = setup.resolve_rope(c, scaling, scale)
|
|
resolve.append({'ctx': c, 'scaling': scaling, 'scale': scale,
|
|
'result': None if res == (None, None) else list(res)})
|
|
except ValueError:
|
|
resolve.append({'ctx': c, 'scaling': scaling, 'scale': scale, 'error': True})
|
|
out['resolve_rope'] = resolve
|
|
rams = [8, 24, 32, 47.9, 48, 62, 64.5, 96, 256]
|
|
vrams = [0, 5, 12, 24, 48]
|
|
out['ram_ctx'] = [{'model': m, 'ram': r, 'low_ram': lr, 'result': setup.ram_ctx(m, r, lr)}
|
|
for m in setup.MODELS for r in rams + [60.2, 62.4, 67.5, 75.3] for lr in (False, True)]
|
|
out['ctx_ram_need'] = [{'model': m, 'ctx': c, 'low_ram': lr, 'result': setup.ctx_ram_need(m, c, lr)}
|
|
for m in setup.MODELS for c in setup.CONTEXTS + [300000] for lr in (False, True)]
|
|
out['resident_budget'] = [{'model': m, 'ram': r, 'kv': kv, 'result': setup.resident_budget_gib(m, r, kv)}
|
|
for m in setup.MODELS for r in rams + [0.5, 2.5, 63.5] for kv in (0.0, 0.1, 3.5, 40.0)]
|
|
low = []
|
|
for m in setup.MODELS:
|
|
for r in rams:
|
|
low.append({'fn': 'needed', 'model': m, 'ram': r, 'result': setup.low_ram_needed(m, r)})
|
|
for v in vrams:
|
|
low.append({'fn': 'fits', 'model': m, 'ram': r, 'vram': v, 'result': setup.low_ram_fits(m, r, v)})
|
|
for v in vrams:
|
|
for ctx in (8192, 65536, 262144, 524288):
|
|
for kv in ('int8', 'q4_0', 'k8v4'):
|
|
low.append({'fn': 'gpu_gb', 'model': m, 'vram': v, 'ctx': ctx, 'kv': kv,
|
|
'result': setup.low_ram_gpu_gb(m, v, ctx, kv),
|
|
'share': setup.low_ram_gpu_share(m, v, ctx, kv)})
|
|
for r in (32, 64, 96):
|
|
low.append({'fn': 'resident', 'model': m, 'ram': r, 'vram': v, 'ctx': ctx, 'kv': kv,
|
|
'result': setup.low_ram_resident(m, r, v, ctx, kv)})
|
|
out['low_ram'] = low
|
|
target = REPO / 'crates/context/tests/fixtures'
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
(target / 'setup_policy_oracle.json').write_text(json.dumps(out, separators=(',', ':')) + '\n')
|
|
|
|
|
|
@golden
|
|
def chat_template_oracle():
|
|
"""Generated conversations (all roles, list content with image parts, tool_calls, tools, kwargs) and what the Python
|
|
server's ChatTemplate renders - or the message it raises - for each."""
|
|
import random
|
|
import diff_chat_template as D
|
|
rng = random.Random(20261014)
|
|
template = D.ChatTemplate(REPO / 'engine/strata/serve/chat_template.jinja')
|
|
cases = {'ok': [], 'raised': []}
|
|
while len(cases['ok']) < 90 or len(cases['raised']) < 25:
|
|
req = {'messages': D.rand_messages(rng), 'tools': D.rand_tools(rng),
|
|
'add_generation_prompt': rng.random() < 0.9, 'kwargs': D.rand_kwargs(rng)}
|
|
if len(json.dumps(req)) > 2500:
|
|
continue
|
|
try:
|
|
text = template.render(req['messages'], req['tools'], req['add_generation_prompt'], **req['kwargs'])
|
|
if len(cases['ok']) < 90:
|
|
cases['ok'].append({**req, 'rendered': text})
|
|
except D.TemplateRequestError as e:
|
|
if len(cases['raised']) < 25:
|
|
cases['raised'].append({**req, 'error': str(e)})
|
|
except Exception: # noqa: BLE001 (jinja2 errors: not part of the contract)
|
|
pass
|
|
(OUT / 'chat_template_oracle.json').write_text(json.dumps(cases, 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()
|