KernelBench-M / pipeline /driver.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw History Blame Contribute Delete
4.45 kB
"""Orchestrates the mutation experiment on the GPU worker.
1. Pre-compiles all kernel variants in parallel (nvcc, cached by torch ext dir).
2. Runs eval_kernel.py per problem in a subprocess, respawning on crash
(crashing mutants are recorded as killed and skipped on resume).
3. Aggregates journals into results/summary.json and results/summary.md.
"""
import concurrent.futures as cf
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
RESULTS = os.path.join(HERE, "results")
os.makedirs(RESULTS, exist_ok=True)
sys.path.insert(0, HERE)
import kernels_def as K # noqa: E402
def precompile():
def build(job):
problem, variant_id, src = job
t0 = time.time()
try:
import eval_kernel
eval_kernel.build_ext(problem, variant_id, src)
return (problem, variant_id, "ok", time.time() - t0)
except Exception as e:
return (problem, variant_id, f"compile_error: {str(e)[:200]}", time.time() - t0)
jobs = [(prob, vid, src) for prob in K.PROBLEMS for vid, src in K.all_variants(prob)]
print(f"[driver] compiling {len(jobs)} variants ...", flush=True)
with cf.ThreadPoolExecutor(max_workers=5) as ex:
for prob, vid, status, dt in ex.map(build, jobs):
print(f"[compile] {prob}/{vid}: {status} ({dt:.0f}s)", flush=True)
def run_problem(problem):
journal = os.path.join(RESULTS, f"{problem}.jsonl")
for attempt in range(40):
proc = subprocess.run(
[sys.executable, os.path.join(HERE, "eval_kernel.py"), problem, journal],
timeout=7200)
if proc.returncode == 0:
print(f"[driver] {problem}: done", flush=True)
return
print(f"[driver] {problem}: process exited rc={proc.returncode}, respawning "
f"(attempt {attempt + 1})", flush=True)
print(f"[driver] {problem}: too many respawns, giving up", flush=True)
def aggregate():
summary = {}
for problem in K.PROBLEMS:
journal = os.path.join(RESULTS, f"{problem}.jsonl")
if not os.path.exists(journal):
continue
res = {}
for line in open(journal):
rec = json.loads(line)
if rec["type"] == "RESULT":
res[(rec["variant"], rec["suite"])] = rec
summary[problem] = {f"{v}|{s}": r for (v, s), r in res.items()}
with open(os.path.join(RESULTS, "summary.json"), "w") as f:
json.dump(summary, f, indent=1)
lines = ["# Mutation experiment results", ""]
for problem in K.PROBLEMS:
if problem not in summary:
continue
p = K.PROBLEMS[problem]
suites = [s for s, _, _ in p["suites"]()]
res = summary[problem]
lines.append(f"## {problem} ({os.path.basename(p['kb_file'])})")
lines.append("")
lines.append("| mutant | category | description | " + " | ".join(suites) + " |")
lines.append("|---" * (3 + len(suites)) + "|")
t0_survivors = []
for vid_info in [dict(id="correct", category="-", desc="correct implementation")] + p["mutants"]:
vid = vid_info["id"]
cells = []
for s in suites:
r = res.get(f"{vid}|{s}")
if r is None:
cells.append("?")
elif r["status"] == "survived":
cells.append("SURVIVED")
elif r["status"] == "skipped_after_crash":
cells.append("(skipped)")
else:
cells.append(f"killed:{r.get('reason', '?')}")
if vid != "correct" and res.get(f"{vid}|T0_original", {}).get("status") == "survived":
t0_survivors.append(vid)
lines.append(f"| {vid} | {vid_info['category']} | {vid_info['desc']} | " + " | ".join(cells) + " |")
n_mut = len(p["mutants"])
lines.append("")
lines.append(f"**T0 (original KernelBench inputs, 5 trials) survivors: "
f"{len(t0_survivors)}/{n_mut}: {', '.join(t0_survivors) or 'none'}**")
lines.append("")
with open(os.path.join(RESULTS, "summary.md"), "w") as f:
f.write("\n".join(lines))
print("[driver] summary written", flush=True)
if __name__ == "__main__":
precompile()
for problem in K.PROBLEMS:
run_problem(problem)
aggregate()
print("[driver] ALL DONE", flush=True)