Download code/compoundingkernel/controller.py from QianQu/CompoundingKernel-Explorer: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/code/compoundingkernel/controller.py
- Command line
-
hf download hf://spaces/QianQu/CompoundingKernel-Explorer/code/compoundingkernel/controller.py
-
curl -L -o controller.py https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/code/compoundingkernel/controller.py
14.6 kB
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | |
| # SPDX-License-Identifier: CC-BY-NC-4.0 | |
| """Loop 2: one LLM controller per problem picks the parents and the directions; children fill free slots.""" | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import json | |
| import os | |
| import random | |
| import re | |
| import time | |
| from . import archive as archive_mod | |
| from . import child, load_config, load_prompt | |
| from .checks import robustness, sanitizer | |
| # In the final run the LLM controller chose every parent and direction (arm "hyper"). It has two | |
| # tools: query_archive (read-only SQL over its run's archive) and expand(parent, directions), | |
| # which starts one child per direction on a free GPU slot, waits until a slot is free again and | |
| # reports what changed. Slots are refilled as children end, until the time limit or the budget. | |
| # The UCB-style tree (run_tree, arm "tree") was only the A/B baseline. The config keys and | |
| # their defaults are in compoundingkernel.DEFAULTS and examples/example_config.yaml. | |
| _API_ERROR = re.compile(r"\s*API Error\b[^\n]*") | |
| _TRANSIENT = re.compile(r"\b(?:5\d\d|429)\b|overloaded|throttl|unable to process|too many requests", | |
| re.I) | |
| class Search: | |
| """One search's live state. Everything that lasts is in the archive, so a stopped search resumes.""" | |
| def __init__(self, cfg): | |
| s, self.cfg, self.c = cfg["search"], cfg, cfg["controller"] | |
| problem_id = os.path.basename(os.path.normpath(s["problem_dir"])) | |
| self.archive = archive_mod.Archive(s["archive_dir"], problem_id, s["run_id"], | |
| cfg["checks"]["precision"]) | |
| self.budget, self.used, self.seq = int(s["budget"]), 0, 0 | |
| self.deadline = time.time() + 60.0 * float(s["time_limit_min"]) | |
| self.free = [(int(g), "g%d_%d" % (int(g), m)) # GPUs interleaved | |
| for m in range(int(s["children_per_gpu"])) for g in s["gpus"]] | |
| self.n_slots = len(self.free) | |
| self.inflight, self.finished, self.flags = {}, [], [] | |
| self.shown, self.checked, self.validations = set(), set(), set() | |
| def minutes_left(self) -> float: | |
| return max(0.0, (self.deadline - time.time()) / 60.0) | |
| def start(self, parent, direction) -> dict: | |
| gpu, slot = self.free.pop(0) | |
| self.used += 1 | |
| self.seq += 1 | |
| info = {"child": self.seq, "parent": parent, "t0": time.time()} | |
| info["task"] = asyncio.ensure_future(self._child(info, direction, gpu, slot)) | |
| self.inflight[self.seq] = info | |
| return {"child": self.seq, "direction": (direction or "")[:120]} | |
| async def _child(self, info, direction, gpu, slot): | |
| res, err = {}, None | |
| try: | |
| res = await child.run_child(self.cfg, self.archive, info["parent"], direction, gpu, slot) | |
| except Exception as e: # a failed child is reported, never fatal to the search | |
| err = type(e).__name__ | |
| finally: | |
| self.free.append((gpu, slot)) | |
| self.inflight.pop(info["child"], None) | |
| self.finished.append({"child": info["child"], "parent": info["parent"], "error": err, | |
| "minutes": round((time.time() - info["t0"]) / 60.0, 1), | |
| "candidates": res.get("candidates"), "evals": res.get("evals")}) | |
| task = asyncio.ensure_future(self.validate(gpu)) | |
| self.validations.add(task) | |
| task.add_done_callback(self.validations.discard) | |
| async def validate(self, gpu): | |
| """Plain code, not a model, checks each new best. A best that fails stops counting.""" | |
| k, h = self.cfg["checks"], self.cfg["harness"] | |
| kw = {"gpu_id": gpu, "lock_dir": h["lock_dir"], "compile_timeout_s": h["compile_timeout_s"], | |
| "eval_timeout_s": h["eval_timeout_s"]} | |
| for _ in range(3): # if the best fails, check the next best | |
| best = self.archive.best(pending_ok=True) | |
| if best is None or best["cand_id"] in self.checked: | |
| return | |
| cid = best["cand_id"] | |
| self.checked.add(cid) | |
| path, out = self.archive.solution_path(cid), os.path.join(self.archive.dir, "checks", cid) | |
| todo = [("robustness", robustness.check, "NOT_ROBUST", k["robustness_on_new_best"], | |
| {"n_shapes": int(k["robustness_shapes"])}), | |
| ("sanitizer", sanitizer.check, "errors", k["sanitizer_on_new_best"], {})] | |
| failed = False | |
| for name, check, bad, on, extra in todo: | |
| if not on or best.get(name) or failed: | |
| continue | |
| v = (await asyncio.to_thread(check, self.cfg["search"]["problem_dir"], path, | |
| os.path.join(out, name), **dict(kw, **extra)))["verdict"] | |
| self.archive.add_check(cid, name, v) | |
| if v == bad: | |
| failed = True | |
| self.flags.append({"cand_id": cid, "check": name, "verdict": v}) | |
| if not failed: | |
| return | |
| async def wait(self, pure_wait): | |
| """Until a slot is free (a pure wait: until a child ends, at most idle_wait_min), then a grace.""" | |
| t0, waited = time.time(), False | |
| while self.inflight and not (self.finished if pure_wait else self.free): | |
| left = self.deadline - time.time() | |
| if self.free: # only a pure wait holds a free slot | |
| left = min(left, 60.0 * self.c["idle_wait_min"] - (time.time() - t0)) | |
| if left <= 0: | |
| break | |
| await asyncio.wait([i["task"] for i in self.inflight.values()], timeout=left, | |
| return_when=asyncio.FIRST_COMPLETED) | |
| waited = True | |
| if waited and self.inflight: # children ending together are reported together | |
| grace = max(0.0, min(float(self.c["grace_s"]), self.deadline - time.time())) | |
| await asyncio.wait([i["task"] for i in self.inflight.values()], timeout=grace) | |
| def new_candidates(self, limit=25) -> list: | |
| rows = [r for r in self.archive.candidates() if r.get("correct") | |
| and r["cand_id"] not in self.shown][-limit:] | |
| self.shown.update(r["cand_id"] for r in rows) | |
| return [{"cand_id": r["cand_id"], "parent_id": r.get("parent_id"), "reward": r.get("reward"), | |
| "sol_score": r.get("sol_score"), "counted": r.get("counted"), | |
| "notes": (r.get("notes") or "")[:200]} for r in reversed(rows)] | |
| async def expand(self, parent, directions) -> dict: | |
| """One child per direction on free slots; wait for a slot; report what changed.""" | |
| started, not_started = [], [] | |
| if time.time() < self.deadline and self.used < self.budget: | |
| for d in directions: | |
| if self.free and self.used < self.budget: | |
| started.append(self.start(parent, d)) | |
| else: | |
| not_started.append(d[:120]) | |
| await self.wait(pure_wait=not directions) | |
| now = time.time() | |
| out = {"stop": "time_limit" if now >= self.deadline else | |
| "budget" if self.used >= self.budget else None, | |
| "started": started, "not_started": not_started, "finished": self.finished, | |
| "running": [{"child": i["child"], "parent": i["parent"], | |
| "minutes": round((now - i["t0"]) / 60.0, 1)} for i in self.inflight.values()], | |
| "free_slots": len(self.free), "used": self.used, "budget": self.budget, | |
| "minutes_remaining": round(self.minutes_left(), 1), | |
| "new_candidates": self.new_candidates(), "flags": self.flags} | |
| self.finished, self.flags = [], [] | |
| return out | |
| async def drain(self): | |
| """Wait for every running child and check: children are never killed.""" | |
| while self.inflight or self.validations: | |
| await asyncio.wait([i["task"] for i in self.inflight.values()] + list(self.validations)) | |
| async def _read_turn(client): | |
| """(the text the turn ended with, an SDK error code, whether a tool was used) for one turn.""" | |
| text, err, used = None, None, False | |
| async for msg in client.receive_response(): | |
| err = getattr(msg, "error", None) or err | |
| status = getattr(msg, "api_error_status", None) | |
| if isinstance(status, int) and (status == 429 or status >= 500): | |
| err = "server_error" | |
| blocks = getattr(msg, "content", None) | |
| for b in blocks if isinstance(blocks, list) else []: | |
| if hasattr(b, "text"): | |
| text = b.text | |
| elif hasattr(b, "name"): | |
| used = True | |
| if getattr(msg, "result", None): | |
| text = str(msg.result) | |
| return text, err, used | |
| def _transient(text, err) -> bool: | |
| """A turn that ended on a server-side error (5xx, 429, overload): retried, never counted.""" | |
| m = _API_ERROR.match(text or "") | |
| return bool(m and _TRANSIENT.search(m.group())) or err in ("server_error", "rate_limit") | |
| async def drive(client, st, first_turn): | |
| """Send the first turn; when the controller ends a turn with time left, send a follow-up.""" | |
| c, pdir = st.c, st.cfg["prompts"].get("prompt_dir") | |
| await client.query(first_turn) | |
| counted = streak = turn = 0 | |
| while True: | |
| try: | |
| text, err, used_tool = await _read_turn(client) | |
| except Exception: | |
| if turn == 0: | |
| raise # the first turn's errors are real errors | |
| return # a follow-up on a dead session: the end | |
| if st.minutes_left() <= c["min_left_min"] or st.used >= st.budget: | |
| return | |
| transient = _transient(text, err) | |
| if transient: # exponential backoff with jitter | |
| streak = 1 if used_tool else streak + 1 | |
| d = min(float(c["backoff_cap_s"]), float(c["backoff_s"]) * 2 ** (min(streak, 20) - 1)) | |
| await asyncio.sleep(random.uniform(d / 2, d)) | |
| else: | |
| streak = 0 | |
| if counted >= c["reinvoke_max"]: | |
| return | |
| counted += 1 | |
| await asyncio.sleep(5) | |
| turn += 1 | |
| try: | |
| await client.query(load_prompt( | |
| "controller_continue", pdir, minutes_remaining=round(st.minutes_left(), 1), | |
| used=st.used, budget=st.budget, transient=int(transient))) | |
| except Exception: | |
| return | |
| async def run_hyper(cfg): | |
| """The final run's arm: the LLM controller picks parents and directions with its two tools.""" | |
| from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, create_sdk_mcp_server, tool | |
| st, pdir = Search(cfg), cfg["prompts"].get("prompt_dir") | |
| async def query_archive(args): | |
| return child.tool_result(await asyncio.to_thread(st.archive.query, str(args.get("sql") or ""))) | |
| async def expand(args): | |
| parent = str(args.get("parent_cand") or "").strip() | |
| parent = None if parent.lower() in ("", "none", "null", "root") else parent # a new root | |
| dirs = args.get("directions") | |
| dirs = [dirs] if isinstance(dirs, str) else dirs | |
| if parent is not None and not (st.archive.get(parent) or {}).get("correct"): | |
| return child.tool_result({"error": "unknown_parent"}) | |
| if not isinstance(dirs, list) or not all(isinstance(d, str) and d.strip() for d in dirs): | |
| return child.tool_result({"error": "bad_directions"}) | |
| return child.tool_result(await st.expand(parent, dirs)) | |
| server = create_sdk_mcp_server(name="search", version="1.0.0", tools=[query_archive, expand]) | |
| options = ClaudeAgentOptions( | |
| system_prompt=load_prompt("controller", pdir), model=cfg["model"]["id"], | |
| mcp_servers={"search": server}, | |
| allowed_tools=["mcp__search__query_archive", "mcp__search__expand"], | |
| disallowed_tools=list(child.DENIED_TOOLS) + ["Bash", "Write", "Edit", "NotebookEdit"], | |
| permission_mode="bypassPermissions", cwd=st.archive.dir, env=child.model_env(cfg), | |
| max_turns=int(cfg["model"]["controller_max_turns"])) | |
| first = load_prompt("controller_start", pdir, budget=st.budget, slots=st.n_slots, | |
| problem_dir=os.path.abspath(cfg["search"]["problem_dir"]), | |
| minutes=round(st.minutes_left())) | |
| try: | |
| async with ClaudeSDKClient(options=options) as client: | |
| await drive(client, st, first) | |
| finally: | |
| await st.drain() | |
| return st.archive.best() | |
| async def run_tree(cfg): | |
| """The A/B baseline only: a coded UCB-style tree picks the parents; children get no direction.""" | |
| st, t = Search(cfg), cfg["tree"] | |
| pruned, i = set(), 0 | |
| if not st.archive.nodes(): | |
| for _ in range(min(3, len(st.free))): # up to 3 cold roots | |
| st.start(None, None) | |
| await st.drain() | |
| while st.used < st.budget and time.time() < st.deadline and st.archive.nodes(): | |
| width = max(int(t["width_min"]), int(round(t["width_start"] * t["width_decay"] ** i))) | |
| for node in archive_mod.select_tree(st.archive.nodes(), max(1, st.n_slots // width), | |
| pruned, t["c"]): | |
| for _ in range(width): | |
| if st.free and st.used < st.budget: | |
| st.start(node["cand_id"], None) | |
| await st.drain() # the whole batch, then prune | |
| archive_mod.prune_tree(st.archive.nodes(), pruned, t["margin"], t["grace"]) | |
| i += 1 | |
| return st.archive.best() | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description="Run one CompoundingKernel search on one problem.") | |
| ap.add_argument("--config", required=True, help="a file like examples/example_config.yaml") | |
| cfg = load_config(ap.parse_args(argv).config) | |
| if not cfg["search"].get("problem_dir"): | |
| raise SystemExit("search.problem_dir is not set") | |
| best = asyncio.run(run_tree(cfg) if cfg["search"]["arm"] == "tree" else run_hyper(cfg)) | |
| print(json.dumps({k: (best or {}).get(k) for k in ("cand_id", "reward", "reward_basis", | |
| "sol_score")})) | |
| if __name__ == "__main__": | |
| main() | |