interplane.Get Omega
Read in your language

aien-train

AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.

Brought by drakestapleton

branch main Branches Tags History

aien-train / tests / omegallm / kv-check.py

108 lines · 5524 bytes Raw Blame History
1#!/usr/bin/env python3
2"""KV-cached decode check for e993f179 (native/omegallm/model.om okvlcp and okvkv), host CPU only.
3
4e993f179 removed okvlcp's guard (any bank-B activation layer, l >= LAA, made ofwdi recompute every
5row) and made okvlay restore and save each bank-B layer's K/V slices (okvkv) instead of flipping the
6windows with oaflip. This check builds three ollm binaries with tests/omegallm/build.sh, all at the bx
7capacities (the only shapes with bank-B layers that init accepts; LAA = 1 for 258 8 16 2 32 4):
8 bx the product, at the bx capacities
9 kvg bx plus the removed guard: the guarded path
10 kvo bx plus e993f179 without its bank-B slices (old oaflip, no restore): the control
11and runs `ollm kvcmp CK N PROMPT MERGES` (ofwdi then olast against ofwd 0 then olast, f64 bits of every
12logit) on each case. Required per case:
13 bx exit 0, ndiff 0, and the cache was used (some step starts past row 0)
14 kvg exit 0, ndiff 0, every step starts at row 0 (so bank-B layers are present), and the same greedy
15 tokens as bx in both passes; ofwd is the same code in both binaries, so bx's incremental
16 logits are bit-identical to the guarded path's
17 kvo exit 43 with ndiff > 0 (the control must be caught)
18Last line: KV_CHECK PASS cases=C controls=C caught=C, exit 0; else KV_CHECK FAIL ... and exit 1.
19Env: OMC and CORE are passed to build.sh (its compiler pin is checked there).
20"""
21import os
22from pathlib import Path
23import re
24import struct
25import subprocess
26import sys
27import tempfile
28
29root = Path(__file__).resolve().parents[2]
30build = root / "tests/omegallm/build.sh"
31SHAPE = ["258", "8", "16", "2", "32", "4", "1"]
32SEEDS = ["7", "11"]
33PROMPTS = ["a", "ab"]
34STEPS = ["6", "12"]
35
36
37def fail(msg):
38 print(f"KV_CHECK FAIL {msg}")
39 sys.exit(1)
40
41
42def merges(path):
43 # a valid OLLM BPE merges file, V = 258 (two merges), as tests/omegallm/ollm_metrics_bench.py writes it
44 payload = struct.pack("<HHHH", ord("t"), ord("h"), ord("i"), ord("n"))
45 h = 14695981039346656037
46 for b in payload:
47 h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
48 path.write_bytes(struct.pack("<QQQ", 3550332126946413647, 258, h) + payload)
49
50
51def kvcmp(binary, ck, n, prompt, m):
52 p = subprocess.run([str(binary), "kvcmp", str(ck), n, prompt, str(m)],
53 capture_output=True, text=True, timeout=600)
54 ki = [l.split() for l in p.stdout.splitlines() if l.startswith("KI ")]
55 kf = [l.split() for l in p.stdout.splitlines() if l.startswith("KF ")]
56 last = re.findall(r"^KVCMP (\d+) (\d+) (\d+) (\d+)$", p.stdout, re.M)
57 if len(ki) != int(n) or len(kf) != int(n) or len(last) != 1:
58 fail(f"{binary.name} kvcmp {n} {prompt!r}: rc={p.returncode} malformed output {p.stdout[-200:]!r} {p.stderr[-200:]!r}")
59 return {"rc": p.returncode, "ndiff": int(last[0][1]),
60 "t0": [int(r[3]) for r in ki], "ki": [r[4] for r in ki], "kf": [r[3] for r in kf]}
61
62
63with tempfile.TemporaryDirectory(prefix="kv-check-") as tmp:
64 tmp = Path(tmp)
65 env = dict(os.environ, OUT=str(tmp))
66 bins = {}
67 for name, args, out in [("bx", ["--variant", "bx"], "ollm-var-bx"),
68 ("kvg", ["--variant", "kvg"], "ollm-var-kvg"),
69 ("kvo", ["--mutant", "kvo"], "ollm-mut-kvo")]:
70 p = subprocess.run(["sh", str(build)] + args, env=env, capture_output=True, text=True, timeout=1800)
71 if p.returncode != 0:
72 fail(f"build.sh {' '.join(args)} rc={p.returncode}: {(p.stderr or p.stdout).strip()[-300:]}")
73 bins[name] = tmp / out
74 m = tmp / "m258"
75 merges(m)
76 cases = caught = 0
77 for seed in SEEDS:
78 ck = tmp / f"ck{seed}"
79 p = subprocess.run([str(bins["bx"]), "init", str(ck)] + SHAPE + [seed, "10", "1000"],
80 capture_output=True, text=True, timeout=600)
81 if p.returncode != 0:
82 fail(f"init seed {seed} rc={p.returncode}")
83 for prompt in PROMPTS:
84 for n in STEPS:
85 case = f"seed={seed} prompt={prompt!r} steps={n}"
86 a = kvcmp(bins["bx"], ck, n, prompt, m)
87 g = kvcmp(bins["kvg"], ck, n, prompt, m)
88 o = kvcmp(bins["kvo"], ck, n, prompt, m)
89 if a["rc"] != 0 or a["ndiff"] != 0:
90 fail(f"{case}: KV-cached decode differs from the full forward: rc={a['rc']} ndiff={a['ndiff']}")
91 if max(a["t0"]) == 0:
92 fail(f"{case}: the cache was never used (every step started at row 0)")
93 if g["rc"] != 0 or g["ndiff"] != 0:
94 fail(f"{case}: guarded path rc={g['rc']} ndiff={g['ndiff']}")
95 if max(g["t0"]) != 0:
96 fail(f"{case}: guarded path reused rows (no bank-B layer at this shape): t0={g['t0']}")
97 if a["ki"] != g["ki"] or a["kf"] != g["kf"]:
98 fail(f"{case}: tokens differ from the guarded path: {a['ki']} {g['ki']}")
99 print(f"ok case {case} ndiff=0 t0={','.join(map(str, a['t0']))} guarded=identical")
100 cases += 1
101 if o["rc"] == 43 and o["ndiff"] > 0:
102 print(f"ok control kvo {case} caught ndiff={o['ndiff']}")
103 caught += 1
104 else:
105 print(f"FAIL control kvo {case} ESCAPED rc={o['rc']} ndiff={o['ndiff']}")
106 if caught != cases:
107 fail(f"cases={cases} controls={cases} caught={caught}")
108 print(f"KV_CHECK PASS cases={cases} controls={cases} caught={caught}")