#!/usr/bin/env python3 """Compare the repository kernels with the archived public human winners. The runner uses the official FlashInfer-Trace definitions and workload input generation. Correctness is checked against each definition's reference implementation, while the reported speedup is explicitly ``human_latency / ours_latency``. This is deliberately different from FlashInfer-Bench's built-in speedup field, which is relative to its mathematical reference baseline. """ from __future__ import annotations import argparse import importlib.metadata import json import math import statistics import subprocess import sys import warnings from pathlib import Path from typing import Any import torch REPO_ROOT = Path(__file__).resolve().parents[1] MANIFEST_PATH = REPO_ROOT / "human_best" / "manifest.json" DEFAULT_DATASET = REPO_ROOT / "benchmark_data" / "mlsys26-contest" SOURCE_EXTENSIONS = {".py"} CURRENT = { "gdn_prefill": { "source_root": REPO_ROOT / "kernels" / "gdn_prefill", "entry_point": "kernel.py::run", "language": "python", "destination_passing_style": False, "definition": "gdn_prefill_qk4_v8_d128_k_last", }, "moe": { "source_root": REPO_ROOT / "kernels" / "moe", "entry_point": "kernel.py::run", "language": "python", "destination_passing_style": False, "definition": "moe_fp8_block_scale_ds_routing_topk8_ng8_kg4_e32_h7168_i2048", }, "dsa_attention": { "source_root": REPO_ROOT / "kernels" / "dsa_attention", "entry_point": "kernel.py::run", "language": "python", "destination_passing_style": False, "definition": "dsa_sparse_attention_h16_ckv512_kpe64_topk2048_ps64", }, } def _load_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) def _submodule_source_root(entry: dict[str, Any]) -> Path: """Resolve a pinned submodule's source directory, verifying its checkout. The human reference is compiled straight from the winner's upstream tree. Git already guarantees the content matches the recorded commit, so the only thing to check is that the submodule is present, sits on that commit, and carries no local edits. A mismatch is an error rather than a silent substitution of whatever happens to be on disk. """ path = REPO_ROOT / entry["path"] hint = "run `git submodule update --init --recursive`" if not (path / ".git").exists(): raise RuntimeError(f"submodule {entry['path']} is not checked out; {hint}") def git(*argv: str) -> str: return subprocess.run( ["git", "-C", str(path), *argv], capture_output=True, text=True, check=True, ).stdout.strip() head = git("rev-parse", "HEAD") if head != entry["commit"]: raise RuntimeError( f"submodule {entry['path']} is at {head}, expected {entry['commit']}; {hint}" ) dirty = git("status", "--porcelain") if dirty: raise RuntimeError( f"submodule {entry['path']} has local modifications; the human " f"reference must be the unmodified upstream tree:\n{dirty}" ) source_root = path / entry["source_root"] if not source_root.is_dir(): raise RuntimeError( f"source root {entry['source_root']!r} missing in {entry['path']}" ) return source_root def _source_files(source_root: Path, entry_point: str): from flashinfer_bench.data import SourceFile files: dict[str, str] = {} for path in sorted(source_root.rglob("*")): if not path.is_file() or path.suffix.lower() not in SOURCE_EXTENSIONS: continue relative = path.relative_to(source_root).as_posix() files[relative] = path.read_text(encoding="utf-8") entry_file = entry_point.split("::", 1)[0] if entry_file not in files: raise RuntimeError(f"entry point file {entry_file!r} is not under {source_root}") # PythonBuilder writes sources into a package. Explicit package markers # keep relative imports in the Wombat snapshot reliable. directories = {Path(".")} for relative in files: parent = Path(relative).parent while parent != Path("."): directories.add(parent) parent = parent.parent for directory in sorted(directories): marker = (directory / "__init__.py").as_posix() files.setdefault(marker, "# benchmark package marker\n") return [SourceFile(path=path, content=content) for path, content in sorted(files.items())] def _make_solution(track: str, spec: dict[str, Any], *, human: bool): from flashinfer_bench.data import BuildSpec, Solution, SupportedLanguages if human: source_root = _submodule_source_root(spec) name = f"human-{track}-{spec['commit'][:8]}" entry_point = spec["entry_point"] language = spec["language"] destination_passing_style = spec["destination_passing_style"] definition = spec["definition"] else: current = CURRENT[track] source_root = current["source_root"] name = f"ours-{track}" entry_point = current["entry_point"] language = current["language"] destination_passing_style = current["destination_passing_style"] definition = current["definition"] if not source_root.is_dir(): raise FileNotFoundError(f"source root does not exist: {source_root}") spec_model = BuildSpec( language=SupportedLanguages(language), target_hardware=["cuda"], entry_point=entry_point, destination_passing_style=destination_passing_style, ) return Solution( name=name, definition=definition, author="public-human-winner" if human else "repository-submission", spec=spec_model, sources=_source_files(source_root, entry_point), ) def _clone(value: Any) -> Any: if isinstance(value, torch.Tensor): return value.clone() if isinstance(value, tuple): return tuple(_clone(item) for item in value) if isinstance(value, list): return [_clone(item) for item in value] return value def _accuracy( definition: Any, reference: list[torch.Tensor], runnable: Any, inputs: list[Any], device: str, atol: float, rtol: float, required_matched_ratio: float, ) -> dict[str, Any]: from flashinfer_bench.bench.evaluators.utils import allocate_outputs, normalize_result try: if runnable.metadata.destination_passing_style: output = allocate_outputs(definition, inputs, device) runnable(*inputs, *output) else: output = normalize_result(definition, runnable(*inputs), device) except Exception as exc: # noqa: BLE001 - preserve per-workload diagnostics return {"passed": False, "error": f"{type(exc).__name__}: {exc}"} if len(output) != len(reference): return { "passed": False, "error": f"wrong output count: got {len(output)}, expected {len(reference)}", } max_abs = 0.0 max_rel = 0.0 total = 0 bad = 0 for got, expected in zip(output, reference, strict=True): if tuple(got.shape) != tuple(expected.shape): return { "passed": False, "error": f"shape mismatch: got {tuple(got.shape)}, expected {tuple(expected.shape)}", } if got.dtype != expected.dtype: return { "passed": False, "error": f"dtype mismatch: got {got.dtype}, expected {expected.dtype}", } got_f = got.float() expected_f = expected.float() if not torch.isfinite(got_f).all().item(): return {"passed": False, "error": "non-finite output"} diff = (got_f - expected_f).abs() relative = diff / (expected_f.abs() + 1e-8) max_abs = max(max_abs, float(diff.max().item()) if diff.numel() else 0.0) max_rel = max(max_rel, float(relative.max().item()) if relative.numel() else 0.0) bad += int(((diff > atol) & (relative > rtol)).sum().item()) total += diff.numel() matched = 1.0 if total == 0 else 1.0 - bad / total return { "passed": matched >= required_matched_ratio, "max_abs": max_abs, "max_rel": max_rel, "matched_ratio": matched, "error": None if matched >= required_matched_ratio else "tolerance exceeded", } def _is_cupti_fallback_warning(message: str) -> bool: message = message.lower() return "falling back to cuda" in message or "cupti is not installed" in message def _require_cupti() -> str: """Fail before compilation if the required Python CUPTI package is absent.""" try: from cupti import cupti as _cupti # noqa: F401 version = importlib.metadata.version("cupti-python") except Exception as exc: # noqa: BLE001 - provide one actionable message raise RuntimeError( "CUPTI is required for this benchmark; install cupti-python and pyelftools " "with `uv sync` before running it" ) from exc try: if int(version.split(".", 1)[0]) < 13: raise ValueError(f"cupti-python {version} is too old (need >=13)") except ValueError as exc: raise RuntimeError(str(exc)) from exc return version def _measure( runnable: Any, args: list[Any], device: str, warmup: int, iterations: int, ) -> tuple[float, str]: """Measure a callable with the real CUPTI kernel-span timer. The generic Runnable timing helper clones every argument and follows a different framework protocol. Keep one preallocated argument set per trial and use FlashInfer's CUPTI timer directly for the paired comparison. """ from flashinfer.testing import bench_gpu_time_with_cupti try: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") # The FlashInfer helper has an internal fallback. Turn its CUPTI # warning into an exception so no non-CUPTI timing is executed. warnings.filterwarnings("error", message=r"(?i).*cupti.*") times = bench_gpu_time_with_cupti( fn=runnable, dry_run_iters=warmup, repeat_iters=iterations, input_args=tuple(args), cold_l2_cache=True, use_cuda_graph=False, ) fallback = any(_is_cupti_fallback_warning(str(item.message)) for item in caught) if fallback: raise RuntimeError( "FlashInfer CUPTI helper returned a non-CUPTI fallback; " "install cupti-python and pyelftools before benchmarking" ) return float(statistics.median(times)), "cupti" except Exception as exc: # noqa: BLE001 - add an actionable dependency error raise RuntimeError( f"CUPTI timing failed ({type(exc).__name__}: {exc}); " "install cupti-python and pyelftools before benchmarking" ) from exc def _timing_args(definition: Any, runnable: Any, inputs: list[Any], device: str) -> list[Any]: from flashinfer_bench.bench.evaluators.utils import allocate_outputs args = list(inputs) if runnable.metadata.destination_passing_style: args.extend(allocate_outputs(definition, inputs, device)) return args def _reference_outputs(reference_runnable: Any, inputs: list[Any], definition: Any, device: str): from flashinfer_bench.bench.evaluators.utils import normalize_result result = reference_runnable(*inputs) return normalize_result(definition, result, device) def _load_track_workloads(dataset: Path, definition_name: str, max_workloads: int): from flashinfer_bench.data import TraceSet trace_set = TraceSet.from_path(str(dataset)) if definition_name not in trace_set.definitions: available = ", ".join(sorted(trace_set.definitions)) raise RuntimeError(f"definition {definition_name!r} not found; available: {available}") definition = trace_set.definitions[definition_name] workloads = [trace.workload for trace in trace_set.workloads.get(definition_name, [])] if max_workloads > 0: workloads = workloads[:max_workloads] if not workloads: raise RuntimeError(f"no workloads found for {definition_name}") return definition, workloads def _run_track( track: str, dataset: Path, device: str, max_workloads: int, warmup: int, iterations: int, trials: int, skip_accuracy: bool, seed: int, ) -> dict[str, Any]: from flashinfer_bench.bench.utils import gen_inputs, load_safetensors from flashinfer_bench.compile import BuilderRegistry current_spec = CURRENT[track] definition, workloads = _load_track_workloads(dataset, current_spec["definition"], max_workloads) human_spec = next(item for item in _load_json(MANIFEST_PATH)["submodules"] if item["track"] == track) ours_solution = _make_solution(track, current_spec, human=False) human_solution = _make_solution(track, human_spec, human=True) registry = BuilderRegistry.get_instance() ours = registry.build(definition, ours_solution) human = registry.build(definition, human_solution) reference = None if skip_accuracy else registry.build_reference(definition) accuracy_cfg = { "gdn_prefill": (1e-2, 1e-2, 1.0), "moe": (1.0, 0.3, 0.9), "dsa_attention": (1e-2, 1e-2, 1.0), }[track] atol, rtol, required = accuracy_cfg rows: list[dict[str, Any]] = [] timer_names: set[str] = set() print(f"\n=== {track} ===") print(f"definition: {definition.name}") print(f"workloads: {len(workloads)}") print(f"device: {device}; warmup/iterations/trials: {warmup}/{iterations}/{trials}") print( f"human submodule: {human_spec['repository']}" f"@{human_spec['commit'][:12]} ({human_spec['describe']})" ) try: for index, workload in enumerate(workloads): row: dict[str, Any] = { "workload_id": workload.uuid, "axes": workload.axes, "ours": {"correctness": None, "latency_ms": None, "timer": None}, "human": {"correctness": None, "latency_ms": None, "timer": None}, "speedup_human_over_ours": None, } print(f"[{index + 1:03d}/{len(workloads):03d}] {workload.uuid[:12]} axes={workload.axes}") safe_tensors = load_safetensors(definition, workload, trace_set_root=dataset) trial_inputs: list[list[Any]] = [] trial_references: list[list[torch.Tensor] | None] = [] for trial in range(trials): torch.manual_seed((seed + index * 1009 + trial) & 0x7FFFFFFF) inputs = gen_inputs(definition, workload, device=device, safe_tensors=safe_tensors) trial_inputs.append(inputs) if reference is None: trial_references.append(None) continue try: with torch.no_grad(): trial_references.append(_reference_outputs(reference, _clone(inputs), definition, device)) torch.cuda.synchronize(device) except Exception as exc: # noqa: BLE001 - retain speed data if reference fails print(f" reference failed: {type(exc).__name__}: {exc}") trial_references.append(None) for label, runnable in (("ours", ours), ("human", human)): accuracy_rows: list[dict[str, Any]] = [] latency_rows: list[float] = [] for inputs, expected in zip(trial_inputs, trial_references, strict=True): call_inputs = _clone(inputs) if expected is not None and not skip_accuracy: with torch.no_grad(): accuracy_rows.append( _accuracy( definition, expected, runnable, call_inputs, device, atol, rtol, required, ) ) elif not skip_accuracy: accuracy_rows.append({"passed": False, "error": "reference unavailable"}) timing_args = _timing_args(definition, runnable, _clone(inputs), device) latency, timer_name = _measure( runnable, timing_args, device, warmup, iterations, ) latency_rows.append(latency) timer_names.add(timer_name) row[label]["timer"] = timer_name if accuracy_rows: passed = all(item.get("passed", False) for item in accuracy_rows) max_abs = max((float(item.get("max_abs", 0.0)) for item in accuracy_rows), default=None) max_rel = max((float(item.get("max_rel", 0.0)) for item in accuracy_rows), default=None) matched = min((float(item.get("matched_ratio", 0.0)) for item in accuracy_rows), default=0.0) row[label]["correctness"] = { "passed": passed, "max_abs": max_abs, "max_rel": max_rel, "min_matched_ratio": matched, "errors": [item.get("error") for item in accuracy_rows if item.get("error")], } elif skip_accuracy: row[label]["correctness"] = {"skipped": True} if latency_rows: row[label]["latency_ms"] = sum(latency_rows) / len(latency_rows) ours_ms = row["ours"]["latency_ms"] human_ms = row["human"]["latency_ms"] if ours_ms and human_ms and ours_ms > 0: row["speedup_human_over_ours"] = human_ms / ours_ms print( f" ours={ours_ms:.6f} ms human={human_ms:.6f} ms " f"speedup={row['speedup_human_over_ours']:.4f}x" ) else: print(" latency unavailable") for label in ("ours", "human"): check = row[label]["correctness"] if check and "passed" in check: print(f" {label} correctness={'PASS' if check['passed'] else 'FAIL'}") rows.append(row) finally: ours.cleanup() human.cleanup() if reference is not None: reference.cleanup() speedups = [row["speedup_human_over_ours"] for row in rows if row["speedup_human_over_ours"]] if timer_names != {"cupti"}: raise RuntimeError(f"unexpected timing backends: {sorted(timer_names)}") summary: dict[str, Any] = { "track": track, "definition": definition.name, "human_repository": human_spec["repository"], "human_commit": human_spec["commit"], "human_describe": human_spec["describe"], "workloads": len(rows), "timer": sorted(timer_names), "warmup": warmup, "iterations": iterations, "trials": trials, "seed": seed, "speedup_definition": "human_latency_ms / ours_latency_ms", "speedup_aggregation": "per_workload_geometric_mean", "timing_protocol": "FlashInfer CUPTI kernel span with cold L2; one preallocated argument set per trial", "accuracy_scope": "all_definition_outputs", "speedup_arithmetic_mean": sum(speedups) / len(speedups) if speedups else None, "speedup_geometric_mean": ( math.exp(sum(math.log(value) for value in speedups) / len(speedups)) if speedups else None ), "ours_correct": sum( 1 for row in rows if row["ours"]["correctness"] and row["ours"]["correctness"].get("passed") ), "human_correct": sum( 1 for row in rows if row["human"]["correctness"] and row["human"]["correctness"].get("passed") ), "rows": rows, } print( f"summary: speedup arithmetic={summary['speedup_arithmetic_mean']} " f"geomean={summary['speedup_geometric_mean']}" ) return summary def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--track", choices=["all", *CURRENT.keys()], default="all", help="track to run (default: all)", ) parser.add_argument("--dataset", type=Path, default=DEFAULT_DATASET) parser.add_argument("--device", default="cuda:0") parser.add_argument("--max-workloads", type=int, default=0, help="limit each track; 0 means all") parser.add_argument("--warmup", type=int, default=3) parser.add_argument("--iterations", type=int, default=50) parser.add_argument("--trials", type=int, default=3) parser.add_argument("--seed", type=int, default=20260823) parser.add_argument( "--skip-accuracy", action="store_true", help="skip mathematical-reference execution; latency is still measured", ) parser.add_argument("--output", type=Path, help="optional JSON output path") args = parser.parse_args() if not torch.cuda.is_available(): print("CUDA is required; run this on an NVIDIA B200", file=sys.stderr) return 2 if not args.dataset.is_dir(): print( f"dataset not found: {args.dataset}\n" "run `uv run python tools/download_workloads.py` first", file=sys.stderr, ) return 2 device = torch.device(args.device) if device.type != "cuda": print("--device must be a CUDA device", file=sys.stderr) return 2 torch.cuda.set_device(device) cupti_version = _require_cupti() props = torch.cuda.get_device_properties(device) print(f"GPU: {props.name} (compute capability {props.major}.{props.minor})") print(f"CUPTI: cupti-python {cupti_version} (required; no fallback timer)") tracks = list(CURRENT) if args.track == "all" else [args.track] results = [] for track in tracks: results.append( _run_track( track, args.dataset.expanduser().resolve(), str(device), args.max_workloads, args.warmup, args.iterations, args.trials, args.skip_accuracy, args.seed, ) ) result = {"schema": "mlsys26-human-best-benchmark/v1", "device": str(device), "tracks": results} if args.output: output = args.output.expanduser() output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n", encoding="utf-8") print(f"wrote {output}") return 0 if __name__ == "__main__": raise SystemExit(main())