KernelBench-M / pipeline /eval_kernel.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw
History Blame Contribute Delete
6.48 kB
"""Evaluate all variants (correct + mutants) of one problem against all test suites.
Kill criterion follows KernelBench eval: runtime error, shape mismatch, or
!torch.allclose(ref, out, atol=1e-2, rtol=1e-2) => killed.
Writes JSONL journal (one line per variant x suite). Resumable: already-journaled
(variant, suite) pairs are skipped; a START line without a matching RESULT line
(previous process died there) is recorded as killed:process_crash, and all
remaining suites of that variant are skipped.
Usage: python3 eval_kernel.py <problem> <journal_path>
"""
import importlib.util
import json
import os
import sys
import torch
import kernels_def as K
ATOL = RTOL = 1e-2
def load_ref_model(problem):
p = K.PROBLEMS[problem]
spec = importlib.util.spec_from_file_location(f"kb_{problem}", p["kb_file"])
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
init = mod.get_init_inputs()
return mod.Model(*init), init
def build_ext(problem, variant_id, cuda_src):
from torch.utils.cpp_extension import load_inline
p = K.PROBLEMS[problem]
return load_inline(
name=f"{problem}_{variant_id}",
cpp_sources=p["cpp"],
cuda_sources=cuda_src,
functions=[p["func"]],
verbose=False,
)
def compare(ref, out):
if not isinstance(out, torch.Tensor):
return dict(status="killed", reason="not_a_tensor")
if out.shape != ref.shape:
return dict(status="killed", reason="shape_mismatch",
detail=f"{tuple(out.shape)} vs {tuple(ref.shape)}")
ok = torch.allclose(ref, out, atol=ATOL, rtol=RTOL)
if ok:
return dict(status="survived")
diff = (ref - out).abs()
finite = torch.isfinite(out).all().item()
return dict(status="killed", reason="value_mismatch",
max_diff=float(diff.nan_to_num(nan=float("inf")).max()),
out_finite=bool(finite))
def main():
problem, journal_path = sys.argv[1], sys.argv[2]
p = K.PROBLEMS[problem]
done = {} # (variant, suite) -> True
crashed = set() # variants that crashed a previous process
pending_start = None
if os.path.exists(journal_path):
for line in open(journal_path):
rec = json.loads(line)
if rec["type"] == "START":
pending_start = (rec["variant"], rec["suite"])
elif rec["type"] == "RESULT":
done[(rec["variant"], rec["suite"])] = True
pending_start = None
journal = open(journal_path, "a")
def emit(rec):
journal.write(json.dumps(rec) + "\n")
journal.flush()
os.fsync(journal.fileno())
# a START without RESULT means the previous process died on that (variant, suite)
if pending_start is not None:
v, s = pending_start
emit(dict(type="RESULT", variant=v, suite=s, trial=-1,
status="killed", reason="process_crash"))
done[(v, s)] = True
crashed.add(v)
ref_model, _ = load_ref_model(problem)
ref_model = ref_model.cuda().eval()
suites = p["suites"]()
# cache reference outputs on CPU: (suite, trial) -> ref_out
ref_cache = {}
def ref_out_for(suite_name, builder, trial):
key = (suite_name, trial)
if key not in ref_cache:
inputs = builder(trial)
with torch.no_grad():
gpu_in = [t.cuda() for t in inputs]
ref_cache[key] = ref_model(*gpu_in).cpu()
del gpu_in
torch.cuda.empty_cache()
return ref_cache[key]
for variant_id, cuda_src in K.all_variants(problem):
if variant_id in crashed:
for suite_name, _, _ in suites:
if (variant_id, suite_name) not in done:
emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
status="skipped_after_crash"))
continue
try:
ext = build_ext(problem, variant_id, cuda_src)
except Exception as e:
for suite_name, _, _ in suites:
if (variant_id, suite_name) not in done:
emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
status="killed", reason="compile_error", detail=str(e)[:300]))
continue
wrapper_cls = p["wrapper"]
if problem == "sum":
model_new = wrapper_cls(ext, 1)
else:
model_new = wrapper_cls(ext)
model_new = model_new.cuda().eval()
variant_dead = False
for suite_name, n_trials, builder in suites:
if (variant_id, suite_name) in done:
continue
if variant_dead:
emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
status="skipped_after_crash"))
continue
emit(dict(type="START", variant=variant_id, suite=suite_name))
result = dict(status="survived")
for trial in range(n_trials):
ref_out = ref_out_for(suite_name, builder, trial)
inputs = builder(trial)
try:
with torch.no_grad():
gpu_in = [t.cuda() for t in inputs]
out = model_new(*gpu_in)
torch.cuda.synchronize()
r = compare(ref_out.cuda(), out)
del gpu_in, out
torch.cuda.empty_cache()
except RuntimeError as e:
r = dict(status="killed", reason="runtime_error", detail=str(e)[:300])
if "CUDA" in str(e) or "cuda" in str(e):
# context may be poisoned; record and let the driver restart us
r["trial"] = trial
emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **r))
journal.close()
sys.exit(3)
if r["status"] == "killed":
r["trial"] = trial
result = r
break
if "trial" not in result:
result["trial"] = n_trials
emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **result))
emit(dict(type="DONE", problem=problem))
journal.close()
if __name__ == "__main__":
main()