spiderpilot89's picture
Update
95c262f verified
Raw History Blame Contribute Delete
14.8 kB
#!/usr/bin/env python3
"""Run and grade one rack-twin task. Standard library only.
python3 run_task.py prompt rack-train-00 the text an agent is given
python3 run_task.py prepare rack-train-00 WORKSPACE copy the starter rack_twin/, SPEC_SHEET.md and PROMPT.md
python3 run_task.py serve rack-train-00 --log probes.json the agent's tools as an MCP stdio server (budgets enforced)
python3 run_task.py grade rack-train-00 WORKSPACE/rack_twin --probes probes.json
python3 run_task.py grade rack-train-00 rack_twin --standard-probe
`grade` runs compute_unit_trim on racks A, B and C and grades every returned trim on the compiled 8-corner plant.
Any specimen file works in place of the id, changed or new ones included: nothing is pinned to these 40."""
import argparse
import hashlib
import json
import math
import os
import shutil
import subprocess
import sys
import tempfile
sys.dont_write_bytecode = True
import bench
import ztp_bin
ROOT, PASS_RATIO = bench.ROOT, 0.92
LIMIT_BOUNDS = {"sustained_compute_target_w": (3000.0, 22000.0), "pump_speed_rpm": (900.0, 5600.0), "supply_pressure_pa": (3.0e5, 2.4e6),
"mount_active_kp": (0.0, 25000.0)}
CTRL_BOUNDS = {"throttle_onset_measured_k": (315.0, 370.0), "throttle_gain_w_per_k": (0.0, 1200.0), "min_compute_fraction": (0.35, 1.0),
"bess_emergency_current_a": (0.5, 14.0), "surge_flow_multiplier": (1.0, 1.5)}
LOCKED = ("pipe_length_m", "pipe_diameter_m", "nominal_flow_m3_s", "valve_ramp_s", "fin_area_multiplier", "tim_thickness_um", "clamp_preload_mpa",
"pll_bandwidth_per_s", "governor_droop", "bess_parallel_strings", "parallel_feeder_legs", "mount_natural_freq_hz", "mount_damping_ratio")
INTEGERS = ("bess_parallel_strings", "parallel_feeder_legs")
PROMPT = """You are the commissioning engineer for a lot of three liquid-cooled AI compute racks of one SKU. Racks A, B and C were built and \
factory-tested together and share one factory record; on site each has drifted in its own way.
The lot's plant twin and commissioning synthesizer is rack_twin/ (Python, standard library only). \
rack_twin.compute_unit_trim(unit_spec, probe_log) returns one rack's operating limits and protection controller. Its unit tests pass, but the \
code holds physics and coupling defects: commissioned with it as shipped, racks are not safe. SPEC_SHEET.md is the complete datasheet.
1. Two stateful probes (service_probe, at most 2) on rack A. Each changes the rack, and the changed rack is graded. The grader replays the same \
requests on racks B and C and hands each rack's own readings to your code.
2. Component solvers only (solve, at most 24): die_coldplate_fe, cdu_loop_moc, rack_power_pll, chassis_mount_duffing. There is no whole-plant \
simulator. Use them to find where the twin disagrees with the real components.
3. Repair rack_twin/ in place. The grader runs compute_unit_trim once per rack, offline, with a 30 s CPU limit.
4. A pass needs all 24 corners (8 per rack) safe and a mean of min(1, net PPA / reference PPA) of at least 0.92 over the three racks.
"""
RUNNER = r'''
import json, os, sys
sys.dont_write_bytecode = True
ROOT = os.path.dirname(os.path.abspath(__file__))
OK = tuple(os.path.realpath(p) + os.sep for p in {ROOT, sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix} if p)
DENY = ("socket.", "subprocess.", "ctypes.", "os.exec", "os.spawn", "os.posix_spawn", "os.fork", "os.system", "os.kill", "os.remove", "os.rename",
"os.rmdir", "os.mkdir", "os.chmod", "os.chown", "os.link", "os.symlink", "os.truncate", "shutil.", "pty.", "mmap.", "urllib.", "http.")
def hook(event, args):
if event.startswith(DENY): raise PermissionError("refused: " + event)
if event == "open":
path, mode, flags = (list(args) + [None] * 3)[:3]
if isinstance(path, int): return
if (mode and any(c in str(mode) for c in "wax+")) or (isinstance(flags, int) and flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT)): raise PermissionError("refused: write")
if path is not None and not os.path.realpath(os.fsdecode(path)).startswith(OK): raise PermissionError("refused: read outside")
elif event in ("os.listdir", "os.scandir") and args and isinstance(args[0], (str, bytes)) and not (os.path.realpath(os.fsdecode(args[0])) + os.sep).startswith(OK):
raise PermissionError("refused: listing outside")
with open(os.path.join(ROOT, "input.json")) as f: INPUT = json.load(f)
sys.path.insert(0, ROOT); sys.addaudithook(hook)
from rack_twin import compute_unit_trim
text = json.dumps(compute_unit_trim(INPUT["unit_spec"], INPUT["probe_log"]), allow_nan=False)
sys.stdout.write("\n@@TRIM@@\n" + text + "\n")
'''
def collect(folder):
"""Relative path -> bytes of every .py and .json file; links and special files are refused."""
if os.path.islink(folder) or not os.path.isdir(folder):
raise ValueError("%s is not a real folder" % folder)
files = {}
for root, dirs, names in os.walk(folder):
dirs[:] = [d for d in dirs if d != "__pycache__"]
for n in dirs + names:
p = os.path.join(root, n)
if os.path.islink(p) or not (os.path.isdir(p) or os.path.isfile(p)):
raise ValueError("link or special file in rack_twin: %s" % n)
for n in names:
if n.endswith((".py", ".json")):
p = os.path.join(root, n)
with open(p, "rb") as f:
files[os.path.relpath(p, folder)] = f.read(512 * 1024 + 1)
if len(files) > 64 or sum(map(len, files.values())) > 2 << 20 or "__init__.py" not in files:
raise ValueError("rack_twin needs __init__.py, at most 64 files and 2 MiB")
return files
WORKER_CPU_S = int(os.environ.get("ZTP_WORKER_CPU_S", "30"))
WORKER_AS = int(os.environ.get("ZTP_WORKER_AS_MB", "256")) << 20 # raise it under amd64 emulation, see README
def _limits():
import resource
os.setsid()
resource.setrlimit(resource.RLIMIT_CPU, (WORKER_CPU_S, WORKER_CPU_S))
resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
try:
resource.setrlimit(resource.RLIMIT_AS, (WORKER_AS, WORKER_AS))
except (ValueError, OSError):
pass
if os.geteuid() == 0:
os.setgroups([])
os.setgid(65534)
os.setuid(65534)
def run_package(files, unit_spec, probe_log):
"""compute_unit_trim in its own process: (trim, None) or (None, why)."""
base = tempfile.mkdtemp(prefix="rack_twin_")
try:
os.chmod(base, 0o755)
for rel, data in files.items():
dst = os.path.join(base, "rack_twin", rel)
os.makedirs(os.path.dirname(dst), mode=0o755, exist_ok=True)
with open(dst, "wb") as f:
f.write(data)
with open(os.path.join(base, "input.json"), "w") as f:
json.dump({"unit_spec": unit_spec, "probe_log": probe_log}, f)
with open(os.path.join(base, "runner.py"), "w") as f:
f.write(RUNNER)
try:
p = subprocess.run([sys.executable, "-I", "-S", os.path.join(base, "runner.py")], cwd=base, capture_output=True, timeout=3 * WORKER_CPU_S,
env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"}, preexec_fn=_limits)
except subprocess.TimeoutExpired:
return None, "compute_unit_trim passed the %d s wall limit" % (3 * WORKER_CPU_S)
text = p.stdout.decode("utf-8", "replace")
if p.returncode or "\n@@TRIM@@\n" not in text or len(text) > 256 * 1024:
last = p.stderr.decode("utf-8", "replace").strip().splitlines()[-1:]
return None, "compute_unit_trim did not return (%s)" % (last[0][:160] if last else "exit %s" % p.returncode)
return json.loads(text.rsplit("\n@@TRIM@@\n", 1)[1]), None
finally:
shutil.rmtree(base, ignore_errors=True)
def check_trim(t):
if not isinstance(t, dict) or set(t) - {"task_id", "limits", "controller"} or t.get("task_id") != "rack-twin":
return "the trim must be {task_id: 'rack-twin', limits, controller}"
for name, bounds in (("limits", LIMIT_BOUNDS), ("controller", CTRL_BOUNDS)):
b = t.get(name)
if not isinstance(b, dict) or set(b) != set(bounds):
return "%s must hold exactly %s" % (name, sorted(bounds))
for k, (lo, hi) in bounds.items():
v = b[k]
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not lo <= v <= hi:
return "%s.%s=%r outside [%s, %s]" % (name, k, v, lo, hi)
return None
def grade_unit(spec, unit, memory, trim):
inc = spec["public"]["incumbent_design"]
design = {k: int(inc[k]) if k in INTEGERS else float(inc[k]) for k in LOCKED}
design.update({k: float(v) for k, v in trim["limits"].items()})
return ztp_bin.run("ztp_foundry_verifier", "grade", {"hidden": unit["hidden"], "memory": memory, "design": design,
"controller": {k: float(v) for k, v in trim["controller"].items()}, "reference_ppa_ceiling_w": unit["reference_ppa_w"]})
def _finish(rows):
safe = all(r["safe"] for r in rows)
ratio = sum(r["ratio"] for r in rows) / len(rows)
ok = safe and ratio >= PASS_RATIO
return {"passed": ok, "reward": int(ok), "shaped": 1.0 if ok else sum(r["shaped"] for r in rows) / len(rows), "all_safe": safe, "mean_ratio": ratio,
"corners_passed": sum(r["corners_passed"] for r in rows), "total_corners": 8 * len(rows),
"suite_sha384": hashlib.sha384(json.dumps([r["suite_seal_sha384"] for r in rows]).encode()).hexdigest(), "racks": rows}
def _row(spec, unit, memory, trim, why):
if why:
return {"rack": unit["unit_id"], "safe": False, "ratio": 0.0, "shaped": 0.10, "corners_passed": 0, "suite_seal_sha384": None, "error": why}
rep = grade_unit(spec, unit, memory, trim)
ppa = float(rep["net_ppa_efficiency_w"])
return {"rack": unit["unit_id"], "safe": bool(rep["all_corners_safe"]), "corners_passed": int(rep["corners_passed"]), "net_ppa_w": ppa,
"ratio": min(1.0, ppa / max(unit["reference_ppa_w"], 1.0)), "shaped": float(rep["shaped_score"]), "suite_seal_sha384": rep["suite_seal_sha384"],
"trim": trim, "violations": ["%s: %s" % (c["corner_id"], ", ".join(c["violations"])) for c in rep["corners"] if not c["safe"]]}
def grade_trims(spec, requests, trims):
"""Grade given trims (rack label -> trim) after the probe requests have been replayed on each rack."""
return _finish([_row(spec, u, bench.replay(u, requests)[1], trims[u["unit_id"]], check_trim(trims[u["unit_id"]])) for u in spec["units"]])
def grade_package(spec, folder, requests):
"""Grade a rack_twin folder: run it on every rack's own probe log, then grade each trim on the compiled plant."""
files, rows = collect(folder), []
for u in spec["units"]:
log, mem = bench.replay(u, requests)
trim, why = run_package(files, dict(spec["public"], unit_id=u["unit_id"]), log)
rows.append(_row(spec, u, mem, trim, why or check_trim(trim)))
return _finish(rows)
def prepare(workspace):
os.makedirs(workspace, exist_ok=True)
shutil.copytree(os.path.join(ROOT, "rack_twin"), os.path.join(workspace, "rack_twin"), ignore=shutil.ignore_patterns("__pycache__"), dirs_exist_ok=True)
shutil.copyfile(os.path.join(ROOT, "SPEC_SHEET.md"), os.path.join(workspace, "SPEC_SHEET.md"))
with open(os.path.join(workspace, "PROMPT.md"), "w") as f:
f.write(PROMPT)
def serve(spec, log_path):
"""The agent's tools over MCP stdio. Probe requests are kept in log_path for `grade --probes`."""
b = bench.Bench(spec)
num = {"type": "number"}
tools = [("describe_plant", "The lot's factory record, shared by racks A, B and C.", {}, []),
("service_probe", "One stateful probe on rack A (at most 2; never resets).", {k: dict(num, minimum=lo, maximum=hi) for k, (lo, hi) in bench.PROBE_BOUNDS.items()}, list(bench.PROBE_BOUNDS)),
("solve", "One component solve (at most 24).", {"solver": {"type": "string"}, "parameters": {"type": "object"}}, ["solver", "parameters"]),
("list_solvers", "The component solvers.", {}, []), ("describe_solver", "Inputs and outputs of one solver.", {"solver": {"type": "string"}}, ["solver"]),
("budget_status", "What is left.", {}, [])]
for line in sys.stdin:
m = json.loads(line)
if "id" not in m:
continue
method, params, out = m.get("method"), m.get("params") or {}, {}
if method == "initialize":
out = {"protocolVersion": params.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}}, "serverInfo": {"name": "rack-twin-bench", "version": "1"}}
elif method == "tools/list":
out = {"tools": [{"name": n, "description": d, "inputSchema": {"type": "object", "properties": p, "required": r, "additionalProperties": False}} for n, d, p, r in tools]}
elif method == "tools/call":
try:
if params.get("name") not in [t[0] for t in tools]:
raise bench.Refused("no such tool")
text, err = json.dumps(getattr(b, params["name"])(**(params.get("arguments") or {}))), False
except (bench.Refused, RuntimeError, TypeError) as e:
text, err = str(e), True
with open(log_path, "w") as f:
json.dump(b.requests, f)
out = {"content": [{"type": "text", "text": text}], "isError": err}
print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": out}), flush=True)
b.close()
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("command", choices=("prompt", "prepare", "serve", "grade"))
ap.add_argument("specimen")
ap.add_argument("folder", nargs="?")
ap.add_argument("--probes", help="JSON list of the probe requests made (from serve --log)")
ap.add_argument("--standard-probe", action="store_true", help="grade after the twin's own standard probe")
ap.add_argument("--log", default="probes.json")
a = ap.parse_args()
spec = bench.load(a.specimen)
if a.command == "prompt":
print(PROMPT)
elif a.command == "prepare":
prepare(a.folder)
elif a.command == "serve":
serve(spec, a.log)
else:
reqs = json.load(open(a.probes)) if a.probes else (list(bench.STANDARD_PROBES) if a.standard_probe else [])
r = grade_package(spec, a.folder, reqs[:bench.MAX_SERVICE_PROBES])
print(json.dumps({k: v for k, v in r.items() if k != "racks"} | {"racks": [{k: x[k] for k in x if k != "trim"} for x in r["racks"]]}, indent=1))
if __name__ == "__main__":
main()