#!/usr/bin/env python3 """Differential for the small offline tools: leleka-api `tools ...` vs the unmodified Python originals. embd_bf16_pack.py -> tools embd-bf16-pack (synthetic safetensors checkpoint, BF16 table) ple_fp8_pack.py -> tools ple-fp8-pack (3 shards of F8_E4M3 + BF16 scale) draft_vocab.py -> tools draft-vocab (synthetic vocabulary with Han/kana/Hangul/Cyrillic tokens) make_profile.py -> tools make-profile (ranked base + routing traces; 512, 256 and 8 experts) mtp_rt.py -> tools mtp-rt (Q2_0 experts at the real H/FF geometry, 2 experts) Every output file must be byte-identical. Needs numpy, regex (draft_vocab imports the tokenizer) and the pinned gguf-py (mtp_rt imports it): STRATA_GGUF_PY=/gguf-py python scripts/offline/diff_tools.py """ import contextlib import io import json import random import runpy import struct import subprocess import sys import tempfile from pathlib import Path import numpy as np REPO = Path(__file__).resolve().parents[2] TOOLS = REPO / 'engine/strata/tools' sys.path.insert(0, str(TOOLS)) sys.path.insert(0, str(Path(__file__).resolve().parent)) from ggufgen import write_gguf # noqa: E402 MASK = (1 << 64) - 1 class SplitMix: """splitmix64: the shared deterministic byte source of the Python generators and the Rust golden tests.""" def __init__(self, seed): self.state = seed & MASK def next(self): self.state = (self.state + 0x9E3779B97F4A7C15) & MASK z = self.state z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK return z ^ (z >> 31) def bytes(self, n): out = bytearray() while len(out) < n: out += struct.pack('> 1) % 0x12) << 7) | ((r >> 40) & 0x7F)) return np.array(words, dtype='', 'ab'] # a token that is only a piece of a multi-byte character, and special tokens tokens += [b2u[0xE4] + b2u[0xB8]] types = [1] * len(tokens) types[-2] = 1 meta = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'), ('tokenizer.ggml.pre', 'str', 'qwen35'), ('tokenizer.ggml.tokens', ('array', 'str'), tokens), ('tokenizer.ggml.merges', ('array', 'str'), ['a b']), ('tokenizer.ggml.token_type', ('array', 'i32'), types), ('tokenizer.chat_template', 'str', 'x')] write_gguf(path, [('w', [1], 0, bytes(4))], meta) return tokens def check_draft_vocab(binary, root, bad): gguf = root / 'vocab.gguf' tokens = vocab_gguf(gguf) rnd = random.Random(3) base_ids = sorted(rnd.sample(range(len(tokens)), 40)) base_file = root / 'base.bin' base_file.write_bytes(struct.pack('<%di' % len(base_ids), *base_ids)) dup_file = root / 'base-dup.bin' dup_file.write_bytes(struct.pack('<%di' % 4, 300, 5, 300, 1)) odd = root / 'odd.bin' odd.write_bytes(b'abc') far = root / 'far.bin' far.write_bytes(struct.pack('<2i', 3, len(tokens) + 5)) cases = [(None, ''), (None, 'cjk'), (None, 'han'), (None, 'kana,hangul'), (None, 'cyrillic'), (None, 'cjk, cyrillic'), (None, 'cjk_punct'), (base_file, ''), (base_file, 'cjk'), (base_file, 'cyrillic,han'), (dup_file, 'kana'), (base_file, 'bogus'), (odd, 'cjk'), (far, 'cjk')] for number, (base, add) in enumerate(cases): for with_out in (True, False): for stats in (False, True): args = ['--gguf', gguf] + (['--base', base] if base else []) + (['--add', add] if add else []) + \ (['--stats'] if stats else []) py_out, rs_out = root / f'd{number}-py.bin', root / f'd{number}-rs.bin' for f in (py_out, rs_out): f.unlink(missing_ok=True) py = run_py('draft_vocab.py', *args, *(['--out', py_out] if with_out else [])) rs = run_rust(binary, 'draft-vocab', *args, *(['--out', rs_out] if with_out else [])) label = f'draft_vocab case {number} base={base and base.name} add={add!r} out={with_out} stats={stats}' if (py.returncode == 0) != (rs.returncode == 0): bad.append(f'{label}: python rc {py.returncode} ({py.stderr.strip()[-80:]}), rust rc ' f'{rs.returncode} ({rs.stderr.strip()[-80:]})') continue if py.returncode: continue if with_out: same_files(py_out, rs_out, [''], label, bad) strip = lambda text, path: ''.join(l + '\n' for l in text.splitlines() if not l.startswith('wrote ')) if strip(py.stdout, py_out) != strip(rs.stdout, rs_out): bad.append(f'{label}: printed statistics differ:\n{py.stdout!r}\n{rs.stdout!r}') # ------------------------------------------------------------------------------------------------ make_profile def check_make_profile(binary, root, bad): import make_profile as MP rnd = random.Random(11) for n_expert in (512, 256, 8): base_pairs = [(l, e) for e in rnd.sample(range(n_expert), min(n_expert, 20)) for l in rnd.sample(range(48), 6)] base_pairs = list(dict.fromkeys(base_pairs)) base = root / f'base{n_expert}.bin' MP.write_profile(base, base_pairs, n_expert) traces = [] for t in range(3): blob = bytearray() for _ in range(rnd.randint(1, 40)): layer, k = rnd.randint(-1, 49), rnd.randint(0, 6) blob += struct.pack('