Files
leleka/scripts/offline/diff_tools.py
T

303 lines
15 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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=<llama.cpp>/gguf-py python scripts/offline/diff_tools.py <leleka-api>
"""
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('<Q', self.next())
return bytes(out[:n])
def bf16(self, n):
"""n finite BF16 words: sign, exponent 0x70..0x81 (|x| in ~2^-15..2^2), 7 random mantissa bits."""
words = []
for _ in range(n):
r = self.next()
words.append(((r & 1) << 15) | ((0x70 + (r >> 1) % 0x12) << 7) | ((r >> 40) & 0x7F))
return np.array(words, dtype='<u2')
def mtp_fixture(path, seed, n_expert, h=2560, ff=640):
"""A synthetic MTP GGUF at the real H/FF geometry: two Q2_0 expert tensors, Q8-path and BF16-path projections,
F32 norms. Deterministic in `seed`."""
rng = SplitMix(seed)
gu_bytes = n_expert * 2 * ff * (h // 64) * 18
dn_bytes = n_expert * h * (ff // 64) * 18
bf = lambda name, dims: (name, dims, 30, rng.bf16(int(np.prod(dims))).tobytes())
f32 = lambda name, n: (name, [n], 0, (rng.bf16(n).astype('<u4') << 16).view('<f4').tobytes())
tensors = [
('mtp.layers.0.mlp.experts.gate_up_proj', [h, 2 * ff, n_expert], 42, rng.bytes(gu_bytes)),
bf('mtp.fc_embedding.weight', [64, 8]),
f32('mtp.pre_fc_norm_hidden.weight', 24),
('mtp.layers.0.mlp.experts.down_proj', [ff, h, n_expert], 42, rng.bytes(dn_bytes)),
bf('mtp.layers.0.self_attn.q_proj.weight', [32, 6]),
bf('mtp.layers.0.mlp.gate.weight', [16, 4]),
f32('mtp.layers.0.self_attn.q_norm.weight', 16),
bf('mtp.layers.0.mlp.shared_expert.down_proj.weight', [96, 5]),
bf('mtp.hyper_connection_mixer.input_mix_weight_up.weight', [40, 3]),
]
write_gguf(path, tensors, [('general.architecture', 'str', 'qwen4exp-mtp')])
def run_rust(binary, *args):
r = subprocess.run([binary, 'tools', *map(str, args)], capture_output=True, text=True)
return r
def run_py(script, *args, env_extra=None):
r = subprocess.run([sys.executable, str(TOOLS / script), *map(str, args)], capture_output=True, text=True)
return r
def same_files(a, b, names, label, bad):
for name in names:
pa, pb = Path(a) / name if Path(a).is_dir() else Path(a), Path(b) / name if Path(b).is_dir() else Path(b)
if not pa.exists() or not pb.exists():
bad.append(f'{label}: {name} exists python={pa.exists()} rust={pb.exists()}')
elif pa.read_bytes() != pb.read_bytes():
bad.append(f'{label}: {name} differs')
# ------------------------------------------------------------------------------------------------ embd / ple
def safetensors_file(path, tensors):
"""tensors: [(name, dtype, shape, raw bytes)]"""
header, data = {}, b''
for name, dtype, shape, raw in tensors:
header[name] = {'dtype': dtype, 'shape': shape, 'data_offsets': [len(data), len(data) + len(raw)]}
data += raw
body = json.dumps(header).encode()
path.write_bytes(struct.pack('<Q', len(body)) + body + data)
def checkpoint(root, kind, rng, bad_dtype=False):
root.mkdir(parents=True)
weight_map = {}
if kind == 'embd':
vocab, dim = 37, 12
raw = rng.bf16(vocab * dim).tobytes()
safetensors_file(root / 'model-00001.safetensors', [
('model.embed_tokens.weight', 'F16' if bad_dtype else 'BF16', [vocab, dim], raw),
('model.visual.embed_tokens.weight', 'BF16', [4, 4], rng.bf16(16).tobytes()),
('mtp.embed_tokens.weight', 'BF16', [4, 4], rng.bf16(16).tobytes())])
weight_map = {'model.embed_tokens.weight': 'model-00001.safetensors',
'model.visual.embed_tokens.weight': 'model-00001.safetensors',
'mtp.embed_tokens.weight': 'model-00001.safetensors'}
else:
dim = 10
scale = struct.pack('<H', 0x3E80) # BF16 0.25
safetensors_file(root / 'scale.safetensors', [('m.ngram_embedding.weight_scale', 'BF16', [1], scale)])
weight_map['m.ngram_embedding.weight_scale'] = 'scale.safetensors'
for k, rows in enumerate((7, 5, 9)):
safetensors_file(root / f'ple{k}.safetensors', [(f'm.ngram_embedding.shard_{k}.weight', 'F8_E4M3',
[rows, dim], rng.bytes(rows * dim))])
weight_map[f'm.ngram_embedding.shard_{k}.weight'] = f'ple{k}.safetensors'
if bad_dtype:
weight_map.pop('m.ngram_embedding.shard_1.weight') # a gap in the shard numbering
(root / 'model.safetensors.index.json').write_text(json.dumps({'weight_map': weight_map}))
def check_packs(binary, root, bad):
rng = SplitMix(5)
for kind, script, command in (('embd', 'embd_bf16_pack.py', 'embd-bf16-pack'),
('ple', 'ple_fp8_pack.py', 'ple-fp8-pack')):
for broken in (False, True):
model = root / f'{kind}-{broken}' / 'ckpt'
checkpoint(model, kind, rng, broken)
py_out, rs_out = root / f'{kind}-{broken}' / 'py.gguf', root / f'{kind}-{broken}' / 'rs.gguf'
py = run_py(script, '--model', model, '--out', py_out)
rs = run_rust(binary, command, '--model', model, '--out', rs_out)
if (py.returncode == 0) != (rs.returncode == 0):
bad.append(f'{kind} broken={broken}: python rc {py.returncode}, rust rc {rs.returncode} '
f'({rs.stderr.strip()[-120:]})')
elif py.returncode == 0:
same_files(py_out, rs_out, [''], f'{kind}', bad)
if (rs_out.with_suffix('.gguf.part')).exists():
bad.append(f'{kind}: leftover .part')
# ------------------------------------------------------------------------------------------------ draft_vocab
def vocab_gguf(path):
import strata_tokenizer as T
b2u = T.BYTE_TO_UNICODE
words = ['中文', '你好', '世界', '日本語', 'こんにちは', 'カタカナ', '한국어', '안녕하세요', ',', '。', 'アイウ', 'привет',
'мир', 'Україна', 'hello', ' world', 'def', '_x', 'ñandú', 'é', '😀', ' ', 'ЖЖ', 'ӂ', 'ꙁ']
tokens = [b2u[b] for b in range(256)]
tokens += [''.join(b2u[b] for b in w.encode('utf-8')) for w in words]
tokens += ['<|im_end|>', '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('<ii', layer, k)
blob += struct.pack('<%di' % k, *[rnd.randint(-1, n_expert) for _ in range(k)])
blob += struct.pack('<%df' % k, *[rnd.random() for _ in range(k)])
trace = root / f'trace{n_expert}-{t}.bin'
trace.write_bytes(bytes(blob))
traces.append(trace)
for use_base in (True, False):
for chosen in ([], traces[:1], traces):
py_out, rs_out = root / f'p{n_expert}-py.bin', root / f'p{n_expert}-rs.bin'
common = [str(t) for t in chosen] + (['--base', str(base)] if use_base else ['--no-base']) + \
['--n-expert', str(n_expert)]
py = run_py('make_profile.py', *common, '--out', py_out)
rs = run_rust(binary, 'make-profile', *common, '--out', rs_out)
label = f'make_profile n_expert={n_expert} base={use_base} traces={len(chosen)}'
if (py.returncode == 0) != (rs.returncode == 0):
bad.append(f'{label}: rc python {py.returncode} rust {rs.returncode}: {rs.stderr.strip()[-100:]}')
continue
same_files(py_out, rs_out, [''], label, bad)
tail = lambda text: text.split(': ', 1)[1]
if tail(py.stdout) != tail(rs.stdout):
bad.append(f'{label}: summary differs {py.stdout!r} vs {rs.stdout!r}')
# wrong geometry and garbage are refused by both
junk = root / 'junk.bin'
junk.write_bytes(b'NOPE' + bytes(40))
for args in (['--base', str(junk)], ['--base', str(root / 'base512.bin'), '--n-expert', '256']):
py = run_py('make_profile.py', *args, '--out', root / 'x.bin')
rs = run_rust(binary, 'make-profile', *args, '--out', root / 'y.bin')
if (py.returncode == 0) != (rs.returncode == 0):
bad.append(f'make_profile refusal {args}: python rc {py.returncode}, rust rc {rs.returncode}')
# ------------------------------------------------------------------------------------------------ mtp_rt
def check_mtp_rt(binary, root, bad, n_expert=2):
gguf = root / 'mtp-q2_0.gguf'
mtp_fixture(gguf, 20261014, n_expert)
py_out, rs_out = root / 'rt-py', root / 'rt-rs'
import _paths
_paths.add_gguf_py()
sys.argv = ['mtp_rt.py', '--gguf', str(gguf), '--out', str(py_out)]
module = runpy.run_path(str(TOOLS / 'mtp_rt.py'), run_name='mtp_rt_probe') # defines main(), does not run it
module['main'].__globals__['NE'] = n_expert # the tool's expert count is a module global
with contextlib.redirect_stdout(io.StringIO()):
rc = module['main']()
rs = run_rust(binary, 'mtp-rt', '--gguf', gguf, '--out', rs_out, '--n-expert', n_expert)
if rc != 0 or rs.returncode != 0:
bad.append(f'mtp_rt: python rc {rc}, rust rc {rs.returncode} {rs.stderr.strip()[-200:]}')
return
same_files(py_out, rs_out, ['experts.bin', 'dense.bin', 'dense.txt'], 'mtp_rt', bad)
def main():
binary = str(Path(sys.argv[1]).resolve())
root = Path(tempfile.mkdtemp(prefix='strata-tools-diff-'))
bad = []
check_packs(binary, root, bad)
check_draft_vocab(binary, root, bad)
check_make_profile(binary, root, bad)
check_mtp_rt(binary, root, bad)
for b in bad[:30]:
print('FAIL', b[:500])
print(json.dumps({'failures': len(bad), 'tools': ['embd_bf16_pack', 'ple_fp8_pack', 'draft_vocab', 'make_profile',
'mtp_rt'], 'tolerance': 'byte-identical'}))
return 1 if bad else 0
if __name__ == '__main__':
raise SystemExit(main())