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 / eval / omegese45 / oe_controls.py

339 lines · 15025 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Controls and metrics on the sealed set (EVAL-CONTRACT.md sections 4-5).
3
4Eval-owned (OE45Eval). Python standard library only. Ground truth is the
5sealed bundle (oe_sealgen.py) and the eval reference policy (oe45lib.py);
6the pipeline's generator output (train/dev) is read only for the retrieval
7control, the overlap and leakage checks and the spec audit.
8
9Model controls run the pipeline core through its documented CLI
10(docs/omegese45/CORE-CLI.md: `batch CKDIR U|G IN OUT`), one batch per mode
11and checkpoint, over every decode-point prefix of the sealed set.
12
13Closed-loop success is computed from the teacher-forced decodes: every
14control here is a deterministic function of its input prefix (argmax decode,
15reference policy) or of the decode-point index (retrieval), and the scripted
16R messages are fixed, so while every earlier model message equals the
17reference the closed-loop prefix IS the sealed prefix. An episode therefore
18succeeds in closed loop iff every one of its decode points is an exact
19match, and the first mismatch ends it, as the contract defines.
20
21Usage: oe_controls.py SEALED SEED TRAIN DEV CORE CK0 CK1 OUTDIR
22Use '-' for CORE/CK0/CK1 to run DET/RET only (model controls print NOT_RUN).
23Writes counts.json, intervals.json, decodes.tsv, overlap.txt, xclass.tsv,
24spec-audit.txt, hash-check.txt and summary.txt in OUTDIR.
25"""
26
27import json
28import hashlib
29from collections import Counter
30import os
31import subprocess
32import sys
33
34HERE = os.path.dirname(os.path.abspath(__file__))
35sys.path.insert(0, HERE)
36
37import oe45lib as L # noqa: E402
38from oe_audit import audit_one # noqa: E402
39from oe_sealgen import read_bundle # noqa: E402
40import oe_episode as EP
41from oe_wilson import wilson
42
43HEADER = "oe45 v1"
44REFUSE = "act refuse bound end"
45TRANSPORT = "res fail transport end"
46
47
48def split_corpus(text):
49 """Pipeline generator output: concatenated `oe45 v1` episodes -> [lines]."""
50 eps = []
51 for ln in text.rstrip("\n").split("\n"):
52 if ln == HEADER:
53 eps.append([])
54 else:
55 eps[-1].append(ln)
56 return eps
57
58
59def model_lines(lines):
60 msgs = [L.parse_line(x) for x in lines]
61 return [lines[i] for i in L.decode_points(msgs)]
62
63
64def nearest(goal_ids, train_goals):
65 """Index of the train episode with the smallest position-wise id Hamming
66 distance (missing positions count as mismatches; first in order on ties)."""
67 best, best_d = -1, None
68 gl = len(goal_ids)
69 for idx, ids in train_goals:
70 d = abs(len(ids) - gl) + sum(a != b for a, b in zip(ids, goal_ids))
71 if best_d is None or d < best_d:
72 best, best_d = idx, d
73 if d == 0:
74 break
75 return best, best_d
76
77
78def run_batch(core, ck, mode, prefixes, path):
79 inp = path + ".in"
80 with open(inp, "w") as f:
81 f.write("".join(prefixes))
82 r = subprocess.run(["taskset", "-c", os.environ.get("AIEN_TEST_CPUS") or "0-9,15-19", "nice", "-n", "19", "ionice", "-c3",
83 core, "batch", ck, mode, inp, path], capture_output=True, text=True)
84 if r.returncode != 0:
85 raise SystemExit("core batch %s %s rc=%d %s" % (ck, mode, r.returncode, r.stderr))
86 out = open(path).read().rstrip("\n").split("\n")
87 if len(out) != len(prefixes):
88 raise SystemExit("core batch %s %s: %d lines for %d prefixes" % (ck, mode, len(out), len(prefixes)))
89 res = []
90 for ln in out:
91 res.append(ln[3:] if ln.startswith("ok ") else None)
92 return res, out
93
94
95def valid_model(text):
96 if text is None:
97 return False
98 try:
99 return L.parse_line(text).kind in ("A", "P")
100 except ValueError:
101 return False
102
103
104def main(argv):
105 if len(argv) != 9:
106 sys.stderr.write(__doc__)
107 return 2
108 sealed_p, seed_p, train_p, dev_p, core, ck0, ck1, out = argv[1:]
109 os.makedirs(out, exist_ok=True)
110 pins = [
111 (sealed_p, "1dc394c1cb9903572bf9b5f68532f18a80985ca2843faf67129607bb65dbce70"),
112 (seed_p, "1adc002cf1c1df90c76d473783f4828112f1ec27210ad662d8f4cc2b9c3c82f2"),
113 (os.path.join(HERE, "oe_sealgen.py"), "38fbeb7ced137d1184eb9aa9c1f42e6dfcec90189f0e6729623af4419a7d812a"),
114 (os.path.join(HERE, "oe45lib.py"), "31ea114aae4b8d8c68f8c3834c4b5e9f65db9d7ac0195d042b35de2f186a326d"),
115 ]
116 hashes = []
117 for path, expected in pins:
118 observed = hashlib.sha256(open(path, "rb").read()).hexdigest()
119 hashes.append("%s %s %s" % ("PASS" if observed == expected else "FAIL", observed, path))
120 open(os.path.join(out, "hash-check.txt"), "w").write("\n".join(hashes) + "\n")
121 if any(x.startswith("FAIL") for x in hashes):
122 print("INVALID commitment hash mismatch")
123 return 1
124 sealed = read_bundle(open(sealed_p).read())
125 train = split_corpus(open(train_p).read())
126 dev = split_corpus(open(dev_p).read())
127 manifest = {}
128 artifacts = [sealed_p, seed_p, train_p, dev_p]
129 if core != "-":
130 artifacts.append(core)
131 for ck in (ck0, ck1):
132 if ck != "-":
133 artifacts.extend(os.path.join(ck, name) for name in ("ck.a", "ck.b", "ck.done")
134 if os.path.isfile(os.path.join(ck, name)))
135 for path in artifacts:
136 manifest[path] = hashlib.sha256(open(path, "rb").read()).hexdigest()
137 json.dump(manifest, open(os.path.join(out, "inputs-sha256.json"), "w"), indent=1, sort_keys=True)
138 for name, ck in (("ck0", ck0), ("ck1", ck1)):
139 if core != "-" and ck != "-":
140 r = subprocess.run([core, "info", ck], capture_output=True, text=True)
141 open(os.path.join(out, name + "-info.txt"), "w").write(
142 r.stdout + r.stderr + "RC %d\n" % r.returncode)
143 if r.returncode:
144 raise ValueError("%s checkpoint info failed" % name)
145
146 # ---- spec audit of the pipeline generator (contract 4.6)
147 spec = []
148 spec_bad = False
149 for name, corpus in (("train", train), ("dev", dev),
150 ("sealed", [lines for _, _, lines in sealed])):
151 bad = []
152 for i, lines in enumerate(corpus):
153 ok, why, _ = audit_one(lines)
154 if not ok:
155 bad.append((i, why))
156 spec_bad = spec_bad or bool(bad)
157 spec.append("%s episodes=%d disagreements=%d" % (name, len(corpus), len(bad)))
158 spec.extend(" %s[%d] %s" % (name, i, w) for i, w in bad[:50])
159 open(os.path.join(out, "spec-audit.txt"), "w").write("\n".join(spec) + "\n")
160
161 # ---- overlap and leakage (contract 4.2-4.4, 4.7)
162 tg = {e[0] for e in train}
163 dg = {e[0] for e in dev}
164 te = {"\n".join(e) for e in train}
165 de = {"\n".join(e) for e in dev}
166 train_r = Counter(l for e in train for l in e if l.startswith("res "))
167 xc_report = ["eid\tR\ttrain_R_count\tfull_sequence_in_train\tfull_sequence_in_dev"]
168 ov = {"goal_in_train": 0, "goal_in_dev": 0, "episode_in_train": 0, "episode_in_dev": 0,
169 "episode_overlap_without_goal_overlap": 0, "xclass_lines_in_train": 0}
170 disjoint = set()
171 xlines = []
172 for eid, stratum, lines in sealed:
173 g_t, g_d = lines[0] in tg, lines[0] in dg
174 e_t, e_d = "\n".join(lines) in te, "\n".join(lines) in de
175 ov["goal_in_train"] += g_t
176 ov["goal_in_dev"] += g_d
177 ov["episode_in_train"] += e_t
178 ov["episode_in_dev"] += e_d
179 ov["episode_overlap_without_goal_overlap"] += (e_t and not g_t) or (e_d and not g_d)
180 if not g_t and not g_d:
181 disjoint.add(eid)
182 if stratum == "XCLASS":
183 for l in lines:
184 m = L.parse_line(l)
185 if m.kind == "R" and m.code and L.RUNTIME_CLASS.get(m.code) != m.cls:
186 xlines.append(l)
187 ov["xclass_lines_in_train"] += l in train_r
188 xc_report.append("%s\t%s\t%d\t%s\t%s" % (eid, l, train_r[l], e_t, e_d))
189 ov["xclass_lines"] = len(xlines)
190 ov["goal_disjoint_thresholded"] = sum(1 for e, s, _ in sealed if e in disjoint and s != "XCLASS")
191 # Parent clarification 2026-10-29: public grammar R strings are not
192 # sealed-only data. XCLASS line exposure is reported, never called novel.
193 leak = ov["episode_overlap_without_goal_overlap"] > 0
194 ov["leakage"] = leak
195 open(os.path.join(out, "overlap.txt"), "w").write(
196 "".join("%s %s\n" % (k, v) for k, v in ov.items()))
197 open(os.path.join(out, "xclass.tsv"), "w").write("\n".join(xc_report) + "\n")
198
199 # ---- decode points
200 points = [] # (eid, stratum, k, i, prefix_text, reference, msgs)
201 for eid, stratum, lines in sealed:
202 msgs = [L.parse_line(x) for x in lines]
203 for k, i in enumerate(L.decode_points(msgs)):
204 points.append((eid, stratum, k, i, HEADER + "\n" + "".join(x + "\n" for x in lines[:i]),
205 lines[i], msgs, lines))
206 prefixes = [p[4] for p in points]
207
208 # ---- controls
209 emitted = {}
210 raw = {}
211 emitted["DET"] = [L.policy_next(p[6][:p[3]]) for p in points]
212 train_goals = []
213 seen = set()
214 for idx, e in enumerate(train):
215 if e[0] not in seen: # first occurrence wins ties anyway
216 seen.add(e[0])
217 train_goals.append((idx, L.surface_to_ids(e[0])))
218 ret_pick = {}
219 for eid, stratum, lines in sealed:
220 ret_pick[eid] = nearest(L.surface_to_ids(lines[0]), train_goals)
221 emitted["RET"] = []
222 for p in points:
223 ml = model_lines(train[ret_pick[p[0]][0]])
224 emitted["RET"].append(ml[p[2]] if p[2] < len(ml) else None)
225 for name, ck, mode in (("U0", ck0, "U"), ("G0", ck0, "G"), ("U1", ck1, "U"), ("G1", ck1, "G")):
226 if core == "-" or ck == "-":
227 print("%s NOT_RUN checkpoint/core not supplied" % name)
228 continue
229 emitted[name], raw[name] = run_batch(core, ck, mode, prefixes, os.path.join(out, "batch-%s.out" % name))
230
231 with open(os.path.join(out, "decodes.tsv"), "w") as f:
232 f.write("eid\tstratum\tk\treference\t" + "\t".join(emitted) + "\n")
233 for j, p in enumerate(points):
234 f.write("\t".join([p[0], p[1], str(p[2]), p[5]] + [str(emitted[c][j]) for c in emitted]) + "\n")
235
236 # ---- metrics
237 def counts(ctrl, keep):
238 em = emitted[ctrl]
239 c = {k: [0, 0] for k in ("validity", "action_exact", "closed_loop", "completion", "recovery",
240 "refusal_precision", "refusal_recall", "retry", "report_exact")}
241 c["binding_needs"] = 0
242 c["binding_opportunities"] = 0
243 ep_ok = {}
244 for j, p in enumerate(points):
245 eid, stratum, k, i, _, ref, msgs, lines = p
246 if not keep(eid, stratum):
247 continue
248 got = em[j]
249 match = got == ref
250 c["validity"][0] += valid_model(got)
251 c["validity"][1] += 1
252 c["action_exact"][0] += match
253 c["action_exact"][1] += 1
254 ep_ok[eid] = ep_ok.get(eid, True) and match
255 if lines[i - 1] == TRANSPORT:
256 c["retry"][0] += match
257 c["retry"][1] += 1
258 if msgs[i].kind == "P":
259 c["report_exact"][0] += match
260 c["report_exact"][1] += 1
261 if k == 0:
262 pos, ref_pos = got == REFUSE, ref == REFUSE
263 c["refusal_precision"][0] += pos and ref_pos
264 c["refusal_precision"][1] += pos
265 c["refusal_recall"][0] += pos and ref_pos
266 c["refusal_recall"][1] += ref_pos
267 if valid_model(got):
268 m = L.parse_line(got)
269 if m.kind == "A" and m.jk == "job":
270 c["binding_opportunities"] += 1
271 ok, _ = EP.bind_current(msgs[0], m, msgs[:i])
272 c["binding_needs"] += not ok
273 for eid, stratum, lines in sealed:
274 if eid not in ep_ok:
275 continue
276 msgs = [L.parse_line(x) for x in lines]
277 s = ep_ok[eid]
278 c["closed_loop"][0] += s
279 c["closed_loop"][1] += 1
280 if msgs[-1].kind == "P" and msgs[-1].cls == "ok":
281 c["completion"][0] += s
282 c["completion"][1] += 1
283 admitted = lines[1] != REFUSE
284 if admitted and any(m.kind == "R" and m.cls != "ok" for m in msgs):
285 c["recovery"][0] += s
286 c["recovery"][1] += 1
287 return c
288
289 subsets = {
290 "thresholded": lambda e, s: s != "XCLASS",
291 "goal_disjoint": lambda e, s: s != "XCLASS" and e in disjoint,
292 "xclass": lambda e, s: s == "XCLASS",
293 }
294 result = {"overlap": ov, "controls": {}}
295 for ctrl in emitted:
296 result["controls"][ctrl] = {sub: counts(ctrl, f) for sub, f in subsets.items()}
297 result["ret_mean_distance"] = [sum(d for _, d in ret_pick.values()), len(ret_pick)]
298 result["ret_exact_goal"] = sum(1 for _, d in ret_pick.values() if d == 0)
299 json.dump(result, open(os.path.join(out, "counts.json"), "w"), indent=1, sort_keys=True)
300 intervals = {}
301 detail = ["subset\tcontrol\tmetric\tk\tn\tWilson95_lower\tWilson95_upper"]
302 for ctrl, subs in result["controls"].items():
303 intervals[ctrl] = {}
304 for sub, c in subs.items():
305 intervals[ctrl][sub] = {}
306 metrics = {k: v for k, v in c.items() if isinstance(v, list)}
307 metrics["binding_needed_rate"] = [c["binding_needs"], c["binding_opportunities"]]
308 for metric, (k, n) in metrics.items():
309 ci = wilson(k, n)
310 intervals[ctrl][sub][metric] = ci
311 lo, hi = ("NOT_DEFINED", "NOT_DEFINED") if ci is None else (
312 "%.12g" % ci[0], "%.12g" % ci[1])
313 detail.append("%s\t%s\t%s\t%d\t%d\t%s\t%s" % (sub, ctrl, metric, k, n, lo, hi))
314 json.dump(intervals, open(os.path.join(out, "intervals.json"), "w"), indent=1, sort_keys=True)
315 open(os.path.join(out, "intervals.tsv"), "w").write("\n".join(detail) + "\n")
316
317 lines = ["subset control " + " ".join(result["controls"]["DET"]["thresholded"])]
318 for sub in subsets:
319 for ctrl in emitted:
320 c = result["controls"][ctrl][sub]
321 lines.append("%s %s %s" % (sub, ctrl, " ".join(
322 "%d/%d" % tuple(v) if isinstance(v, list) else str(v) for v in c.values())))
323 lines.extend("%s NOT_RUN checkpoint/core not supplied" % ctrl
324 for ctrl in ("U0", "G0", "U1", "G1") if ctrl not in emitted)
325 open(os.path.join(out, "summary.txt"), "w").write("\n".join(lines) + "\n")
326 print("\n".join(lines))
327 print("\n".join(detail))
328 print("".join("%s %s\n" % (k, v) for k, v in ov.items()), end="")
329 print(spec[0])
330 print(spec[[i for i, s in enumerate(spec) if s.startswith("dev ")][0]])
331 det_bad = any(k != n for k, n in (
332 v for v in result["controls"]["DET"]["thresholded"].values() if isinstance(v, list)))
333 invalid = det_bad or leak or spec_bad
334 print("MACHINERY %s" % ("INVALID" if invalid else "PASS"))
335 return 1 if invalid else 0
336
337
338if __name__ == "__main__":
339 sys.exit(main(sys.argv))