Datasets:
Download kernel_bench/phase_runner.py from code-roamer/gpu-kernel-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/phase_runner.py
- Command line
-
hf download hf://datasets/code-roamer/gpu-kernel-benchmark/kernel_bench/phase_runner.py
-
curl -L -o phase_runner.py https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/phase_runner.py
12.2 kB
| """Run one two-phase v0.7 task on its designated GPU profile.""" | |
| from contextlib import ExitStack | |
| import datetime as dt | |
| import fcntl | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import signal | |
| import subprocess | |
| import sys | |
| from .kernel_v07 import CSA, MOE, ROOT | |
| from .metrics import geometric_mean, paired_summary | |
| class GraderFailure(RuntimeError): | |
| pass | |
| def phase_stats(raw): | |
| samples = raw.get("native_us", raw.get("baseline_us")) | |
| if len(samples) != 9 or len(raw["candidate_us"]) != 9: | |
| raise ValueError("Expected nine paired timing samples") | |
| result = paired_summary(samples, raw["candidate_us"]) | |
| if "split_us" in raw: | |
| result["split_diagnostic"] = paired_summary(raw["split_us"], raw["candidate_us"]) | |
| result["candidate_kernel"] = raw["candidate_kernel"] | |
| result["native_api_reused"] = raw.get("native_api_reused", False) | |
| return result | |
| def worker_error(lines): | |
| # torchrun appends an elastic summary after the real per-rank exceptions. | |
| ranks = {} | |
| for line in lines: | |
| match = re.match(r"^\[rank(\d+)\]: ?(.*)$", line) | |
| if match: | |
| rank, body = match.groups() | |
| if body.startswith("Traceback ("): | |
| ranks.setdefault(rank, []).append(body) | |
| elif rank in ranks: | |
| ranks[rank].append(body) | |
| for rank, trace in ranks.items(): | |
| for i, line in enumerate(trace): | |
| if re.match(r"^(?:[\w.]+(?:Error|Exception)|KeyboardInterrupt)(?:$|:)", line): | |
| frames = [m.group(1) for frame in trace[:i] | |
| if (m := re.search(r'/submission\.py", (line \d+, in .+)', frame))] | |
| location = f"submission.py {frames[-1]}: " if frames else "" | |
| details = [] | |
| for detail in trace[i:i+16]: | |
| if detail.startswith(("During handling of", "The above exception", "Traceback (")): | |
| break | |
| details.append(detail) | |
| return f"[rank{rank}] {location}" + "\n".join(details).strip()[:4500] | |
| return "\n".join(lines[-28:])[-4500:] | |
| def run_process(cmd, log, env, timeout): | |
| with log.open("w") as stream: | |
| proc = subprocess.Popen(cmd, stdout=stream, stderr=subprocess.STDOUT, env=env, start_new_session=True) | |
| try: | |
| proc.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| # torchrun workers may create their own sessions outside the launcher's group. | |
| table = subprocess.check_output(["ps", "-e", "-o", "pid=,ppid="], text=True) | |
| children = {} | |
| for row in table.splitlines(): | |
| pid, parent = map(int, row.split()) | |
| children.setdefault(parent, []).append(pid) | |
| descendants = [proc.pid] | |
| for parent in descendants: | |
| descendants.extend(children.get(parent, [])) | |
| for pid in reversed(descendants): | |
| try: | |
| os.kill(pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| try: | |
| os.killpg(proc.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| proc.wait() | |
| raise RuntimeError(f"worker exceeded {timeout}s") from None | |
| lines = log.read_text(errors="replace").splitlines() | |
| if proc.returncode == 0: | |
| for line in reversed(lines): | |
| if line.startswith("{"): | |
| result = json.loads(line) | |
| if "candidate_us" in result: | |
| return result | |
| raise RuntimeError(worker_error(lines) or f"worker exit {proc.returncode}") | |
| def evaluate_case(case, candidate, seed, out, env, timeout, public=False): | |
| task, regime = case["task"], case["regime"] | |
| folder = ROOT / "candidates" / task | |
| cmd = [sys.executable] | |
| common = ["--seed", str(seed)] | |
| capacity = ["--capacity", str(case["capacity"])] | |
| if task == MOE: | |
| cmd += ["-m", "torch.distributed.run", "--standalone", "--nproc-per-node=8"] | |
| forward = ["--tokens", str(case["capacity"]), "--shared", "2" if regime == "t512_s2" else "1"] | |
| else: | |
| forward = ["--case", regime, *capacity, "--baseline", folder / "triton_baseline.py"] | |
| if public and task == MOE: | |
| forward.append("--public-feedback") | |
| backward = ["--case", regime, *capacity, "--baseline", "public"] | |
| runs = [("forward", "check.py", forward), ("backward", "check_backward.py", backward)] | |
| if task == MOE and regime == "t32_s1": | |
| runs.extend((name, "check_backward.py", ["--case", name, "--baseline", "public"]) | |
| for name in ("masked", "shared_only")) | |
| phases = {} | |
| errors = {} | |
| for phase, script, options in runs: | |
| def invoke(module, label): | |
| args = [*cmd, folder / script, "--candidate", module, *options, *common] | |
| if task == CSA and phase == "backward": | |
| args += ["--forward", module] | |
| return run_process(args, out / f"{case['id']}-{phase}-{label}.log", env, timeout) | |
| try: | |
| raw = invoke(candidate, "submission") | |
| except (RuntimeError, ValueError) as error: | |
| if candidate == folder / "control.py": | |
| raise GraderFailure(f"{phase} control failed: {error}") from error | |
| try: | |
| invoke(folder / "control.py", "control") | |
| except (RuntimeError, ValueError) as control_error: | |
| raise GraderFailure(f"{phase} control failed: {control_error}") from control_error | |
| if public: | |
| errors[phase] = str(error) | |
| # CSA2 backward consumes the selection from the submitted forward. | |
| if task == CSA and phase == "forward": | |
| errors["backward"] = "Not run: CSA2 backward needs saved indices from the submitted forward." | |
| break | |
| continue | |
| raise ValueError(f"{phase} failed: {error}") from error | |
| if phase in ("forward", "backward"): | |
| phases[phase] = phase_stats(raw) | |
| if "cross_rank_routes" in raw: | |
| phases[phase].update({key: raw[key] for key in ("valid_routes", "cross_rank_routes", "cross_rank_pairs")}) | |
| else: | |
| phases.setdefault("extra_backward_checks", {})[phase] = "passed" | |
| if errors: | |
| phases["phase_errors"] = errors | |
| return phases | |
| def summarize(rows): | |
| passed = [r for r in rows if r["status"] == "passed"] | |
| task = rows[0]["task"] | |
| item = dict(cases=len(rows), passed_cases=len(passed), all_correct=len(rows) == len(passed)) | |
| if item["all_correct"]: | |
| for phase in ("forward", "backward", "kernel"): | |
| item[phase + "_speedup"] = geometric_mean([r[phase]["speedup"] for r in rows]) | |
| item[phase + "_lower_bound"] = geometric_mean([r[phase]["speedup_ci95"][0] for r in rows]) | |
| item["stable"] = all(max(r[p]["baseline_cv"], r[p]["candidate_cv"]) <= .1 | |
| for r in rows for p in ("forward", "backward")) | |
| item["worst_case_kernel_speedup"] = min(r["kernel"]["speedup"] for r in rows) | |
| return dict(tasks={task: item}, task_count=1, fully_correct_tasks=int(item["all_correct"])) | |
| def check_devices(task, devices, infos): | |
| if len(set(devices)) != len(devices) or len({g["uuid"] for g in infos}) != len(devices): | |
| raise GraderFailure("Duplicate device in allocation") | |
| if task == CSA and (len(devices) != 1 or "H100" not in infos[0]["name"]): | |
| raise GraderFailure("CSA2 requires one H100") | |
| if task == MOE and (len(devices) != 8 or any("B200" not in g["name"] for g in infos)): | |
| raise GraderFailure("Mega MoE requires eight local B200 GPUs (EP=8)") | |
| def run(args, cases, suite, candidate, out): | |
| from .__main__ import gpu_info, gpu_processes, write_json | |
| task = cases[0]["task"] | |
| devices = str(args.device).split(",") | |
| out.mkdir(parents=True, exist_ok=False) | |
| result = dict(schema_version=2, protocol_version=suite["protocol_version"], suite_id=suite["suite_id"], | |
| source_sha256=hashlib.sha256(candidate.read_bytes()).hexdigest(), | |
| suite_sha256=hashlib.sha256(Path(args.suite).read_bytes()).hexdigest(), | |
| grader_sha256={str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() | |
| for p in [Path(__file__), ROOT / "metrics.py", ROOT / "candidates/backward_eval.py", | |
| *sorted((ROOT / "candidates" / task).glob("*.py"))]}, | |
| config=dict(input_seed=args.seed, rounds=9, phases=["forward", "backward"], | |
| timeout_seconds_per_phase=args.timeout), | |
| started_at=dt.datetime.now(dt.timezone.utc).isoformat(), cases=[]) | |
| rows = result["cases"] | |
| try: | |
| infos = [gpu_info(d) for d in devices] | |
| result["gpus"] = infos | |
| import importlib.metadata as metadata | |
| result["runtime"] = {"python": sys.version.split()[0]} | |
| for package in ("torch", "triton", "deep_gemm"): | |
| try: | |
| result["runtime"][package] = metadata.version(package) | |
| except metadata.PackageNotFoundError: | |
| pass | |
| check_devices(task, devices, infos) | |
| if task == MOE and "5081f85" not in result["runtime"].get("deep_gemm", ""): | |
| raise GraderFailure("Install DeepGEMM from the pinned 5081f851 source with matching build metadata") | |
| if args.bwrap: | |
| raise GraderFailure("The installed single-GPU bubblewrap profile does not support the phase grader") | |
| env = dict(os.environ, CUDA_VISIBLE_DEVICES=",".join(g["uuid"] for g in infos), OMP_NUM_THREADS="1", | |
| TORCHINDUCTOR_COMPILE_THREADS="1") | |
| with ExitStack() as stack: | |
| for gpu in sorted(infos, key=lambda g: g["uuid"]): | |
| lock = stack.enter_context(open("/tmp/kernelbench-" + gpu["uuid"] + ".lock", "a")) | |
| fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| if gpu_processes(gpu["uuid"]): | |
| raise GraderFailure("GPU has active compute processes: " + gpu["uuid"]) | |
| for case in cases: | |
| row = dict(id=case["id"], task=task) | |
| try: | |
| phases = evaluate_case(case, candidate, args.seed, out, env, args.timeout, | |
| public=suite.get("split") == "public" or suite["suite_id"] == "kernel-v07-public") | |
| if "phase_errors" in phases: | |
| row.update(**phases) | |
| raise ValueError("Failed phases: " + ", ".join(phases["phase_errors"])) | |
| f, b = phases["forward"], phases["backward"] | |
| # Retain raw measurements while excluding positive noise from direct reference calls. | |
| forward_lower = f["speedup_ci95"][0] | |
| if f.get("native_api_reused"): | |
| forward_lower = min(1., forward_lower) | |
| row.update(status="passed", **phases, kernel=dict( | |
| speedup=geometric_mean([f["speedup"], b["speedup"]]), | |
| speedup_ci95=[geometric_mean([forward_lower, b["speedup_ci95"][0]]), | |
| geometric_mean([f["speedup_ci95"][1], b["speedup_ci95"][1]])])) | |
| except ValueError as exc: | |
| row.update(status="error", error=str(exc)) | |
| rows.append(row) | |
| print(row["id"], row["status"], flush=True) | |
| result["summary"] = summarize(rows) | |
| write_json(out / "results.json", result) | |
| except (GraderFailure, OSError, RuntimeError) as exc: | |
| rows.extend(dict(id=c["id"], task=task, status="error", error="RuntimeError: Baseline failed " + str(exc)) | |
| for c in cases[len(rows):]) | |
| result["summary"] = summarize(rows) | |
| result["finished_at"] = dt.datetime.now(dt.timezone.utc).isoformat() | |
| write_json(out / "results.json", result) | |
| return 0 if all(r["status"] == "passed" for r in rows) else 1 | |