omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / train / omega-llm / tools / combined / experiment / measure.py
| 1 | """Select programs with eight charged answers, seal them, then score them independently.""" |
| 2 | import argparse |
| 3 | from concurrent.futures import ThreadPoolExecutor |
| 4 | from collections import Counter |
| 5 | import hashlib |
| 6 | import json |
| 7 | from pathlib import Path |
| 8 | import tempfile |
| 9 | import time |
| 10 | |
| 11 | from engines import ComponentFailure, Engines |
| 12 | import fixture |
| 13 | |
| 14 | |
| 15 | def digest(path): |
| 16 | with path.open("rb") as reader: |
| 17 | return hashlib.file_digest(reader, "sha256").hexdigest() |
| 18 | |
| 19 | |
| 20 | def kit_hashes(kit): |
| 21 | files = ("combined", "solve", "om_formalize", "om_sketch", "om_synth", "predict", |
| 22 | "omc", "ollm", "merges.bin", "trace.ck", "r6.ck", "r3.ck", "base.ck", "r11.ck", |
| 23 | "S1_arith.sp", "S2_fold.sp", "S3_rewrite.sp", "S4_repair.sp") |
| 24 | hashes = {name: digest(kit/name) for name in files} |
| 25 | if hashes["trace.ck"] != "08fc55505c8fa6a094e30807e616b64e4ea6d186cd4ef769ed877e469bcaac91": |
| 26 | raise ValueError("private checkpoint differs from the registered baseline") |
| 27 | return hashes |
| 28 | |
| 29 | |
| 30 | def select_task(task, kit, mode, diagnostic=False): |
| 31 | xs = [tuple(x) for x in task["fixed"]] |
| 32 | pool = list(dict.fromkeys(tuple(x) for x in [*task["pool"], *xs])) |
| 33 | if len(xs) != 8 or len(set(xs)) != 8 or set(pool).intersection(map(tuple, task["score"])): |
| 34 | raise ValueError(("invalid input partition", task["id"])) |
| 35 | observed = {} |
| 36 | |
| 37 | def query(x): |
| 38 | if len(observed) >= 8 or x in observed or x not in pool: |
| 39 | raise ValueError(("invalid query", task["id"], x)) |
| 40 | observed[x] = tuple(fixture.ref(task, x)) |
| 41 | return observed[x] |
| 42 | |
| 43 | with tempfile.TemporaryDirectory() as d: |
| 44 | engine = Engines(kit, d, task["prompt"]) |
| 45 | start = time.monotonic() |
| 46 | error = None |
| 47 | try: |
| 48 | if mode == "baseline": |
| 49 | for x in xs: |
| 50 | query(x) |
| 51 | body, route = engine.baseline(list(observed.items())) |
| 52 | trace = [] |
| 53 | else: |
| 54 | from selection import choose |
| 55 | body, route, trace = choose(engine, xs, pool, query, mode == "adaptive") |
| 56 | except ComponentFailure as exc: |
| 57 | if not diagnostic: |
| 58 | raise |
| 59 | error = exc.details |
| 60 | body, route, trace = None, "component error", [] |
| 61 | elapsed = time.monotonic()-start |
| 62 | if not error and len(observed) != 8: |
| 63 | raise ValueError(("unfinished query budget", task["id"])) |
| 64 | return dict(id=task["id"], family=task["family"], group=task["group"], mode=mode, |
| 65 | query_count=len(observed), queries=list(observed.items()), route=route, |
| 66 | program=None if body is None else body.decode(), rounds=trace, seconds=elapsed, **({"error":error} if error else {})) |
| 67 | |
| 68 | |
| 69 | def score(task, selected, kit): |
| 70 | start = time.monotonic() |
| 71 | mismatch = None |
| 72 | prog = selected["program"] |
| 73 | if selected.get("error"): |
| 74 | verdict = "error" |
| 75 | elif prog is None: |
| 76 | verdict = "abstain" |
| 77 | else: |
| 78 | xs = list(map(tuple, task["score"])) |
| 79 | with tempfile.TemporaryDirectory() as d: |
| 80 | predicted = Engines(kit, d, task["prompt"]).predict(prog.encode(), xs) |
| 81 | for x, got in zip(xs, predicted, strict=True): |
| 82 | wanted = tuple(fixture.ref(task, x)) |
| 83 | if wanted != got: |
| 84 | mismatch = dict(x=x, expected=wanted, actual=got) |
| 85 | break |
| 86 | verdict = "correct" if mismatch is None else "wrong" |
| 87 | return {**selected, "verdict": verdict, "first_mismatch": mismatch, |
| 88 | "scoring_seconds": time.monotonic()-start} |
| 89 | |
| 90 | |
| 91 | def json_file(path, obj): |
| 92 | with path.open("x") as f: |
| 93 | json.dump(obj, f, indent=2) |
| 94 | f.write("\n") |
| 95 | |
| 96 | |
| 97 | def main(): |
| 98 | p = argparse.ArgumentParser(description=__doc__) |
| 99 | p.add_argument("split", choices=("dev", "eval")) |
| 100 | p.add_argument("output", type=Path) |
| 101 | p.add_argument("--kit", type=Path, required=True) |
| 102 | p.add_argument("--improved", type=Path) |
| 103 | p.add_argument("--jobs", type=int, default=1) |
| 104 | p.add_argument("--rewrite-only", action="store_true") |
| 105 | p.add_argument("--diagnose-interruption", action="store_true", |
| 106 | help="continue an interrupted run on identical pins with per-task error accounting; ineligible for qualification") |
| 107 | args = p.parse_args() |
| 108 | if args.split == "eval" and (not args.improved or args.rewrite_only): |
| 109 | p.error("final evaluation requires both registered kits and all tasks") |
| 110 | baseline = args.kit.resolve() |
| 111 | arms = {"baseline": (baseline, "baseline")} |
| 112 | if args.improved: |
| 113 | better = args.improved.resolve() |
| 114 | arms.update({"improved_cli": (better, "baseline"), "fixed": (better, "fixed"), |
| 115 | "adaptive": (better, "adaptive")}) |
| 116 | entries = list(fixture.tasks(args.split)) |
| 117 | if args.rewrite_only: |
| 118 | entries = [t for t in entries if " edit " in t["prompt"]] |
| 119 | out = args.output.resolve() |
| 120 | out.mkdir(exist_ok=args.diagnose_interruption) |
| 121 | registered = {arm: kit_hashes(k) for arm,(k,_) in arms.items()} |
| 122 | here = Path(__file__).resolve().parent |
| 123 | js = {"split":args.split, "fixture":digest(here/"fixture.py"), |
| 124 | "manifest":digest(here/"manifest.json"), "kits":registered, "jobs":args.jobs} |
| 125 | if args.diagnose_interruption: |
| 126 | if json.loads((out/"inputs.json").read_text()) != js: |
| 127 | raise ValueError("interrupted run has different source data, kit hashes or resource configuration") |
| 128 | json_file(out/"interruption.json", {"status":"diagnostic", "reason":"registered run stopped on a component failure"}) |
| 129 | else: |
| 130 | json_file(out/"inputs.json", js) |
| 131 | with ThreadPoolExecutor(max_workers=args.jobs) as workers: |
| 132 | for arm, (kit, mode) in arms.items(): |
| 133 | path = out/f"{arm}.sealed.jsonl" |
| 134 | existing = [json.loads(l) for l in path.read_text().splitlines()] if path.exists() else [] |
| 135 | if [r["id"] for r in existing] != [t["id"] for t in entries[:len(existing)]]: |
| 136 | raise ValueError("sealed prefix does not match frozen task order") |
| 137 | with path.open("a" if args.diagnose_interruption else "x") as f: |
| 138 | for row in workers.map(lambda t: select_task(t, kit, mode, args.diagnose_interruption), |
| 139 | entries[len(existing):]): |
| 140 | f.write(json.dumps(row)+"\n") |
| 141 | f.flush() |
| 142 | for arm, (kit, _) in arms.items(): |
| 143 | rows = [json.loads(line) for line in (out/f"{arm}.sealed.jsonl").read_text().splitlines()] |
| 144 | assert [r["id"] for r in rows] == [t["id"] for t in entries] |
| 145 | results = list(workers.map(lambda t,r: score(t,r,kit), entries, rows)) |
| 146 | json_file(out/f"{arm}.json", results) |
| 147 | print(arm, dict(Counter(r["verdict"] for r in results)), flush=True) |
| 148 | if registered != {arm:kit_hashes(k) for arm,(k,_) in arms.items()}: |
| 149 | raise RuntimeError("kit changed during experiment") |
| 150 | |
| 151 | |
| 152 | if __name__ == "__main__": |
| 153 | main() |