import argparse import ctypes import datetime as dt import fcntl import hashlib import importlib.metadata import json import os from pathlib import Path import platform import signal import subprocess import sys import time import traceback import zipfile from .metrics import summarize from . import __version__, LEGACY_PROTOCOL from .main_h100 import validate_cases from .restricted import worker_command ROOT = Path(__file__).resolve().parent.parent def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") tmp.replace(path) def command(args): result = subprocess.run(args, text=True, capture_output=True, timeout=30) if result.returncode: raise RuntimeError(result.stderr.strip() or "Command failed: " + str(args)) return result.stdout.strip() def gpu_info(device): fields = "index,uuid,name,driver_version,memory.total,compute_mode,pstate,temperature.gpu,power.draw,power.limit,clocks.sm,clocks.mem" raw = command(["nvidia-smi", "-i", str(device), "--query-gpu=" + fields, "--format=csv,noheader,nounits"]) return dict(zip(fields.split(","), (x.strip() for x in raw.split(",")))) def gpu_processes(uuid): raw = command(["nvidia-smi", "-i", uuid, "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"]) return raw.splitlines() if raw else [] def source_snapshot(out, candidate, suite): sources = {} excluded = {"results", "private", "artifacts", "__pycache__", "releases"} for folder, directories, files in os.walk(ROOT / "kernel_bench"): directories[:] = sorted(name for name in directories if name not in excluded) for name in sorted(files): p = Path(folder) / name if p.is_file() and not name.startswith("._"): sources[str(p.relative_to(ROOT))] = p # Snapshot adjacent submission helpers too; exclude generated results and binary caches. for p in sorted(candidate.parent.iterdir()): if p.is_file() and p.suffix in {".py", ".cu", ".cpp", ".h", ".cuh"}: sources["submitted/" + p.name] = p sources["submitted_suite.json"] = suite hashes = {} with zipfile.ZipFile(out / "source.zip", "w", zipfile.ZIP_DEFLATED) as archive: for name, path in sources.items(): content = path.read_bytes() hashes[name] = hashlib.sha256(content).hexdigest() archive.writestr(name, content) return hashes def environment(device): import torch import triton driver = ctypes.CDLL("libcuda.so.1") driver_version = ctypes.c_int() driver_status = driver.cuDriverGetVersion(ctypes.byref(driver_version)) maps = Path("/proc/self/maps").read_text().splitlines() cuda_libs = sorted({line.split()[-1] for line in maps if any(name in line for name in ("libcuda.so", "libcudart.so", "libcublas", "libcudnn", "libnvrtc"))}) try: git_head = command(["git", "-C", str(ROOT), "rev-parse", "HEAD"]) git_status = command(["git", "-C", str(ROOT), "status", "--short"]) except (RuntimeError, FileNotFoundError): git_head, git_status = None, None return { "python": platform.python_version(), "platform": platform.platform(), "torch": torch.__version__, "torch_cuda_runtime": torch.version.cuda, "triton": triton.__version__, "gpu": gpu_info(device), "packages": dict(sorted((d.metadata["Name"], d.version) for d in importlib.metadata.distributions())), "git_head": git_head, "git_status": git_status, "torch_build": torch.__config__.show(), "cuda_driver_api": driver_version.value if driver_status == 0 else None, "loaded_cuda_libraries": cuda_libs, "library_environment": {k: os.environ.get(k) for k in ("LD_LIBRARY_PATH", "CUDA_HOME", "TRITON_PTXAS_PATH")}, "precision": {"allow_tf32": False, "allow_bf16_reduced_precision_reduction": False, "output_dtype": "specified by task contract"}, "public_profile_matches": torch.__version__ == "2.9.1+cu128" and triton.__version__ == "3.5.1", } def worker(args): case = json.loads(Path(args.case_json).read_text()) started = time.monotonic() try: from .evaluate import InvalidSubmission, evaluate try: result = evaluate(case, args.candidate, args.seed, args.rounds, args.repeats) except InvalidSubmission as exc: result = {"id": case["id"], "task": case["task"], "status": "incorrect", "error": str(exc)} except Exception as exc: traceback.print_exc() result = {"id": case["id"], "task": case["task"], "status": "error", "error": f"{type(exc).__name__}: {exc}"} result["worker_seconds"] = time.monotonic() - started write_json(args.out, result) return 0 if result["status"] == "passed" else 1 def execute_worker(command, log, timeout, env, candidate, case, output, gpu, bwrap): with worker_command(command, candidate, case, output, gpu, bwrap) as cmd, log.open("w") as stream: proc = subprocess.Popen(cmd, cwd=ROOT, env=env, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) try: return proc.wait(timeout=timeout) except subprocess.TimeoutExpired: os.killpg(proc.pid, signal.SIGKILL) proc.wait() return None def allocation_profiles(args, case_file, out, index, env, gpu): """Each implementation gets a new process, before any warmup can hide buffers.""" profiles = {} for implementation in ("baseline", "candidate"): target = out / f"memory-{index}-{implementation}.json" cmd = [sys.executable, "-m", "kernel_bench.memory_profile", "--case-json", str(case_file), "--candidate", str(Path(args.candidate).resolve()), "--implementation", implementation, "--out", str(target), "--seed", str(args.seed + index * 10000 + 100)] code = execute_worker(cmd, out / f"memory-{index}-{implementation}.log", args.timeout, env, args.candidate, case_file, target, gpu, args.bwrap) profiles[implementation] = json.loads(target.read_text()) if target.exists() and code == 0 else { "status": "timeout" if code is None else "error", "exit_code": code} return profiles def render_report(result): meta = result["environment"] lines = ["# Kernel benchmark calibration", "", f"Run: `{result['run_id']}`", "", f"GPU: {meta['gpu']['name']}; PyTorch {meta['torch']}; Triton {meta['triton']}.", "", str(result["suite"].get("provenance", "See suite metadata for workload provenance.")), "Calibration of submitted code; not a model capability leaderboard.", "", "| Case | Status | Baseline µs | Candidate µs | Kernel speedup (95% CI) | Block speedup |", "|---|---|---:|---:|---:|---:|"] for c in result["cases"]: if c["status"] != "passed": lines.append(f"| {c['id']} | {c['status']} | — | — | — | — |") else: k, b = c["kernel"], c["block"] lo, hi = k["speedup_ci95"] lines.append(f"| {c['id']} | passed | {k['baseline_us']:.3f} | {k['candidate_us']:.3f} | {k['speedup']:.3f}× [{lo:.3f}, {hi:.3f}] | {b['speedup']:.3f}× |") lines += ["", "## Task families", "", "```json", json.dumps(result["summary"], indent=2), "```", "", "Block = frozen projection + residual + RMS normalization; not full-LLM end-to-end latency.", "CUDA Graph warm-input device timing excludes compilation, host scheduling and input generation.", "allocation_profile uses separate fresh processes and includes persistent PyTorch buffers plus the steady-call peak.", "The older kernel/block memory fields are incremental only. Graph pools, native CUDA allocations, energy and board-wide memory are not measured.", "Raw timing samples, correctness diagnostics, environment and source hashes are in results.json.", "Source snapshot: source.zip. GPU state is sampled before and after each case; this is not continuous isolation.", ""] if result["warnings"]: lines += ["## Warnings", ""] + ["- " + w for w in result["warnings"]] return "\n".join(lines) def run(args): candidate, suite_path = Path(args.candidate).resolve(), Path(args.suite).resolve() suite = json.loads(suite_path.read_text()) from . import kernel_v07, kernel_v08, kernel_v081 validate_cases(suite) kernel_v07.validate(suite) kernel_v08.validate(suite) kernel_v081.validate(suite) if args.seed is None: args.seed=suite.get('input_seed',20261102) cases = suite["cases"] if args.case: wanted = set(args.case) cases = [c for c in cases if c["id"] in wanted] if wanted != {c["id"] for c in cases}: raise ValueError("Requested case does not exist in suite") if not cases or len({c["id"] for c in cases}) != len(cases): raise ValueError("Suite must have nonempty unique case IDs") if not candidate.is_file(): raise FileNotFoundError(candidate) out = Path(args.out).resolve() tasks = {c["task"] for c in cases} if tasks & kernel_v07.SPECS.keys(): if suite.get("protocol_version") not in (kernel_v07.VERSION, kernel_v08.VERSION, kernel_v081.VERSION) or len(tasks) != 1: raise ValueError("Select one forward/backward task pack for this candidate and hardware profile") from . import phase_runner code = phase_runner.run(args, cases, suite, candidate, out) compact_finished_output(out) return code out.mkdir(parents=True, exist_ok=False) meta = environment(args.device) if suite.get("protocol_version") in (kernel_v07.VERSION, kernel_v08.VERSION, kernel_v081.VERSION) and "H100" not in meta["gpu"]["name"]: raise RuntimeError("Inherited tasks require the frozen H100 GPU profile") uuid = meta["gpu"]["uuid"] lock = open(Path("/tmp") / ("kernelbench-" + uuid + ".lock"), "w") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise RuntimeError("Another benchmark runner holds this GPU lock") from None busy = gpu_processes(uuid) if busy: raise RuntimeError("Selected GPU already has compute processes: " + str(busy)) result = { "schema_version": 2, "protocol_version": suite.get("protocol_version", LEGACY_PROTOCOL), "run_id": out.name, "started_at": dt.datetime.now(dt.timezone.utc).isoformat(), "suite": suite, "candidate": str(candidate), "environment": meta, "source_sha256": source_snapshot(out, candidate, suite_path), "config": {"seed": args.seed, "rounds": args.rounds, "repeats": args.repeats, "case_timeout_seconds": args.timeout, "allocation_profile": not args.skip_memory_profile, "host_containment": "bubblewrap" if args.bwrap else "none", "judge_integrity": "cooperative-submissions-only; candidate shares Python checker process", "selected_case_ids": [c["id"] for c in cases]}, "cases": [{"id": c["id"], "task": c["task"], "status": "pending"} for c in cases], "warnings": [], } if not meta["public_profile_matches"]: result["warnings"].append("Environment differs from the pinned public calibration profile.") write_json(out / "environment.json", meta) result["summary"] = summarize(result["cases"]) write_json(out / "results.json", result) child_env = os.environ.copy() child_env.update({"CUDA_VISIBLE_DEVICES": uuid, "OMP_NUM_THREADS": "1", "TORCHINDUCTOR_COMPILE_THREADS": "1"}) for index, case in enumerate(cases): case_file, row_file = out / f"case-{index}.json", out / f"result-{index}.json" write_json(case_file, case) before = gpu_info(uuid) busy = gpu_processes(uuid) if busy: row = {"id": case["id"], "task": case["task"], "status": "interference", "error": str(busy)} else: cmd = [sys.executable, "-m", "kernel_bench", "_worker", "--case-json", str(case_file), "--candidate", str(candidate), "--out", str(row_file), "--seed", str(args.seed + index * 10000), "--rounds", str(args.rounds), "--repeats", str(args.repeats)] code = execute_worker(cmd, out / f"worker-{index}.log", args.timeout, child_env, candidate, case_file, row_file, before, args.bwrap) if code is None: row = {"id": case["id"], "task": case["task"], "status": "timeout", "error": f"GPU worker exceeded {args.timeout}s"} else: row = json.loads(row_file.read_text()) if row_file.exists() else { "id": case["id"], "task": case["task"], "status": "crash", "exit_code": code} if code and row.get("status") == "passed": row.update(status="crash", exit_code=code) if row["status"] == "crash": log = (out / f"worker-{index}.log").read_text(errors="replace") row["error"] = f"GPU worker exited with code {code}. " + log[-3500:] if row["status"] == "passed" and not args.skip_memory_profile: row["allocation_profile"] = allocation_profiles(args, case_file, out, index, child_env, before) if any(p["status"] != "passed" for p in row["allocation_profile"].values()): result["warnings"].append(case["id"] + ": allocator profile incomplete; no memory benefit claim allowed.") row["gpu_before"], row["gpu_after"] = before, gpu_info(uuid) result["cases"][index] = row print(f"{case['id']}: {row['status']}" + (f" kernel={row['kernel']['speedup']:.3f}x block={row['block']['speedup']:.3f}x" if row["status"] == "passed" else " " + row.get("error", "")), flush=True) result["summary"] = summarize(result["cases"]) write_json(out / "results.json", result) result["finished_at"] = dt.datetime.now(dt.timezone.utc).isoformat() write_json(out / "results.json", result) (out / "report.md").write_text(render_report(result)) lock.close() compact_finished_output(out) print("REPORT", out / "report.md", flush=True) return 0 if all(c["status"] == "passed" for c in result["cases"]) else 1 def compact_finished_output(out): from .artifact_store import compact_evaluation try: compact_evaluation(out) except (OSError, ValueError, RuntimeError, zipfile.BadZipFile) as exc: # Storage maintenance must not turn a measured result into a model failure. print("Artifact compaction deferred: " + str(exc), file=sys.stderr, flush=True) def main(): parser = argparse.ArgumentParser(description="GPU inference kernel benchmark " + __version__) sub = parser.add_subparsers(dest="command", required=True) for name in ("run", "_worker"): p = sub.add_parser(name) p.add_argument("--candidate", required=True) p.add_argument("--out", required=True) p.add_argument("--seed", type=int, default=None if name=='run' else 20261102) p.add_argument("--rounds", type=int, default=9) p.add_argument("--repeats", type=int, default=64) if name == "run": legacy_suite = ROOT / "kernel_bench/suites/h100_kernel_v06.json" p.add_argument("--suite", required=not legacy_suite.is_file(), default=str(legacy_suite), help="JSON workload suite, e.g. a v0.8.1 task pack public_cases.json") p.add_argument("--device", default="0") p.add_argument("--timeout", type=int, default=600) p.add_argument("--case", action="append") p.add_argument("--skip-memory-profile", action="store_true", help="Debug latency only; omit fresh-process persistent allocation measurements") p.add_argument("--bwrap", help="Optional bubblewrap executable for host containment; not a tamper-proof judge") else: p.add_argument("--case-json", required=True) args = parser.parse_args() if args.rounds < 3 or args.repeats < 1: parser.error("rounds >= 3 and repeats >= 1 are required") return run(args) if args.command == "run" else worker(args) if __name__ == "__main__": sys.exit(main())