Download code/compoundingkernel/archive.py from QianQu/CompoundingKernel-Explorer: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/code/compoundingkernel/archive.py
- Command line
-
hf download hf://spaces/QianQu/CompoundingKernel-Explorer/code/compoundingkernel/archive.py
-
curl -L -o archive.py https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/code/compoundingkernel/archive.py
13.8 kB
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | |
| # SPDX-License-Identifier: CC-BY-NC-4.0 | |
| """The archive: every evaluated kernel with its parent. An append-only ledger, and a rebuilt SQLite copy.""" | |
| from __future__ import annotations | |
| import collections | |
| import fcntl | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import pathlib | |
| import re | |
| import sqlite3 | |
| import tempfile | |
| import threading | |
| import time | |
| from .checks import precision | |
| # One run of one problem lives in <root>/<problem>/<run>/: ledger.jsonl (append-only), one folder | |
| # per candidate (solution.json, eval.json), sessions/ (transcripts) and archive.sqlite. A | |
| # candidate's files are written first and its ledger row last, so a row always points to complete | |
| # files. The SQLite database is a copy rebuilt from the ledger; agents only read it. Failed tries | |
| # are rows too (correct = 0), so agents can see dead ends; only correct kernels are tree nodes. | |
| EVAL_FIELDS = ("compiled", "correct", "fail_class", "n_workloads", "n_passed", "t_k_ms_mean", | |
| "reward", "reward_basis", "sol_score", "flags") | |
| COLUMNS = { | |
| "candidates": ("cand_id TEXT PRIMARY KEY", "parent_id TEXT", "ts TEXT", "language TEXT", | |
| "direction TEXT", "notes TEXT", "compiled INTEGER", "correct INTEGER", | |
| "fail_class TEXT", "n_workloads INTEGER", "n_passed INTEGER", | |
| "t_k_ms_mean REAL", "reward REAL", "reward_basis TEXT", "sol_score REAL", | |
| "flags TEXT", "precision TEXT", "robustness TEXT", "sanitizer TEXT", | |
| "counted INTEGER"), | |
| "evaluation": ("cand_id TEXT", "workload_idx INTEGER", "workload TEXT", "axes TEXT", | |
| "status TEXT", "t_k_ms REAL"), | |
| "lineage": ("cand_id TEXT PRIMARY KEY", "root_id TEXT", "depth INTEGER", "n_children INTEGER", | |
| "n_descendants INTEGER", "n_correct_descendants INTEGER", | |
| "best_descendant_reward REAL"), | |
| } | |
| VIEWS = ("CREATE VIEW incumbent AS SELECT * FROM candidates WHERE counted = 1" | |
| " ORDER BY reward DESC LIMIT 1",) | |
| _READ_ACTIONS = frozenset({20, 21, 31, 33}) # SQLite authorizer: READ, SELECT, FUNCTION, RECURSIVE | |
| _PRAGMA, _PRAGMAS_OK = 19, frozenset({"table_info", "table_list", "index_list"}) | |
| _CAND_ID = re.compile(r"[0-9a-f]{12}") | |
| def cand_id_of(problem_id: str, sol_text: str) -> str: | |
| """The candidate id: a hash of the problem and the exact solution text (a replay adds no copy).""" | |
| return hashlib.sha1((problem_id + "\n" + sol_text).encode("utf-8", "surrogatepass")).hexdigest()[:12] | |
| def is_cand_id(s) -> bool: | |
| return isinstance(s, str) and _CAND_ID.fullmatch(s) is not None | |
| def _authorize(action, arg1, arg2, dbname, source): | |
| if action in _READ_ACTIONS or (action == _PRAGMA and (arg1 or "").lower() in _PRAGMAS_OK): | |
| return sqlite3.SQLITE_OK | |
| return sqlite3.SQLITE_DENY | |
| def _sql_value(v): | |
| if isinstance(v, bool): | |
| return int(v) | |
| return json.dumps(v) if isinstance(v, (list, dict)) else v | |
| def _counted(r, policy): | |
| """A correct kernel counts unless a check failed it; its measured numbers never change.""" | |
| if not r.get("correct") or {"impossibly_fast", "below_sol"} & set(r.get("flags") or ()): | |
| return 0 | |
| if r.get("robustness") == "NOT_ROBUST" or r.get("sanitizer") == "errors": | |
| return 0 | |
| return 1 if precision.counts(r.get("precision"), r.get("robustness"), policy) else 0 | |
| def _lineage(rows): | |
| """Per node: root, depth, children, and its subtree's size, correct count and best reward.""" | |
| kids, out = collections.defaultdict(list), {} | |
| for r in rows: # ledger order: a parent comes before its children | |
| up = out.get(r.get("parent_id")) | |
| if up is not None: | |
| kids[r["parent_id"]].append(r) | |
| out[r["cand_id"]] = {"root_id": up["root_id"] if up else r["cand_id"], | |
| "depth": up["depth"] + 1 if up else 0} | |
| for r in reversed(rows): # children first: sum each subtree | |
| o, best = out[r["cand_id"]], [] | |
| o.update(n_children=len(kids[r["cand_id"]]), n_descendants=0, n_correct_descendants=0) | |
| for k in kids[r["cand_id"]]: | |
| ko = out[k["cand_id"]] | |
| o["n_descendants"] += 1 + ko["n_descendants"] | |
| o["n_correct_descendants"] += int(bool(k.get("correct"))) + ko["n_correct_descendants"] | |
| best += [v for v in (k.get("reward") if k.get("counted") else None, | |
| ko["best_descendant_reward"]) if v is not None] | |
| o["best_descendant_reward"] = max(best) if best else None | |
| return out | |
| class Archive: | |
| """One run of one problem. Safe for several children (threads or processes) at once.""" | |
| def __init__(self, root, problem_id, run_id, precision_policy="paper"): | |
| self.problem_id, self.run_id, self.policy = problem_id, run_id, precision_policy | |
| self.dir = os.path.join(root, problem_id, run_id) | |
| self.ledger = os.path.join(self.dir, "ledger.jsonl") | |
| self.db = os.path.join(self.dir, "archive.sqlite") | |
| for sub in ("candidates", "sessions", "work", "checks"): | |
| os.makedirs(os.path.join(self.dir, sub), exist_ok=True) | |
| self._lock, self._rows, self._evals = threading.RLock(), None, {} | |
| # -- writing ------------------------------------------------------------------------------ | |
| def _append(self, row): | |
| row = dict(row, ts=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) | |
| with self._lock, open(self.ledger, "a", encoding="utf-8") as f: | |
| fcntl.flock(f, fcntl.LOCK_EX) | |
| f.write(json.dumps(row) + "\n") | |
| f.flush() | |
| fcntl.flock(f, fcntl.LOCK_UN) | |
| self.rebuild() | |
| def record(self, sol_text, result, parent_id=None, **fields) -> str: | |
| """Store one evaluated candidate: its files first, then its ledger row (the commit).""" | |
| cid = cand_id_of(self.problem_id, sol_text) | |
| d = os.path.join(self.dir, "candidates", cid) | |
| os.makedirs(d, exist_ok=True) | |
| with open(os.path.join(d, "solution.json"), "w", encoding="utf-8") as f: | |
| f.write(sol_text) | |
| with open(os.path.join(d, "eval.json"), "w", encoding="utf-8") as f: | |
| json.dump({k: v for k, v in result.items() if k != "output"}, f, indent=1, default=str) | |
| row = {"kind": "eval", "cand_id": cid, "parent_id": parent_id or None} | |
| row.update((k, result.get(k)) for k in EVAL_FIELDS) | |
| row.update(fields) | |
| self._append(row) | |
| return cid | |
| def add_check(self, cand_id, check, verdict): | |
| """A later check verdict (robustness, sanitizer) for a stored candidate.""" | |
| self._append({"kind": "check", "cand_id": cand_id, "check": check, "verdict": verdict}) | |
| def save_session(self, name, records): | |
| with open(os.path.join(self.dir, "sessions", name + ".jsonl"), "w", encoding="utf-8") as f: | |
| f.writelines(json.dumps(r, default=str) + "\n" for r in records) | |
| # -- the rebuilt copy ----------------------------------------------------------------------- | |
| def rebuild(self) -> list: | |
| """Rebuild the SQLite copy from the ledger (a temporary file, then swapped in).""" | |
| with self._lock: | |
| cands, checks = collections.OrderedDict(), collections.defaultdict(dict) | |
| lines = [] | |
| if os.path.exists(self.ledger): | |
| with open(self.ledger, encoding="utf-8") as f: | |
| lines = f.read().splitlines() | |
| for line in lines: | |
| try: | |
| row = json.loads(line) | |
| except ValueError: | |
| continue # a torn last line: not committed | |
| cid = row.get("cand_id") if isinstance(row, dict) else None | |
| if not cid: | |
| continue | |
| if row.get("kind") == "check": | |
| checks[cid][row.get("check")] = row.get("verdict") | |
| elif cid not in cands: # the first record of a candidate decides | |
| p = row.get("parent_id") | |
| row["parent_id"] = p if p in cands and cands[p].get("correct") else None | |
| cands[cid] = row | |
| rows = [] | |
| for cid, r in cands.items(): | |
| r = dict(r, **{k: v for k, v in checks[cid].items() if k in ("robustness", "sanitizer")}) | |
| r["counted"] = _counted(r, self.policy) | |
| rows.append(r) | |
| self._write_db(rows, _lineage(rows)) | |
| self._rows = rows | |
| return rows | |
| def _workloads(self, cid): | |
| if cid not in self._evals: | |
| try: | |
| with open(os.path.join(self.dir, "candidates", cid, "eval.json"), encoding="utf-8") as f: | |
| ev = json.load(f) | |
| except (OSError, ValueError): | |
| ev = {} | |
| self._evals[cid] = [(cid, i, r.get("uuid"), json.dumps(r.get("axes")), r.get("status"), | |
| r.get("latency_ms")) for i, r in enumerate(ev.get("rows") or [])] | |
| return self._evals[cid] | |
| def _write_db(self, rows, lin): | |
| fd, tmp = tempfile.mkstemp(prefix=".archive-", suffix=".sqlite", dir=self.dir) | |
| os.close(fd) | |
| conn = sqlite3.connect(tmp) | |
| try: | |
| for table, cols in COLUMNS.items(): | |
| conn.execute("CREATE TABLE %s (%s)" % (table, ", ".join(cols))) | |
| for view in VIEWS: | |
| conn.execute(view) | |
| names = [c.split()[0] for c in COLUMNS["candidates"]] | |
| conn.executemany("INSERT INTO candidates VALUES (%s)" % ",".join("?" * len(names)), | |
| [[_sql_value(r.get(c)) for c in names] for r in rows]) | |
| conn.executemany("INSERT INTO evaluation VALUES (?,?,?,?,?,?)", | |
| [w for r in rows for w in self._workloads(r["cand_id"])]) | |
| lcols = [c.split()[0] for c in COLUMNS["lineage"]][1:] | |
| conn.executemany("INSERT INTO lineage VALUES (?,?,?,?,?,?,?)", | |
| [[cid] + [o[c] for c in lcols] for cid, o in lin.items()]) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| os.replace(tmp, self.db) | |
| # -- reading ------------------------------------------------------------------------------ | |
| def candidates(self) -> list: | |
| return self._rows if self._rows is not None else self.rebuild() | |
| def get(self, cand_id): | |
| return next((r for r in self.candidates() if r["cand_id"] == cand_id), None) | |
| def find_key(self, key): | |
| """An earlier candidate of this run with the same code (harness.solution_key), if any.""" | |
| return next((r for r in self.candidates() if key and r.get("key") == key), None) | |
| def solution_path(self, cand_id) -> str: | |
| return os.path.join(self.dir, "candidates", cand_id, "solution.json") | |
| def solution(self, cand_id): | |
| if not is_cand_id(cand_id) or self.get(cand_id) is None: | |
| return None | |
| with open(self.solution_path(cand_id), encoding="utf-8") as f: | |
| return json.load(f) | |
| def nodes(self) -> list: | |
| """The tree nodes: correct kernels that count.""" | |
| return [r for r in self.candidates() if r.get("counted")] | |
| def best(self, pending_ok=False): | |
| """The best node by reward. pending_ok: also a kernel still waiting for its checks.""" | |
| rows = [r for r in self.candidates() if r.get("counted") or ( | |
| pending_ok and _counted(dict(r, robustness=r.get("robustness") or "ROBUST"), self.policy))] | |
| return max(rows, key=lambda r: r.get("reward") or 0.0, default=None) | |
| def query(self, sql, limit=200) -> dict: | |
| """Read-only SQL over this run's archive: a read-only connection plus an authorizer.""" | |
| if not os.path.exists(self.db): | |
| self.rebuild() | |
| conn = sqlite3.connect(pathlib.Path(self.db).resolve().as_uri() + "?mode=ro", uri=True) | |
| try: | |
| conn.execute("PRAGMA query_only = ON") | |
| conn.set_authorizer(_authorize) | |
| cur = conn.execute(sql) | |
| rows = cur.fetchmany(limit + 1) | |
| return {"columns": [c[0] for c in cur.description or ()], | |
| "rows": [list(r) for r in rows[:limit]], "truncated": len(rows) > limit} | |
| except Exception as e: # sqlite errors, a second statement, a denied write | |
| return {"error": "sql_error", "detail": str(e)[:300]} | |
| finally: | |
| conn.close() | |
| # -- the tree baseline (the A/B arm; the final run's controller did not use it) ------------------ | |
| def select_tree(nodes, want, pruned, c=0.7) -> list: | |
| """UCB-style pick: reward / best + c * sqrt(ln(|A| + 1) / (children + 1)), over live nodes.""" | |
| visits = collections.Counter(n.get("parent_id") for n in nodes if n.get("parent_id")) | |
| live = [n for n in nodes if n["cand_id"] not in pruned] | |
| best = max([n.get("reward") or 0.0 for n in live] + [1e-12]) | |
| def ucb(n): | |
| explore = math.sqrt(math.log(len(nodes) + 1) / (visits[n["cand_id"]] + 1)) | |
| return (n.get("reward") or 0.0) / best + c * explore | |
| return sorted(live, key=ucb, reverse=True)[:want] | |
| def prune_tree(nodes, pruned, margin, grace) -> None: | |
| """Prune a node that has had `grace` children and is still more than `margin` below the best.""" | |
| if not nodes: | |
| return | |
| best = max(n.get("reward") or 0.0 for n in nodes) | |
| visits = collections.Counter(n.get("parent_id") for n in nodes if n.get("parent_id")) | |
| for n in nodes: | |
| r = n.get("reward") or 0.0 | |
| if n["cand_id"] not in pruned and visits[n["cand_id"]] >= grace and r < best - margin: | |
| pruned.add(n["cand_id"]) | |