Datasets:
Download kernel_bench/evaluate.py from code-roamer/gpu-kernel-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/evaluate.py
- Command line
-
hf download hf://datasets/code-roamer/gpu-kernel-benchmark/kernel_bench/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/evaluate.py
13.9 kB
| """One-case GPU evaluator. The supervisor gives each case a fresh process.""" | |
| import gc | |
| import importlib.util | |
| from pathlib import Path | |
| import sys | |
| import time | |
| import torch | |
| from . import baselines, extended, sparse, expansion | |
| from .metrics import paired_summary | |
| from .tasks import PATTERNS, TASKS, make_inputs, make_integration, reference, tensor_bytes | |
| class InvalidSubmission(Exception): | |
| pass | |
| def same_tensor_bits(a, b): | |
| """Integer low bits, signed zero, and opaque FP8 storage must stay unchanged.""" | |
| return (a.shape == b.shape and a.dtype == b.dtype and a.device == b.device and | |
| torch.equal(a.contiguous().reshape(-1).view(torch.uint8), b.contiguous().reshape(-1).view(torch.uint8))) | |
| def load_candidate(path, task): | |
| sys.path.insert(0, str(Path(path).resolve().parent)) | |
| spec = importlib.util.spec_from_file_location("kernel_submission", path) | |
| module = importlib.util.module_from_spec(spec) | |
| sys.modules[spec.name] = module | |
| spec.loader.exec_module(module) | |
| fn = getattr(module, task) | |
| if not callable(fn): | |
| raise InvalidSubmission(f"Submission must define {task}") | |
| return fn | |
| def check_output(actual, expected, contract): | |
| if isinstance(expected, tuple): | |
| if not isinstance(actual, tuple) or len(actual) != len(expected): | |
| raise InvalidSubmission("Output tuple structure mismatch") | |
| contracts = contract.get("outputs", [contract] * len(expected)) | |
| return {"outputs": [check_output(a, e, c) for a, e, c in zip(actual, expected, contracts)]} | |
| if not isinstance(actual, torch.Tensor): | |
| raise InvalidSubmission("Output is not a torch.Tensor") | |
| if actual.shape != expected.shape or actual.dtype != expected.dtype or actual.device != expected.device: | |
| raise InvalidSubmission(f"Output metadata mismatch: shape={actual.shape}, dtype={actual.dtype}, device={actual.device}") | |
| af, ef = actual.float(), expected.float() | |
| if contract.get("allow_negative_infinity", False): | |
| if not torch.equal(torch.isneginf(af), torch.isneginf(ef)): | |
| raise InvalidSubmission("Negative-infinity sentinel mismatch") | |
| af, ef = (x.masked_fill(torch.isneginf(x), 0.) for x in (af, ef)) | |
| if not torch.isfinite(af).all().item(): | |
| raise InvalidSubmission("Non-finite output") | |
| if contract["rtol"] == 0 and contract["atol"] == 0 and not same_tensor_bits(actual, expected): | |
| raise InvalidSubmission("Exact output bits mismatch") | |
| error = (af - ef).abs() | |
| reference_rms = ef.square().mean().sqrt().item() | |
| rmse = error.square().mean().sqrt().item() | |
| nrmse = rmse / max(reference_rms, 1e-12) | |
| absolute_bound = max(contract["atol"], contract.get("rms_atol", 0) * reference_rms) | |
| bound = absolute_bound + contract["rtol"] * ef.abs() | |
| if 'propagated_atol' in contract: | |
| bound=bound+contract['propagated_atol'] | |
| max_scaled = torch.where(bound > 0, error / bound, torch.where(error == 0, 0., float("inf"))).max().item() | |
| if max_scaled > 1: | |
| raise InvalidSubmission(f"Numerical mismatch: max error/tolerance={max_scaled:.5g}") | |
| if reference_rms > 0 and nrmse > contract["nrmse"]: | |
| raise InvalidSubmission(f"Normalized RMSE {nrmse:.5g} exceeds {contract['nrmse']}") | |
| return {"max_abs_error": error.max().item(), "max_error_over_tolerance": max_scaled, | |
| "rmse": rmse, "reference_rms": reference_rms, "nrmse": nrmse, "absolute_bound": absolute_bound} | |
| def check_call(fn, args, expected, contract): | |
| snapshots = [x.clone() if isinstance(x, torch.Tensor) else x for x in args] | |
| actual = fn(*args) | |
| torch.cuda.synchronize() | |
| for old, new in zip(snapshots, args): | |
| if isinstance(old, torch.Tensor) and not same_tensor_bits(old, new): | |
| raise InvalidSubmission("Input mutation detected") | |
| stats = check_task_output(actual, expected, contract, args) | |
| semantic = contract.get("semantic") | |
| if not (extended.check_invariants(semantic, args, actual) and sparse.check_invariants(semantic, args, actual) | |
| and expansion.check_invariants(semantic, args, actual)): | |
| raise InvalidSubmission("Exact semantic invariant failed") | |
| return stats | |
| def check_task_output(actual, expected, contract, args): | |
| if contract.get('semantic')=='multi_lora': | |
| from .expansion.oracle import lora_rounding_bound | |
| propagated=lora_rounding_bound(*args) | |
| stats=check_output(actual,expected,{**contract,'propagated_atol':propagated}) | |
| stats['propagated_bf16_ulp_bound_max']=float(propagated.max()) | |
| return stats | |
| if contract.get('semantic')!='dsa_indexer': | |
| return check_output(actual,expected,contract) | |
| if not isinstance(actual,tuple) or len(actual)!=2: | |
| raise InvalidSubmission('DSA output must be (scores, indices)') | |
| scores,ids=actual | |
| for got,want in zip(actual,expected): | |
| if not isinstance(got,torch.Tensor) or (got.shape,got.dtype,got.device)!=(want.shape,want.dtype,want.device): | |
| raise InvalidSubmission('DSA output metadata mismatch') | |
| if bool(((ids<0)|(ids>=args[1].shape[1])).any()): | |
| raise InvalidSubmission('DSA index out of range') | |
| ordered=ids.sort(-1).values | |
| if bool((ordered[...,1:]==ordered[...,:-1]).any()): | |
| raise InvalidSubmission('DSA duplicate index') | |
| if bool((scores[...,1:]>scores[...,:-1]).any()) or bool(((scores[...,1:]==scores[...,:-1])&(ids[...,1:]<ids[...,:-1])).any()): | |
| raise InvalidSubmission('DSA score order or exact tie order mismatch') | |
| from .expansion.oracle import dsa_scores | |
| true_scores=dsa_scores(*args[:-1]) | |
| selected=true_scores.gather(-1,ids) | |
| score_contract=contract['outputs'][0] | |
| score_stats=check_output(scores,selected,score_contract) | |
| rank_stats=check_output(selected,expected[0],score_contract) | |
| zero=true_scores.eq(0).all(-1) | |
| if not torch.equal(ids[zero],expected[1][zero]): | |
| raise InvalidSubmission('DSA all-zero tie must select ascending IDs') | |
| return {'score_error':score_stats,'rank_error':rank_stats,'unique_in_range_indices':True} | |
| def memory_usage(fn): | |
| gc.collect() | |
| torch.cuda.synchronize() | |
| before = torch.cuda.memory_allocated() | |
| torch.cuda.reset_peak_memory_stats() | |
| out = fn() | |
| torch.cuda.synchronize() | |
| result = {"extra_peak_allocated_bytes": max(0, torch.cuda.max_memory_allocated() - before), | |
| "output_bytes": sum(x.numel() * x.element_size() for x in (out if isinstance(out, tuple) else (out,)))} | |
| del out | |
| return result | |
| def capture(fn, repeats): | |
| stream = torch.cuda.Stream() | |
| stream.wait_stream(torch.cuda.current_stream()) | |
| with torch.cuda.stream(stream): | |
| for _ in range(5): | |
| fn() | |
| stream.synchronize() | |
| graph = torch.cuda.CUDAGraph() | |
| with torch.cuda.graph(graph, stream=stream): | |
| for _ in range(repeats): | |
| out = fn() | |
| torch.cuda.synchronize() | |
| # Keep the last output alive for the lifetime of the graph. | |
| return graph, out | |
| def measure_pair(base_fn, candidate_fn, rounds, repeats, seed, verify_graphs=None): | |
| memory = {"baseline": memory_usage(base_fn), "candidate": memory_usage(candidate_fn)} | |
| graphs = [capture(base_fn, repeats), capture(candidate_fn, repeats)] | |
| for _ in range(3): | |
| for graph, _out in graphs: | |
| graph.replay() | |
| torch.cuda.synchronize() | |
| samples = [[], []] | |
| for round_id in range(rounds): | |
| # Balanced AB/BA rounds avoid giving one implementation every cold/first slot. | |
| order = (0, 1) if (round_id + seed) % 2 == 0 else (1, 0) | |
| pair = [0.0, 0.0] | |
| for idx in order: | |
| start, end = (torch.cuda.Event(enable_timing=True) for _ in range(2)) | |
| start.record() | |
| graphs[idx][0].replay() | |
| end.record() | |
| end.synchronize() | |
| pair[idx] = start.elapsed_time(end) * 1000 / repeats | |
| for idx in (0, 1): | |
| samples[idx].append(pair[idx]) | |
| result = paired_summary(*samples, seed=seed) | |
| result.update({"memory": memory, "graph_calls_per_sample": repeats, | |
| "timing_mode": "cuda_graph_unrolled/warm_reused_inputs/CUDA_events"}) | |
| if verify_graphs is not None: | |
| result["graph_replay_validation"] = verify_graphs(graphs) | |
| return result | |
| def check_graph_replay(graph, output, args, expected, contract): | |
| snapshots = [x.clone() if isinstance(x, torch.Tensor) else x for x in args] | |
| graph.replay() | |
| torch.cuda.synchronize() | |
| for old, current in zip(snapshots, args): | |
| if isinstance(old, torch.Tensor) and not same_tensor_bits(old, current): | |
| raise InvalidSubmission("CUDA Graph input mutation detected") | |
| stats = check_task_output(output, expected, contract, args) | |
| semantic = contract.get("semantic") | |
| if not (extended.check_invariants(semantic, args, output) and sparse.check_invariants(semantic, args, output) | |
| and expansion.check_invariants(semantic, args, output)): | |
| raise InvalidSubmission("CUDA Graph exact semantic invariant failed") | |
| return stats | |
| def evaluate(case, candidate_path, seed, rounds, repeats): | |
| torch.cuda.set_device(0) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False | |
| task = case["task"] | |
| contract = TASKS[task] | |
| base_fn, baseline_name = baselines.resolve(case) | |
| major, minor = torch.cuda.get_device_capability() | |
| result = {"id": case["id"], "task": task, "case": case, "seed": seed, | |
| "baseline": baseline_name, "contract": contract} | |
| if major * 10 + minor < contract["min_sm"]: | |
| return {**result, "status": "unsupported", "reason": "GPU capability below contract minimum"} | |
| candidate_fn = load_candidate(candidate_path, task) | |
| checks = [] | |
| start = time.perf_counter() | |
| # Baseline validation is separate: a broken baseline is an infrastructure error. | |
| for i, pattern in enumerate(PATTERNS): | |
| args = make_inputs(case, seed + i, pattern) | |
| expected = reference(task, *args) | |
| try: | |
| base_stats = check_call(base_fn, args, expected, contract) | |
| except InvalidSubmission as exc: | |
| raise RuntimeError(f"Baseline failed {pattern} (seed={seed + i}): {exc}") from exc | |
| try: | |
| cand_stats = check_call(candidate_fn, args, expected, contract) | |
| except InvalidSubmission as exc: | |
| raise InvalidSubmission(f"Candidate eager {pattern}: {exc}") from exc | |
| checks.append({"pattern": pattern, "seed": seed + i, | |
| "baseline": base_stats, "candidate": cand_stats}) | |
| del args, expected | |
| result["validation"] = checks | |
| result["compile_and_validation_seconds"] = time.perf_counter() - start | |
| args = make_inputs(case, seed + 100) | |
| expected = reference(task, *args) | |
| glue = make_integration(case, args, seed + 101) | |
| expected_block = glue(expected) | |
| calls = {"baseline": 0, "candidate": 0} | |
| def block(which, fn): | |
| calls[which] += 1 | |
| return glue(fn(*args)) | |
| block_contract = contract.get("integration_contract", {k: v for k, v in contract.items() if k != "outputs"}) | |
| try: | |
| check_output(block("baseline", base_fn), expected_block, block_contract) | |
| except InvalidSubmission as exc: | |
| raise RuntimeError(f"Baseline failed integration (seed={seed + 100}): {exc}") from exc | |
| check_output(block("candidate", candidate_fn), expected_block, block_contract) | |
| result["input_bytes"] = tensor_bytes(args) | |
| def verify_graphs(graphs, phase): | |
| checks = [] | |
| for offset in (2000, 2001): | |
| fresh = make_inputs(case, seed + offset) | |
| # CUDA Graph pointers stay fixed; only their contents change. | |
| for destination, source in zip(args, fresh): | |
| if isinstance(destination, torch.Tensor): | |
| destination.copy_(source) | |
| elif destination != source: | |
| raise RuntimeError("Graph validation requires unchanged CPU planning metadata") | |
| expected = reference(task, *args) | |
| gate = contract | |
| if phase == "block": | |
| expected = glue(expected) | |
| gate = {k: v for k, v in block_contract.items() if k != "semantic"} | |
| for which, (graph, output) in zip(("baseline", "candidate"), graphs): | |
| try: | |
| stats = check_graph_replay(graph, output, args, expected, gate) | |
| except InvalidSubmission as exc: | |
| if which == "baseline": | |
| raise RuntimeError(f"Baseline failed {phase} graph replay (seed={seed + offset}): {exc}") from exc | |
| raise InvalidSubmission(f"Candidate {phase} graph replay failed: {exc}") from exc | |
| checks.append({"implementation": which, "seed": seed + offset, **stats}) | |
| original = make_inputs(case, seed + 100) | |
| for destination, source in zip(args, original): | |
| if isinstance(destination, torch.Tensor): | |
| destination.copy_(source) | |
| return checks | |
| result["kernel"] = measure_pair(lambda: base_fn(*args), lambda: candidate_fn(*args), rounds, repeats, seed, | |
| lambda graphs: verify_graphs(graphs, "kernel")) | |
| result["block"] = measure_pair(lambda: block("baseline", base_fn), | |
| lambda: block("candidate", candidate_fn), rounds, repeats, seed + 1, | |
| lambda graphs: verify_graphs(graphs, "block")) | |
| result["integration_calls"] = calls | |
| # Fresh data after timing catches common output-caching/stateful mistakes. | |
| fresh = make_inputs(case, seed + 1000) | |
| result["post_timing_check"] = check_call(candidate_fn, fresh, reference(task, *fresh), contract) | |
| return {**result, "status": "passed"} | |