aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / om / qwen-native / tokenizer / oracle_test.py
| 1 | """CPU-only independent oracle. Reads only the public dev/prompts manifest.""" |
| 2 | import hashlib |
| 3 | import json |
| 4 | import pathlib |
| 5 | import random |
| 6 | import subprocess |
| 7 | import tempfile |
| 8 | import unicodedata |
| 9 | |
| 10 | import tokenizers |
| 11 | |
| 12 | HERE = pathlib.Path(__file__).resolve().parent |
| 13 | ROOT = HERE.parents[4] |
| 14 | PROMPTS = ROOT / "evaluator/benchmarks-mv/evals/omega-specialist-948/dev/prompts" |
| 15 | MODELS = [ROOT / "q27", pathlib.Path.home() / "models/qwen3.6-35b-a3b-fp8-95a723d0"] |
| 16 | PINS = ["0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3", |
| 17 | "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"] |
| 18 | SEP = "<|endoftext|>" |
| 19 | def digest(data): |
| 20 | return hashlib.sha256(data).hexdigest() |
| 21 | |
| 22 | def ids_bytes(ids): |
| 23 | return b"".join(b"%d\n" % i for i in ids) |
| 24 | |
| 25 | def run(model, mode, data, rc=0): |
| 26 | p = subprocess.run([HERE / "tokenizer", mode, model], input=data, capture_output=True, timeout=90) |
| 27 | assert p.returncode == rc, (model, mode, p.returncode, rc, p.stderr) |
| 28 | if rc: |
| 29 | assert not p.stdout |
| 30 | return p.stdout |
| 31 | |
| 32 | def same(actual, expected, label): |
| 33 | if actual != expected: |
| 34 | k = next((i for i,(x,y) in enumerate(zip(actual, expected)) if x != y), |
| 35 | min(len(actual), len(expected))) |
| 36 | raise AssertionError((label,k,actual[k:k+50],expected[k:k+50])) |
| 37 | |
| 38 | def group(model, tok, cases): |
| 39 | # Independent reference encoding per whole input. A recognized marker prevents |
| 40 | # a merge/normalization across cases while amortizing native JSON hash + load. |
| 41 | sep = tok.token_to_id(SEP) |
| 42 | ref = [] |
| 43 | actual = run(model, "encode", SEP.join(s for _,s in cases).encode()) |
| 44 | for i, (label, s) in enumerate(cases): |
| 45 | if i: |
| 46 | ref.append(sep) |
| 47 | ids = tok.encode(s, add_special_tokens=False).ids |
| 48 | ref.extend(ids) |
| 49 | print("case", model.name, label, len(ids), digest(s.encode()), digest(ids_bytes(ids))) |
| 50 | expected = ids_bytes(ref) |
| 51 | same(actual, expected, (model.name, cases[0][0], "ids")) |
| 52 | decoded = run(model, "decode", actual) |
| 53 | same(decoded, tok.decode(ref, skip_special_tokens=False).encode(), "decoded batch") |
| 54 | print("PASS group", model.name, cases[0][0], len(cases), digest(actual), digest(decoded)) |
| 55 | |
| 56 | def check(model): |
| 57 | file = model / "tokenizer.json" |
| 58 | data = file.read_bytes() |
| 59 | assert digest(data) == PINS[MODELS.index(model)] |
| 60 | config = json.loads(data) |
| 61 | tok = tokenizers.Tokenizer.from_file(str(file)) |
| 62 | print("model", model.name, digest(data), "oracle", tokenizers.__version__) |
| 63 | styles = {} |
| 64 | manifest = (PROMPTS / "SHA256SUMS").read_bytes() |
| 65 | assert digest(manifest) == "8c8aa9ac2df875e3d581f05ae2fecf25b67ef2675897e3679409dac1393930bb" |
| 66 | for line in manifest.decode().splitlines(): |
| 67 | sha, name = line.split() |
| 68 | path = PROMPTS / name |
| 69 | assert path.parent.name in {"q-compact", "q-sheet", "r40-native", "r40-write"} |
| 70 | raw = path.read_bytes() |
| 71 | assert digest(raw) == sha |
| 72 | styles.setdefault(path.parent.name, []).append((name,raw.decode())) |
| 73 | for rows in styles.values(): |
| 74 | label, s = rows[0] |
| 75 | same(run(model, "encode", s.encode()), ids_bytes(tok.encode(s).ids), label) |
| 76 | group(model, tok, rows) |
| 77 | rng = random.Random(948) |
| 78 | alphabet = " abcDE09\0\t\r\n\u00a0\u0085!?\u0301\u0323\u0345επ π©π½βπ»ΓΕΏβ'β«ΰ€ " |
| 79 | cases = [ |
| 80 | ("unicode", "a\u0315\u0300 e\u0301 β« \u1100\u1161\u11a8 \U00011099\U000110ba π©π½βπ»"), |
| 81 | ("contractions", "I'm I'S he'd 'ΕΏTEST we're ha'VE x'Ll?!\r\n\t next"), |
| 82 | ("canonical-decompositions", "|".join(c + ":" + unicodedata.normalize("NFD", c) |
| 83 | for c in map(chr, range(0x110000)) if unicodedata.normalize("NFD", c) != c)), |
| 84 | ("all-added", "".join(it["content"] for it in config["added_tokens"])), |
| 85 | ("model-specific", "x<|audio_start|><tts_text_eod><|audio_pad|>y"), |
| 86 | ("random", "".join(rng.choices(alphabet,k=20000))), |
| 87 | ("long-piece", "ab"*18000 + " "*17000), |
| 88 | ("split-marker", "a"*16380+"<|im_start|>"), |
| 89 | ("split-utf8", "a"*16383+"π"), |
| 90 | ("nfc-boundary", "a"*16383+"e\u0301"), |
| 91 | ] |
| 92 | group(model, tok, cases) |
| 93 | for key, s in cases[-3:]: |
| 94 | same(run(model, "encode", s.encode()), ids_bytes(tok.encode(s).ids), key) |
| 95 | same(run(model, "encode", b""), b"", "empty encode") |
| 96 | same(run(model, "decode", b""), b"", "empty decode") |
| 97 | # Raw byte oracle, independent of UTF-8 replacement behavior in text decoders. |
| 98 | plain = list(range(33,127))+list(range(161,173))+list(range(174,256)) |
| 99 | escaped = [i for i in range(256) if i not in plain] |
| 100 | inverse = {chr(i):i for i in plain} |
| 101 | inverse.update({chr(256+k):i for k,i in enumerate(escaped)}) |
| 102 | by_id = {i:bytes(inverse[c] for c in s) for s,i in config["model"]["vocab"].items()} |
| 103 | by_id.update({a["id"]:a["content"].encode() for a in config["added_tokens"]}) |
| 104 | ids = sorted(by_id) |
| 105 | same(run(model, "decode", b"0"), by_id[0], "unterminated final ID") |
| 106 | raw = b"".join(by_id[i] for i in ids) |
| 107 | same(run(model, "decode", ids_bytes(ids)), raw, "every id raw bytes") |
| 108 | print("PASS every id", model.name, len(ids), "raw_sha256", digest(raw)) |
| 109 | for bad in [b"abc\x80", b"\xc0\xaf", b"\xef\xbf", b"\xed\xa0\x80", b"\xf4\x90\x80\x80"]: |
| 110 | run(model, "encode", bad, 6) |
| 111 | for bad in [b"-1\n", b"2\n\n", b"12x", b"1 2", b"1\n"+b"9"*500, |
| 112 | ids_bytes([ids[-1]+1]), b"0\n"*20000+b"?"]: |
| 113 | run(model, "decode", bad, 7) |
| 114 | with tempfile.TemporaryDirectory(dir=HERE) as tmp: |
| 115 | damaged = bytearray(data) |
| 116 | damaged[len(data)//2] ^= 1 |
| 117 | pathlib.Path(tmp, "tokenizer.json").write_bytes(damaged) |
| 118 | run(tmp, "encode", b"abc", 3) |
| 119 | print("PASS malformed UTF-8, IDs, frozen file mutation and empty streams", model.name) |
| 120 | |
| 121 | if __name__ == "__main__": |
| 122 | for model in MODELS: |
| 123 | check(model) |
| 124 | print("PASS both frozen tokenizers") |