Files
leleka/scripts/offline/diff_tokenizer.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

277 lines
14 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
"""Tokenizer differential: strata-next (crates/tokenizer, extract-tokenizer) vs the unmodified tools/strata_tokenizer.py.
1. pre-tokenizer: for EVERY Unicode scalar value, the qwen35 split of 13 one-character contexts (alone, next to a
letter / space / digit / punctuation / newline, doubled) in Rust's `fancy_regex` vs Python's `regex`.
2. a synthetic GGUF (full 256-byte alphabet, BPE-trained merges that reach words past the 64-symbol heap path,
type-3 and type-4 specials, some with regex metacharacters): `extract-tokenizer` against `extract()` for all
five files, then ids from `tokenize-batch` (with and without special parsing) and text from `detokenize-batch`
over a boundary corpus plus fuzzed Unicode.
python scripts/offline/diff_tokenizer.py <strata-next> [--stride N] [--fuzz N] [--seed S]
Needs `regex` (pip install regex). --stride N checks every Nth scalar value (default 1 = all 1,112,064).
"""
import json
import random
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 regex # noqa: E402
import strata_tokenizer as T # noqa: E402 (the oracle, unchanged)
from ggufgen import write_gguf # noqa: E402
CONTEXTS = ['{c}', 'a{c}', '{c}a', ' {c}', '{c} ', '1{c}', '{c}1', '!{c}', '{c}!', '\n{c}', '{c}\n', '\r{c}',
'{c}{c}']
def run_batch(binary, args, lines, chunk=200_000):
out = []
for at in range(0, len(lines), chunk):
payload = ('\n'.join(lines[at:at + chunk]) + '\n').encode('utf-8')
r = subprocess.run([binary, 'model', *args], input=payload, capture_output=True, timeout=3600)
if r.returncode:
raise RuntimeError(r.stderr.decode('utf-8', 'replace')[-300:])
out.extend(r.stdout.decode('utf-8').split('\n')[:-1]) # not splitlines(): U+2028, U+0085 ...
return out
def per_codepoint(binary, stride):
"""-> (strings checked, version-skew strings, real mismatches).
Python's `regex` (pinned 2026.9.10 by requirements.txt) carries Unicode 17 tables; Rust's regex-syntax carries
Unicode 16 (the same as Python 3.14's `unicodedata`); the pinned llama.cpp C++ tables are older still. A code
point that is unassigned in Unicode 16 (category Cn) but assigned in 17 may therefore split differently - that is
table skew, counted and reported, not a defect of the port. Anything else is a real mismatch."""
import unicodedata
pattern = regex.compile(T.QWEN35_PATTERN)
scalars = [c for c in range(0x110000) if not 0xD800 <= c <= 0xDFFF]
scalars = scalars[::stride] if stride > 1 else scalars
real, skew, checked, groups = [], 0, 0, 20_000
for at in range(0, len(scalars), groups):
batch = scalars[at:at + groups]
texts = [ctx.format(c=chr(c)) for c in batch for ctx in CONTEXTS]
owners = [c for c in batch for _ in CONTEXTS]
got = run_batch(binary, ['pre-tokenize-batch'], [json.dumps(t, ensure_ascii=True) for t in texts])
assert len(got) == len(texts)
for text, owner, line in zip(texts, owners, got):
checked += 1
have = json.loads(line)
if have == pattern.findall(text):
continue
if unicodedata.category(chr(owner)) == 'Cn':
skew += 1
else:
real.append(f'U+{owner:04X} text={text!r}: regex={pattern.findall(text)!r} fancy={have!r}')
return checked, skew, real
def train_bpe(rng, merges_wanted=700):
"""Byte-level BPE merges over a synthetic multilingual corpus, in GGUF order (tokens, merges)."""
b2u = T.BYTE_TO_UNICODE
pattern = regex.compile(T.QWEN35_PATTERN)
pools = ['the quick brown fox jumps over the lazy dog ', 'def foo(bar):\n return bar + 1\n', '你好,世界!今日は天気です。',
'héllo wörld ça va ', 'Привет мир, как дела? ', 'x = [1, 2, 3] # list\n', "it's don't we're I'll they've ",
'😀🚀 emoji ', 'aaaa' * 40, 'abababababab' * 30, 'tool_call response result ']
words = {}
for _ in range(1500):
text = ''.join(rng.choice(pools) for _ in range(rng.randint(1, 4)))
for piece in pattern.findall(text):
word = tuple(b2u[b] for b in piece.encode('utf-8'))
words[word] = words.get(word, 0) + 1
for n in (70, 100, 130): # long words that exercise the heap path (> 64 symbols)
words[tuple('a' for _ in range(n))] = 50
words[tuple(b2u[b] for b in ('ab' * n).encode())] = 40
words[tuple(b2u[b] for b in ('中文' * n).encode())] = 30
merges = []
for _ in range(merges_wanted):
counts = {}
for word, freq in words.items():
for pair in zip(word, word[1:]):
counts[pair] = counts.get(pair, 0) + freq
if not counts:
break
best = max(counts.items(), key=lambda kv: (kv[1], kv[0]))[0]
merges.append(best)
merged = {}
for word, freq in words.items():
out, i = [], 0
while i < len(word):
if i + 1 < len(word) and (word[i], word[i + 1]) == best:
out.append(word[i] + word[i + 1])
i += 2
else:
out.append(word[i])
i += 1
merged[tuple(out)] = merged.get(tuple(out), 0) + freq
words = merged
tokens = [b2u[b] for b in range(256)]
for left, right in merges:
tokens.append(left + right)
return tokens, [f'{l} {r}' for l, r in merges]
SPECIALS = [('<|im_start|>', 3), ('<|im_end|>', 3), ('<|endoftext|>', 3), ('<think>', 4), ('</think>', 4),
('<tool_call>', 4), ('<tool_response>', 4), ('<|a[b|>', 3), ('(x*)', 4), ('<|im_', 3)]
def build_gguf(root, rng):
tokens, merges = train_bpe(rng)
types = [1] * len(tokens)
for text, ty in SPECIALS:
tokens.append(text)
types.append(ty)
n_plain = len(tokens) - len(SPECIALS)
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'), merges),
('tokenizer.ggml.token_type', ('array', 'i32'), types),
('tokenizer.ggml.eos_token_id', 'u32', n_plain + 1), ('tokenizer.ggml.padding_token_id', 'u32', n_plain + 2),
('tokenizer.ggml.bos_token_id', 'u32', n_plain),
('tokenizer.chat_template', 'str', "{%- for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{%- endfor %}\nünïcode ✓")]
path = root / 'synthetic-tokenizer.gguf'
write_gguf(path, [('w', [1], 0, bytes(4))], meta)
return path, tokens, merges
def stricter_cases(binary, root):
"""Inputs the Python tokenizer accepts that the Rust extractor refuses on purpose (each one asserted both ways)."""
bad = []
b2u = T.BYTE_TO_UNICODE
base_tokens = [b2u[b] for b in range(256)] + ['ab']
base = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'),
('tokenizer.ggml.pre', 'str', 'qwen35'), ('tokenizer.ggml.tokens', ('array', 'str'), base_tokens),
('tokenizer.ggml.merges', ('array', 'str'), ['a b']), ('tokenizer.chat_template', 'str', 'tpl')]
def case(label, meta):
path = root / f'stricter-{label}.gguf'
write_gguf(path, [('w', [1], 0, bytes(4))], meta)
T.Tokenizer.from_gguf(path) # the oracle accepts it
r = subprocess.run([binary, 'model', 'extract-tokenizer', str(path), '--output', str(root / f'out-{label}')],
capture_output=True, text=True)
if r.returncode == 0:
bad.append(f'{label}: rust accepted')
merges = base[4]
case('duplicate-merge', [m if m is not merges else ('tokenizer.ggml.merges', ('array', 'str'), ['a b', 'a b'])
for m in base])
case('no-chat-template', base[:5])
case('negative-special-id', base + [('tokenizer.ggml.padding_token_id', 'i32', -1)])
return bad
def compare_extraction(binary, gguf, root):
bad = []
py_out, rs_out = root / 'py', root / 'rs'
T.extract(gguf, py_out)
r = subprocess.run([binary, 'model', 'extract-tokenizer', str(gguf), '--output', str(rs_out)],
capture_output=True, text=True)
if r.returncode:
return [f'extract-tokenizer failed: {r.stderr[-200:]}']
a, b = py_out / 'tokenizer', rs_out / 'tokenizer'
if sorted(p.name for p in a.iterdir()) != sorted(p.name for p in b.iterdir()):
bad.append('file sets differ')
for name in ('vocab.json', 'token_type.json'):
if json.loads((a / name).read_text('utf-8')) != json.loads((b / name).read_text('utf-8')):
bad.append(f'{name} differs')
for name in ('merges.txt', 'chat_template.jinja'):
if (a / name).read_bytes() != (b / name).read_bytes():
bad.append(f'{name} differs')
ca, cb = json.loads((a / 'tokenizer.json').read_text('utf-8')), json.loads((b / 'tokenizer.json').read_text('utf-8'))
if ca != cb:
bad.append(f'tokenizer.json differs: {[(k, ca.get(k), cb.get(k)) for k in set(ca) | set(cb) if ca.get(k) != cb.get(k)]}')
return bad
BOUNDARY = ['', ' ', 'Hello, world!', ' leading and trailing ', 'a\n\n\nb', 'def f(x):\n\treturn x # comment\n',
'你好,世界', 'مرحبا', '\U0001f600\U0001f680\U0001f1fa\U0001f1f8', 'é́ combining', '\x00\x01\x7f control',
' non-breaking space', '1234567890', 'MixedCASE_and-dashes', '\r\n\r\n', '

', 'x' * 5000,
"it's don't WE'RE I'LL they've 'D 'm", '<|im_start|>user\nhi<|im_end|>\n', '<|im_star', '<|im_', '<think>x</think>',
'<tool_call><tool_response>', '(x*)(x*)', '<|a[b|>', 'a<|im_end|>b<|endoftext|>', '<<|im_end|>>',
'中' * 3000, '中文' * 600, 'a' * 500, 'ab' * 400, 'a' * 64, 'a' * 65, 'ab' * 32, 'ab' * 33,
'तुम्हें नमस्ते', 'ก็ไป', '́leading mark', '٣١٢ ½ Ⅷ ² 𝟘', '\x1c\x1d\x1e\x1f', '\x85    ',
' \n \n ', 'a b c d', ' \n', '\n ', '!!!\n\n', 'a‍b', '👨‍👩‍👧', 'BOM', '�',
'"quoted"', 'path/to/file.txt', 'a.b.c', 'x.y_z-9']
def fuzz_text(rng):
pools = [
list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), list('0123456789'), list(' \t\n\r\x0b\x0c'),
list("'s't're've'm'll'd'S'T'RE"), list('.,;:!?()[]{}<>/\\|_-+=*&^%$#@~`"'),
list('ً̀́̂̈҃ؐͅऀ़ั⃐️\U000e0100'),
list('éüñßçøåÆŒΩλπΣЖЯ中文日本語한국어กขคअआइ'), list('٣١٢½Ⅷ²𝟘¼'),
list('     

   \x85\x1c\x1f'),
list('​‌‍⁠�'), list('😀😂🚀🎉👨👩👧🏳🌈'), [chr(i) for i in range(0, 32)],
['<|im_start|>', '<|im_end|>', '<think>', '</think>', '<tool_call>', '<|im_', '(x*)', '<|a[b|>'],
['ab', 'abab', 'aaaa', 'tool', 'call', 'the ', 'ing ', 'ion', '中文'],
]
out = []
for _ in range(rng.choice([1, 3, 8, 20, 60, 200])):
pool = rng.choice(pools)
out.append(rng.choice(pool))
return ''.join(out)
def compare_tokenization(binary, gguf, root, fuzz, rng):
bad = []
tk = T.Tokenizer.from_gguf(gguf)
tok_dir = str(root / 'rs' / 'tokenizer')
texts = BOUNDARY + [fuzz_text(rng) for _ in range(fuzz)]
lines = [json.dumps(t) for t in texts]
for special in (False, True):
got = run_batch(binary, ['tokenize-batch', tok_dir] + (['--special'] if special else []), lines)
for text, line in zip(texts, got):
want = tk.encode(text, parse_special=special)
have = json.loads(line)
if have != want:
bad.append(f'encode(special={special}) {text[:60]!r}: python {want[:12]}.. rust {str(have)[:80]}')
if len(bad) > 15:
return bad
# decode: the ids Python produced, plus random id lists (multi-byte characters split across tokens)
id_lists = [tk.encode(t, parse_special=True) for t in texts]
n = len(tk.tokens)
for _ in range(max(200, fuzz // 4)):
id_lists.append([rng.randrange(n) for _ in range(rng.randint(0, 30))])
got = run_batch(binary, ['detokenize-batch', tok_dir], [json.dumps(ids) for ids in id_lists])
for ids, line in zip(id_lists, got):
try:
want = tk.decode(ids)
except KeyError:
want = None # a special token such as <|im_ is not in the byte alphabet (neither side decodes)
if json.loads(line) != want:
bad.append(f'decode {ids[:10]}: python {want!r} rust {line[:80]}')
if len(bad) > 15:
break
return bad
def main():
args = sys.argv[1:]
opt = lambda name, default: int(args[args.index(name) + 1]) if name in args else default
binary = str(Path(args[0]).resolve())
stride, fuzz, seed = opt('--stride', 1), opt('--fuzz', 4000), opt('--seed', 20261014)
rng = random.Random(seed)
failures = []
root = Path(tempfile.mkdtemp(prefix='strata-tokenizer-diff-'))
gguf, tokens, merges = build_gguf(root, rng)
failures += ['extract: ' + b for b in compare_extraction(binary, gguf, root)]
failures += ['stricter: ' + b for b in stricter_cases(binary, root)]
failures += ['tokenize: ' + b for b in compare_tokenization(binary, gguf, root, fuzz, rng)]
checked, skew, real = per_codepoint(binary, stride)
failures += ['pre-tokenize: ' + b for b in real]
for f in failures[:50]:
print('FAIL', f[:400])
print(json.dumps({'pretokenizer_strings_checked': checked, 'unicode17_table_skew_strings': skew, 'pretokenizer_real_mismatches': len(real),
'vocab': len(tokens), 'merges': len(merges), 'fuzz_texts': fuzz, 'failures': len(failures),
'oracle': 'tools/strata_tokenizer.py (unmodified) with regex ' + regex.__version__}))
return 1 if failures else 0
if __name__ == '__main__':
raise SystemExit(main())