Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-train/blob/main/eval/omegese45/oe45lib.py # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-train / eval / omegese45 / oe45lib.py` 356 lines · 11503 bytes Raw Blame History 1 """Eval-owned R45 codec, grammar parser, binding check and reference policy. 2 3 Independent oracle for aien-train #45 (eval lane). Written from the shared 4 interface (docs: interface v1 sections 2-3), not from the contract, translator or 5 pipeline lanes' code. Python standard library only. 6 7 Two deliberately separate codings of the reference policy exist: 8 - `policy_next` (this file) decides the next model message from an episode 9 prefix; it is the deterministic control. 10 - `oe_sealgen.build_episode` writes whole episodes from a per-job outcome 11 script; it is the sealed-set generator. 12 The deterministic control scoring 1.0 on the sealed set cross-checks the two. 13 """ 14 15 VOCAB = ( 16 ["", "goal", "act", "res", "rep", "end", "mm", "pair", "job", "refuse", 17 "ok", "refused", "fail", "bound", "replay", "budget", "worker", "transport", 18 "receipt", "recomp", "verdict", "io", "ushort", "ulong", "0x"] 19 + list("`0123456789abcdef`") 20 ) 21 assert len(VOCAB) == 41 22 WID = {w: i for i, w in enumerate(VOCAB)} 23 HEX = "`0123456789abcdef`" 24 CODES = ["bound", "replay", "budget", "worker", "transport", "receipt", "recomp", 25 "verdict", "io"] 26 RCODES = CODES[1:] # C' = C without bound (runtime-only) 27 # Runtime class of each C' code as aienet0-run reports it (interface §2 and §5): 28 # exit 11 worker refusal -> refused (replay, budget, worker); 29 # exits 10, 12, 13, 14, 15 -> fail (transport, receipt, recomp, verdict, io). 30 RUNTIME_CLASS = {"replay": "refused", "budget": "refused", "worker": "refused", 31 "transport": "fail", "receipt": "fail", "recomp": "fail", 32 "verdict": "fail", "io": "fail"} 33 DIM_LO, DIM_HI = 0x001, 0x100 34 EPISODE_HEADER = "oe45 v1" 35 36 37 class CodecError(ValueError): 38 pass 39 40 41 def surface_to_ids(line): 42 """Strict surface text -> ids. Raises CodecError with a typed reason.""" 43 if isinstance(line, str): 44 try: 45 raw = line.encode("ascii") 46 except UnicodeEncodeError: 47 raise CodecError("non-ascii") 48 else: 49 raw = bytes(line) 50 if any(b > 0x7E or (b < 0x20) for b in raw): 51 if b"\r" in raw: 52 raise CodecError("cr") 53 if b"\t" in raw: 54 raise CodecError("tab") 55 raise CodecError("non-ascii-or-control") 56 text = raw.decode("ascii") 57 if text == "": 58 raise CodecError("empty") 59 words = text.split(" ") 60 if any(w == "" for w in words): 61 raise CodecError("space") 62 ids = [] 63 for w in words: 64 if w.startswith("0x") and len(w) > 2: 65 ids.append(WID["0x"]) 66 for ch in w[2:]: 67 if ch not in HEX: 68 raise CodecError("bad-hex") 69 ids.append(WID[ch]) 70 elif w in WID and w != "" and w != "0x" and w not in HEX: 71 ids.append(WID[w]) 72 else: 73 raise CodecError("unknown-word") 74 return ids 75 76 77 def ids_to_surface(ids): 78 out = [] 79 i = 0 80 while i < len(ids): 81 t = ids[i] 82 if not (0 <= t < len(VOCAB)) or t == 0: 83 raise CodecError("bad-id") 84 w = VOCAB[t] 85 if w == "0x": 86 j = i + 1 87 s = "0x" 88 while j < len(ids) and VOCAB[ids[j]] in HEX and len(VOCAB[ids[j]]) == 1: 89 s += VOCAB[ids[j]] 90 j += 1 91 out.append(s) 92 i = j 93 continue 94 out.append(w) 95 i += 1 96 return " ".join(out) 97 98 99 # ---------------------------------------------------------------- grammar 100 class Msg: 101 """Parsed message. kind in G A R P; fields per grammar.""" 102 __slots__ = ("kind", "frame", "jk", "dims", "seeds", "cls", "code", "text") 103 104 def __init__(self, **kw): 105 for s in self.__slots__: 106 setattr(self, s, kw.get(s)) 107 108 def __repr__(self): 109 return "Msg(%s)" % self.text 110 111 112 def _hexval(ids, pos, n): 113 v = 0 114 for t in ids[pos:pos + n]: 115 w = VOCAB[t] if 0 <= t < len(VOCAB) else "" 116 if len(w) != 1 or w not in HEX: 117 return None 118 v = v * 16 + HEX.index(w) 119 if pos + n > len(ids): 120 return None 121 return v 122 123 124 def _dim(ids, p): 125 # D := ushort 0x H H H (5 ids) 126 if p + 5 > len(ids) or ids[p] != WID["ushort"] or ids[p + 1] != WID["0x"]: 127 return None 128 return _hexval(ids, p + 2, 3) 129 130 131 def _seed(ids, p): 132 # S := ulong 0x H H H H (6 ids) 133 if p + 6 > len(ids) or ids[p] != WID["ulong"] or ids[p + 1] != WID["0x"]: 134 return None 135 return _hexval(ids, p + 2, 4) 136 137 138 def _operands(ids, p, kind): 139 dims = [] 140 for _ in range(3): 141 d = _dim(ids, p) 142 if d is None: 143 return None, p 144 dims.append(d) 145 p += 5 146 nseeds = 1 if kind == "mm" else 2 147 seeds = [] 148 for _ in range(nseeds): 149 s = _seed(ids, p) 150 if s is None: 151 return None, p 152 seeds.append(s) 153 p += 6 154 return (tuple(dims), tuple(seeds)), p 155 156 157 def parse_ids(ids): 158 """Parse one message (ids). Returns Msg or raises ValueError(reason).""" 159 ids = list(ids) 160 if not ids: 161 raise ValueError("empty") 162 W = WID 163 f = ids[0] 164 def done(p, m): 165 if p >= len(ids) or ids[p] != W["end"]: 166 raise ValueError("missing-end") 167 if p + 1 != len(ids): 168 raise ValueError("bytes-after-end") 169 m.text = ids_to_surface(ids) 170 return m 171 if f == W["goal"]: 172 if len(ids) < 2 or ids[1] not in (W["mm"], W["pair"]): 173 raise ValueError("goal-kind") 174 kind = VOCAB[ids[1]] 175 ops, p = _operands(ids, 2, kind) 176 if ops is None: 177 raise ValueError("goal-operand") 178 return done(p, Msg(kind="G", frame="goal", jk=kind, dims=ops[0], seeds=ops[1])) 179 if f == W["act"]: 180 if len(ids) >= 2 and ids[1] == W["job"]: 181 if len(ids) < 3 or ids[2] != W["mm"]: 182 raise ValueError("act-kind") 183 ops, p = _operands(ids, 3, "mm") 184 if ops is None: 185 raise ValueError("act-operand") 186 return done(p, Msg(kind="A", frame="act", jk="job", dims=ops[0], seeds=ops[1])) 187 if len(ids) >= 3 and ids[1] == W["refuse"] and ids[2] == W["bound"]: 188 return done(3, Msg(kind="A", frame="act", jk="refuse", code="bound")) 189 raise ValueError("act-form") 190 if f == W["res"]: 191 if len(ids) >= 2 and ids[1] == W["ok"]: 192 return done(2, Msg(kind="R", frame="res", cls="ok")) 193 if len(ids) >= 3 and ids[1] in (W["refused"], W["fail"]) and VOCAB[ids[2]] in RCODES: 194 return done(3, Msg(kind="R", frame="res", cls=VOCAB[ids[1]], code=VOCAB[ids[2]])) 195 raise ValueError("res-form") 196 if f == W["rep"]: 197 if len(ids) >= 2 and ids[1] == W["ok"]: 198 if len(ids) < 3 or ids[2] not in (W["mm"], W["pair"]): 199 raise ValueError("rep-kind") 200 kind = VOCAB[ids[2]] 201 ops, p = _operands(ids, 3, kind) 202 if ops is None: 203 raise ValueError("rep-operand") 204 return done(p, Msg(kind="P", frame="rep", cls="ok", jk=kind, dims=ops[0], seeds=ops[1])) 205 if len(ids) >= 3 and ids[1] in (W["refused"], W["fail"]) and ids[2] < len(VOCAB) and VOCAB[ids[2]] in CODES: 206 return done(3, Msg(kind="P", frame="rep", cls=VOCAB[ids[1]], code=VOCAB[ids[2]])) 207 raise ValueError("rep-form") 208 raise ValueError("frame") 209 210 211 def parse_line(line): 212 return parse_ids(surface_to_ids(line)) 213 214 215 def is_model_msg(m): 216 return m is not None and m.kind in ("A", "P") 217 218 219 def admitted(d): 220 return DIM_LO <= d <= DIM_HI 221 222 223 # ------------------------------------------------------------- formatting 224 def fmt_dim(d): 225 return "ushort 0x%03x" % d 226 227 228 def fmt_seed(s): 229 return "ulong 0x%04x" % s 230 231 232 def fmt_ops(dims, seeds): 233 return " ".join([fmt_dim(d) for d in dims] + [fmt_seed(s) for s in seeds]) 234 235 236 def fmt_goal(kind, dims, seeds): 237 return "goal %s %s end" % (kind, fmt_ops(dims, seeds)) 238 239 240 def fmt_act(dims, seed): 241 return "act job mm %s end" % fmt_ops(dims, (seed,)) 242 243 244 ACT_REFUSE = "act refuse bound end" 245 246 247 def fmt_res(cls, code=None): 248 return "res ok end" if cls == "ok" else "res %s %s end" % (cls, code) 249 250 251 def fmt_rep_ok(kind, dims, seeds): 252 return "rep ok %s %s end" % (kind, fmt_ops(dims, seeds)) 253 254 255 def fmt_rep(cls, code): 256 return "rep %s %s end" % (cls, code) 257 258 259 # ------------------------------------------------------- binding check 260 def binding_ok(goal, act, job_index): 261 """Interface §3 binding: act job dims == goal dims, seed == current job seed, 262 every dim admitted. Returns (ok, reason).""" 263 if act.kind != "A" or act.jk != "job": 264 return True, "not-a-job" 265 if any(not admitted(d) for d in act.dims): 266 return False, "bound" 267 if act.dims != goal.dims: 268 return False, "mismatch-dims" 269 if job_index >= len(goal.seeds) or act.seeds[0] != goal.seeds[job_index]: 270 return False, "mismatch-seed" 271 return True, "ok" 272 273 274 def current_job_index(msgs): 275 """Index of the job the next action addresses, given the prefix (interface §3.2).""" 276 goal = msgs[0] 277 j, tseen = 0, False 278 for m in msgs[1:]: 279 if m.kind != "R": 280 continue 281 if m.cls == "ok": 282 j, tseen = j + 1, False 283 elif m.cls == "fail" and m.code == "transport" and not tseen: 284 tseen = True 285 else: 286 return None 287 return j if j < len(goal.seeds) else None 288 289 290 # ----------------------------------------------------- reference policy 291 def policy_next(msgs): 292 """Deterministic reference policy (interface §3): next model message text 293 from a parsed episode prefix [G, (A, R?)*]. Uses only G and the R messages.""" 294 goal = msgs[0] 295 assert goal.kind == "G" 296 if any(not admitted(d) for d in goal.dims): 297 if len(msgs) == 1: 298 return ACT_REFUSE 299 return fmt_rep("refused", "bound") 300 njobs = len(goal.seeds) 301 j, tseen = 0, False 302 for m in msgs[1:]: 303 if m.kind != "R": 304 continue 305 if m.cls == "ok": 306 j, tseen = j + 1, False 307 continue 308 if m.cls == "fail" and m.code == "transport" and not tseen: 309 tseen = True 310 continue 311 return fmt_rep(m.cls, m.code) 312 if j >= njobs: 313 return fmt_rep_ok(goal.jk, goal.dims, goal.seeds) 314 return fmt_act(goal.dims, goal.seeds[j]) 315 316 317 # ----------------------------------------------------------- episodes 318 def parse_episode(text): 319 """OE45 v1 episode text -> list of lines (messages). Raises ValueError.""" 320 if not text.endswith("\n"): 321 raise ValueError("no-final-lf") 322 lines = text[:-1].split("\n") 323 if lines[0] != EPISODE_HEADER: 324 raise ValueError("header") 325 return lines[1:] 326 327 328 def check_episode_shape(msgs): 329 """Sequence G (A R?)+ P; an act refuse gets no R. Returns reason or None.""" 330 if not msgs or msgs[0].kind != "G": 331 return "first-not-G" 332 i = 1 333 nact = 0 334 while i < len(msgs) and msgs[i].kind == "A": 335 a = msgs[i] 336 nact += 1 337 i += 1 338 if a.jk == "refuse": 339 continue 340 if i >= len(msgs) or msgs[i].kind != "R": 341 return "act-without-res" 342 i += 1 343 if nact == 0: 344 return "no-act" 345 if i != len(msgs) - 1 or msgs[i].kind != "P": 346 return "not-ending-P" 347 return None 348 349 350 def decode_points(msgs): 351 """Indices i such that msgs[i] is a model message (A or P).""" 352 return [i for i, m in enumerate(msgs) if m.kind in ("A", "P")] 353 354 355 def episode_ids_len(lines): 356 return sum(len(surface_to_ids(l)) for l in lines)