#!/usr/bin/env python3 """Compare native token IDs and roundtrips with the pinned upstream Python oracle. Offline evaluation only. Requires `regex` for engine/strata/tools/strata_tokenizer.py. The real GGUF and extracted tokenizer assets must stay outside Git. """ import argparse import json import pathlib import subprocess import sys CORPUS = ( "Hello world!", "Привіт, світе! Як справи?", "e\u0301 café — naïve", "😀👨‍👩‍👧‍👦", "空白 漢字\n数字123", "\t\r\nTwo spaces\x00end", "<|im_start|>user\nSay hi<|im_end|>", '{"name":"calc","arguments":{"x":1}}', "a" * 70 + " next", "print(1 + 2) # ✓", ) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=pathlib.Path, required=True) parser.add_argument("--gguf", type=pathlib.Path, required=True) parser.add_argument("--assets", type=pathlib.Path, required=True) args = parser.parse_args() binary = args.binary.resolve(strict=True) gguf = args.gguf.resolve(strict=True) assets = args.assets.resolve(strict=True) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "engine/strata/tools")) from strata_tokenizer import Tokenizer # pylint: disable=import-outside-toplevel oracle = Tokenizer.from_gguf(gguf) for special in (False, True): for number, value in enumerate(CORPUS): command = [binary, "model", "tokenize", assets, "--stdin"] if special: command.append("--special") native = json.loads(subprocess.run( command, input=value, text=True, capture_output=True, check=True, ).stdout) expected = oracle.encode(value, parse_special=special) if native != expected: raise ValueError(f"token IDs differ for case {number}, special={special}") decoded = json.loads(subprocess.run( [binary, "model", "detokenize", assets, ",".join(map(str, native))], text=True, capture_output=True, check=True, ).stdout) if decoded != value or oracle.decode(expected) != value: raise ValueError(f"roundtrip differs for case {number}, special={special}") print(json.dumps({"cases": len(CORPUS) * 2, "vocab": len(oracle.tokens), "merges": len(oracle.ranks), "result": "exact native/upstream parity"})) if __name__ == "__main__": main()