QianQu's picture
Upload folder using huggingface_hub
902d2bb verified
Raw History Blame Contribute Delete
14 kB
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""Loop 1: one child agent session gets a parent and one direction, and writes one candidate kernel."""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import tempfile
from . import harness, load_prompt, score
from .archive import is_cand_id
from .checks import native_code, precision, robustness, sanitizer
# A child is one Claude Agent SDK session with in-process GPU tools (an SDK MCP server named
# "kernel") and the usual file tools. Each evaluated candidate is stored in the archive with its
# parent. "One candidate per child" is soft: evaluate_kernel returns stop = true once the cap is
# reached, and the child's prompt asks it to stop there. Sessions run with bypassPermissions and
# a deny list, so run children in a sandbox (a container that holds nothing it does not need).
TOOLS = ("compile_check", "evaluate_kernel", "profile_kernel", "check_robustness",
"query_history", "get_solution")
FILE_TOOLS = ("Read", "Write", "Edit", "Glob", "Grep", "Bash")
# Built-in tools a session may not use: they end the turn to be woken later, or start work the
# session never waits for (nothing here wakes a session up again).
DENIED_TOOLS = ("Agent", "Task", "ScheduleWakeup", "CronCreate", "Monitor")
NCU = ["ncu", "--csv", "--section", "SpeedOfLight", "--section", "Occupancy",
"--section", "LaunchStats"]
def model_env(cfg) -> dict:
"""Model access from your own setup: Amazon Bedrock (your AWS credentials) or an API key."""
m = cfg["model"]
env = {"ANTHROPIC_MODEL": m["id"]}
if m.get("provider", "bedrock") == "bedrock":
env["CLAUDE_CODE_USE_BEDROCK"] = "1"
if m.get("aws_region"):
env["AWS_REGION"] = m["aws_region"]
return env # "anthropic": ANTHROPIC_API_KEY from your environment
def tool_result(obj) -> dict:
"""A tool result: structured fields only (codes and numbers), as JSON text."""
return {"content": [{"type": "text", "text": json.dumps(obj, default=str)}]}
def _brief(res) -> dict:
"""What a tool reports of one harness run."""
rows = res.get("rows") or []
return {"compiled": res.get("compiled"), "correct": res.get("correct"),
"fail_class": res.get("fail_class"), "n_workloads": res.get("n_workloads"),
"n_passed": res.get("n_passed"), "t_k_ms_mean": res.get("t_k_ms_mean"),
"flags": res.get("flags"),
"workloads": [{k: r.get(k) for k in ("axes", "status", "latency_ms", "max_abs_error",
"max_rel_error")} for r in rows[:64]],
"error_tail": "" if res.get("correct") else (res.get("output") or "")[-2000:]}
class Child:
"""The state of one child session; its tools close over it."""
def __init__(self, cfg, archive, parent_id, direction, gpu_id, slot):
self.cfg, self.archive, self.parent_id, self.direction = cfg, archive, parent_id, direction
self.gpu_id, self.problem_dir = gpu_id, cfg["search"]["problem_dir"]
with open(os.path.join(self.problem_dir, "definition.json"), encoding="utf-8") as f:
self.defn = json.load(f)
self.board = os.path.basename(os.path.dirname(os.path.abspath(self.problem_dir)))
self.anchors = score.load_anchors(cfg["harness"].get("anchors"))
self.workdir = tempfile.mkdtemp(prefix=slot + "-", dir=os.path.join(archive.dir, "work"))
self.max_candidates = int(cfg["search"]["candidates_per_child"])
self.n_candidates = self.n_evals = 0
def kw(self) -> dict:
h = self.cfg["harness"]
return {"gpu_id": self.gpu_id, "lock_dir": h["lock_dir"],
"compile_timeout_s": h["compile_timeout_s"], "eval_timeout_s": h["eval_timeout_s"]}
def solution(self, args):
"""(solution, text, path, error code) for a solution.json inside this child's work dir."""
path = os.path.realpath(os.path.join(self.workdir, str(args.get("solution_path") or "")))
if not path.startswith(os.path.realpath(self.workdir) + os.sep):
return None, None, None, "path_outside_workdir"
try:
with open(path, encoding="utf-8") as f:
text = f.read()
sol = json.loads(text)
except (OSError, ValueError):
return None, None, None, "unreadable_solution"
if not isinstance(sol, dict) or not isinstance(sol.get("sources"), list):
return None, None, None, "not_a_solution"
return sol, text, path, None
def scratch(self, name) -> str:
d = os.path.join(self.workdir, ".runs", name)
os.makedirs(d, exist_ok=True)
return d
def one_workload(self, d) -> str:
return harness.write_jsonl(os.path.join(d, "one.jsonl"),
[harness.smallest_workload(self.problem_dir)])
def write_parent(self) -> list:
"""The parent's files under parent/ in the work dir; the list of their paths."""
sol = self.archive.solution(self.parent_id) if self.parent_id else None
if not sol:
return []
paths = []
for s in sol.get("sources") or []:
rel = os.path.normpath(str(s.get("path") or ""))
if rel.startswith("..") or os.path.isabs(rel):
continue
p = os.path.join(self.workdir, "parent", rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
f.write(str(s.get("content") or ""))
paths.append(os.path.join("parent", rel))
with open(os.path.join(self.workdir, "parent", "solution.json"), "w", encoding="utf-8") as f:
json.dump(sol, f)
return paths + [os.path.join("parent", "solution.json")]
def parent_result(self) -> dict:
r = self.archive.get(self.parent_id) if self.parent_id else None
return {k: r.get(k) for k in ("cand_id", "reward", "sol_score", "t_k_ms_mean")} if r else {}
def evaluate(self, sol, text, path, notes):
"""Time it on the harness, score it, run the precision check, store it with its parent."""
d = self.scratch("eval")
res = harness.evaluate(self.problem_dir, path, d,
env=native_code.guard_env(None, sol, os.path.join(d, "site")),
config_path=self.cfg["harness"].get("bench_config"), **self.kw())
rows = res.get("rows") or []
res["reward"], res["reward_basis"] = (score.reward(rows, self.anchors) if res["correct"]
else (None, None))
res["sol_score"] = score.problem_score(rows, self.anchors)
res["flags"] = list(res.get("flags") or []) + score.flags(rows, self.anchors)
exempt = self.board in (self.cfg["checks"].get("precision_exempt_boards") or ())
prec = precision.check(sol, self.defn, exempt=exempt)
cid = self.archive.record(
text, res, self.parent_id, language=",".join((sol.get("spec") or {}).get("languages") or []),
direction=self.direction, notes=str(notes or "")[:4000], precision=prec["verdict"],
key=harness.solution_key(sol))
return cid, res, prec
def make_tools(c, tool) -> list:
"""The child's GPU tools. Their descriptions are prompt slots too (not released)."""
pdir = c.cfg["prompts"].get("prompt_dir")
def desc(name):
return load_prompt("tool_" + name, pdir)
@tool("compile_check", desc("compile_check"), {"solution_path": str})
async def compile_check(args):
sol, _, path, err = c.solution(args)
if err:
return tool_result({"error": err})
d = c.scratch("compile")
res = await asyncio.to_thread(
harness.evaluate, c.problem_dir, path, d, workload_path=c.one_workload(d),
config_path=harness.quick_config(d),
env=native_code.guard_env(None, sol, os.path.join(d, "site")), **c.kw())
return tool_result(_brief(res))
@tool("evaluate_kernel", desc("evaluate_kernel"), {"solution_path": str, "notes": str})
async def evaluate_kernel(args):
sol, text, path, err = c.solution(args)
if err:
return tool_result({"error": err})
if c.cfg["checks"].get("native_code") == "refuse":
v = native_code.check(sol) # before any GPU time
if v["verdict"] == "violation":
return tool_result({"refused": "native_code", "findings": v["findings"]})
earlier = c.archive.find_key(harness.solution_key(sol))
if earlier: # unchanged code is not timed again
return tool_result({"unchanged": True, **{k: earlier.get(k) for k in (
"cand_id", "correct", "reward", "sol_score", "t_k_ms_mean")}})
cid, res, prec = await asyncio.to_thread(c.evaluate, sol, text, path, args.get("notes"))
c.n_evals += 1
c.n_candidates += int(bool(res.get("correct")))
out = dict(_brief(res), cand_id=cid, reward=res["reward"], sol_score=res["sol_score"],
precision=prec["verdict"], precision_findings=prec["findings"],
candidates=c.n_candidates, max_candidates=c.max_candidates)
out["stop"] = c.n_candidates >= c.max_candidates
return tool_result(out)
@tool("profile_kernel", desc("profile_kernel"), {"solution_path": str})
async def profile_kernel(args):
sol, _, path, err = c.solution(args)
if err or shutil.which("ncu") is None:
return tool_result({"error": err or "ncu_not_found"})
d = c.scratch("profile")
env = harness.site_env(None, [sanitizer.NO_TIMING_SNIPPET], os.path.join(d, "site"))
res = await asyncio.to_thread(
harness.evaluate, c.problem_dir, path, d, workload_path=c.one_workload(d),
config_path=harness.quick_config(d), env=env, prefix=NCU, **c.kw())
return tool_result({"status": [r.get("status") for r in res.get("rows") or []],
"ncu_csv_tail": (res.get("output") or "")[-6000:]})
@tool("check_robustness", desc("check_robustness"), {"solution_path": str})
async def check_robustness(args):
sol, _, path, err = c.solution(args)
if err:
return tool_result({"error": err})
res = await asyncio.to_thread(
robustness.check, c.problem_dir, path, c.scratch("robustness"),
n_shapes=int(c.cfg["checks"]["robustness_shapes"]), **c.kw())
row = c.archive.find_key(harness.solution_key(sol))
if row:
c.archive.add_check(row["cand_id"], "robustness", res["verdict"])
return tool_result(res)
@tool("query_history", desc("query_history"), {"sql": str})
async def query_history(args):
return tool_result(await asyncio.to_thread(c.archive.query, str(args.get("sql") or "")))
@tool("get_solution", desc("get_solution"), {"cand_id": str})
async def get_solution(args):
cid = str(args.get("cand_id") or "")
sol = c.archive.solution(cid) if is_cand_id(cid) else None
if sol is None:
return tool_result({"error": "unknown_cand_id"})
name = "cand-%s.json" % cid
with open(os.path.join(c.workdir, name), "w", encoding="utf-8") as f:
json.dump(sol, f)
return tool_result({"cand_id": cid, "solution_path": name})
return [compile_check, evaluate_kernel, profile_kernel, check_robustness, query_history,
get_solution]
def _record(msg) -> dict:
"""A short transcript record of one SDK message: text, tool calls, the final result."""
rec = {"type": type(msg).__name__}
blocks = getattr(msg, "content", None)
if isinstance(blocks, list):
rec["blocks"] = [{"text": str(b.text)[:2000]} if hasattr(b, "text") else
{"tool": b.name, "input": str(getattr(b, "input", ""))[:500]}
if hasattr(b, "name") else {"block": type(b).__name__} for b in blocks]
for k in ("result", "num_turns", "total_cost_usd", "is_error"):
if getattr(msg, k, None) is not None:
rec[k] = str(getattr(msg, k))[:2000]
return rec
async def run_child(cfg, archive, parent_id, direction, gpu_id, slot) -> dict:
"""One child session on one GPU slot: {"candidates": n, "evals": n} when it ends."""
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, create_sdk_mcp_server, tool
c, log = Child(cfg, archive, parent_id, direction, gpu_id, slot), []
pdir = cfg["prompts"].get("prompt_dir")
try:
files = c.write_parent()
server = create_sdk_mcp_server(name="kernel", version="1.0.0", tools=make_tools(c, tool))
options = ClaudeAgentOptions(
system_prompt=load_prompt("child", pdir), model=cfg["model"]["id"],
mcp_servers={"kernel": server},
allowed_tools=["mcp__kernel__" + t for t in TOOLS] + list(FILE_TOOLS),
disallowed_tools=list(DENIED_TOOLS), permission_mode="bypassPermissions",
cwd=c.workdir, env=model_env(cfg), max_turns=int(cfg["model"]["child_max_turns"]))
task = load_prompt("child_task", pdir, problem_dir=os.path.abspath(c.problem_dir),
parent_id=parent_id or "", parent_files=json.dumps(files),
parent_result=json.dumps(c.parent_result()), direction=direction or "")
async with ClaudeSDKClient(options=options) as client:
await client.query(task)
async for msg in client.receive_response():
log.append(_record(msg))
finally:
archive.save_session(os.path.basename(c.workdir), log)
shutil.rmtree(c.workdir, ignore_errors=True)
return {"candidates": c.n_candidates, "evals": c.n_evals}