File size: 16,683 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
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())