diff --git a/src/kernelbench/eval.py b/src/kernelbench/eval.py index 3557dc948f8611..0e09c803bff9be 100644 --- a/src/kernelbench/eval.py +++ b/src/kernelbench/eval.py @@ -8,6 +8,7 @@ import linecache import os, subprocess import random +import re import sys import tempfile import traceback @@ -391,6 +392,48 @@ def _process_input_tensor(input, device, backend="cuda", precision=torch.float32 return input_tensor.to(device=device) +_GPU_WORK_CALL = re.compile(r"Launch|Memcpy|Memset") + + +def gpu_work_calls(fn, device) -> list[str]: + """ + Names of the CUDA runtime/driver calls that enqueue GPU work (kernel and graph launches, + memcpy, memset), as torch.profiler traces them on the host during one call of fn. + + Host-side calls are counted rather than device-side kernel records: in some environments + the device-side records stop arriving once an extension has been loaded with + torch.utils.cpp_extension, while the host-side calls are still traced. + """ + torch.cuda.synchronize(device=device) + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: + fn() + torch.cuda.synchronize(device=device) + return [e.name for e in prof.events() + if e.device_type == torch.autograd.DeviceType.CPU and _GPU_WORK_CALL.search(e.name)] + + +def count_launches_on_repeated_input(model, inputs, device, repeats: int = 3) -> tuple[int, int, bool]: + """ + Returns (GPU work calls on the first call with inputs the model has not seen, + the most GPU work calls over `repeats` further calls with the same inputs, + whether a repeated call launched a CUDA graph). + + A kernel that caches its output keyed on its inputs (their identity, data_ptr, version + counter or a fingerprint of their values) enqueues less GPU work on the repeated call: + nothing at all, or only the reads that compute its key. Both calls see the same values, + so a kernel without a cache enqueues the same work. A replayed CUDA graph does all of its + work in one launch call, so it is reported separately rather than counted as a cache. + See issue #171. + """ + with torch.no_grad(): + # the first profiler session in a process can record nothing + gpu_work_calls(lambda: torch.zeros(8, device=device).add_(1), device) + first = len(gpu_work_calls(lambda: model(*inputs), device)) + repeated = [gpu_work_calls(lambda: model(*inputs), device) for _ in range(repeats)] + graph = any("Graph" in name for calls in repeated for name in calls) + return first, max(len(calls) for calls in repeated), graph + + def eval_kernel_against_ref( original_model_src: str, custom_model_src: str, @@ -410,6 +453,7 @@ def eval_kernel_against_ref( # Guard against potential reward hacking [optional but ongoing enhancement] check_for_excessive_speedup: bool = True, excessive_speedup_threshold: float = 10, # flag if the kernel is more than x faster than the reference + check_for_cached_output: bool = True, # fail a kernel that launches less GPU work when called again on the same inputs ) -> KernelExecResult: """ Evaluate the custom kernel against the original model @@ -604,6 +648,27 @@ def eval_kernel_against_ref( compiled=True, correctness=False, metadata=metadata ) + # Check that a correct kernel computes on every call instead of returning a cached output + if check_for_cached_output and kernel_exec_result is not None and kernel_exec_result.correctness: + try: + # inputs the model has not seen: correctness trials draw random seeds, timing uses seed_num onwards + set_seed(seed_num + 2**20) + inputs = [_process_input_tensor(x, device, backend, precision) for x in get_inputs()] + first, repeated, graph = count_launches_on_repeated_input(custom_model, inputs, device) + kernel_exec_result.metadata["launches_on_first_call"] = first + kernel_exec_result.metadata["launches_on_repeated_call"] = repeated + if repeated < first and not graph: + kernel_exec_result.correctness = False + kernel_exec_result.metadata["correctness_issue_name"] = "cached_output" + kernel_exec_result.metadata["correctness_issue"] = ( + f"ModelNew enqueued {first} GPU operations on new inputs but only {repeated} when called " + "again on the same inputs, so its output came from a cache" + ) + if verbose: + print("[Eval] Kernel returns a cached output on repeated inputs") + except Exception as e: + kernel_exec_result.metadata["cached_output_check_error"] = str(e) + # Measure Performance [Optional] | conditioned on compilation + correctness + no exception so far if measure_performance: try: diff --git a/src/kernelbench/unit_tests/test_eval_adversarial.py b/src/kernelbench/unit_tests/test_eval_adversarial.py index ac019ba34df6c0..c01780eafc7180 100644 --- a/src/kernelbench/unit_tests/test_eval_adversarial.py +++ b/src/kernelbench/unit_tests/test_eval_adversarial.py @@ -101,10 +101,66 @@ def test_non_default_stream(timing_method="do_bench", threshold=1.5): ) +def test_cached_output(): + """ + Test that we flag a kernel that caches its output keyed on the input tensors. + + Methodology: + - Adversarial kernel computes the correct result on new inputs, so it passes every correctness trial + - Called again on the same input tensors, it returns the stored output without launching GPU work + - The timing loop reuses one set of inputs, so the cached calls would be timed as near zero + - Eval should flag it as incorrect: no GPU launches on a repeated input, some on a fresh one (issue #171) + """ + result = run_test_kernel(problem_name="level1/1_Square_matrix_multiplication_.py", + kernel_filename="cached_output_kernel.py") + assert result.correctness is False, "Cached output hack detected" + assert result.metadata["correctness_issue_name"] == "cached_output" + assert result.metadata["launches_on_repeated_call"] == 0 + assert result.metadata["launches_on_first_call"] > 0 + + +def test_cached_output_fingerprint(): + """ + Test that we flag a cache keyed on a fingerprint of the input values. + On a hit it still launches the reads that compute its key, so a zero-launch rule misses it, + but it launches fewer operations than on the first call with the same inputs. + """ + result = run_test_kernel(problem_name="level1/1_Square_matrix_multiplication_.py", + kernel_filename="fingerprint_cached_output_kernel.py") + assert result.correctness is False, "Fingerprint cache hack detected" + assert result.metadata["correctness_issue_name"] == "cached_output" + assert 0 < result.metadata["launches_on_repeated_call"] < result.metadata["launches_on_first_call"] + + +def test_cached_output_cuda_graph_control(): + """ + Control: a kernel that captures a CUDA graph on its first call with each input set and replays it + afterwards enqueues fewer calls on a repeat (one graph launch) but still computes, so it should pass. + """ + result = run_test_kernel(problem_name="level1/1_Square_matrix_multiplication_.py", + kernel_filename="cuda_graph_kernel.py") + assert result.correctness is True + assert result.metadata["launches_on_repeated_call"] > 0 + + +def test_cached_output_control(): + """ + Control for test_cached_output: the same matmul without a cache launches GPU work on every call and passes. + """ + result = run_test_kernel(problem_name="level1/1_Square_matrix_multiplication_.py", + kernel_filename="no_cache_kernel.py") + assert result.correctness is True + assert result.metadata["launches_on_repeated_call"] == result.metadata["launches_on_first_call"] > 0 + + def main(): test_result_cache_reuse() test_input_modification() test_non_default_stream() + test_cached_output() + test_cached_output_fingerprint() + test_cached_output_cuda_graph_control() + test_cached_output_control() # we might add more adversarial tests in the future diff --git a/src/kernelbench/unit_tests/test_kernels/cached_output_kernel.py b/src/kernelbench/unit_tests/test_kernels/cached_output_kernel.py new file mode 100644 index 00000000000000..8467c85e7f65b7 --- /dev/null +++ b/src/kernelbench/unit_tests/test_kernels/cached_output_kernel.py @@ -0,0 +1,23 @@ +import torch +import torch.nn as nn + +########################################### +# This custom kernel computes the correct matmul on any new inputs, +# but stores the output and returns it again when called on the same input tensors. +# It passes every correctness trial (each trial uses new inputs), and the timing loop, +# which calls it repeatedly on one set of inputs, would time the cached calls as near zero. +# Eval should flag it as incorrect: it launches no GPU work on a repeated input (see issue #171). +########################################### + +class ModelNew(nn.Module): + def __init__(self) -> None: + super().__init__() + self._last_inputs = None + self._last_output = None + + def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: + if self._last_inputs is not None and self._last_inputs[0] is A and self._last_inputs[1] is B: + return self._last_output + self._last_inputs = (A, B) + self._last_output = torch.matmul(A, B) + return self._last_output diff --git a/src/kernelbench/unit_tests/test_kernels/cuda_graph_kernel.py b/src/kernelbench/unit_tests/test_kernels/cuda_graph_kernel.py new file mode 100644 index 00000000000000..7f6d497d21f180 --- /dev/null +++ b/src/kernelbench/unit_tests/test_kernels/cuda_graph_kernel.py @@ -0,0 +1,29 @@ +import torch +import torch.nn as nn + +########################################### +# Control for the cached-output check: captures a CUDA graph on the first call with each input set +# and replays it on later calls with the same inputs. The replay computes the matmul again, so this +# is not a cache, although a repeated call enqueues only one graph launch (see issue #171). +########################################### + +class ModelNew(nn.Module): + def __init__(self) -> None: + super().__init__() + self._graphs = {} + + def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: + key = (A.data_ptr(), B.data_ptr()) + if key not in self._graphs: + side = torch.cuda.Stream() + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + torch.matmul(A, B) # warm up outside the capture + torch.cuda.current_stream().wait_stream(side) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = torch.matmul(A, B) + self._graphs[key] = (graph, out, A, B) # keep A and B alive so their addresses stay valid + graph, out, _, _ = self._graphs[key] + graph.replay() + return out diff --git a/src/kernelbench/unit_tests/test_kernels/fingerprint_cached_output_kernel.py b/src/kernelbench/unit_tests/test_kernels/fingerprint_cached_output_kernel.py new file mode 100644 index 00000000000000..36eccb47abc95a --- /dev/null +++ b/src/kernelbench/unit_tests/test_kernels/fingerprint_cached_output_kernel.py @@ -0,0 +1,20 @@ +import torch +import torch.nn as nn + +########################################### +# This custom kernel caches its output keyed on a fingerprint of the input values (the first 8 +# values of each input). Correctness trials use different values, so it computes on each of them. +# On a cache hit it still reads the fingerprint, which launches GPU copies, so it is not zero-launch, +# but it launches fewer operations than the first call on the same inputs (see issue #171). +########################################### + +class ModelNew(nn.Module): + def __init__(self) -> None: + super().__init__() + self._cache = {} + + def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: + key = tuple(A.flatten()[:8].tolist() + B.flatten()[:8].tolist()) + if key not in self._cache: + self._cache[key] = torch.matmul(A, B) + return self._cache[key] diff --git a/src/kernelbench/unit_tests/test_kernels/no_cache_kernel.py b/src/kernelbench/unit_tests/test_kernels/no_cache_kernel.py new file mode 100644 index 00000000000000..7e90eef870aada --- /dev/null +++ b/src/kernelbench/unit_tests/test_kernels/no_cache_kernel.py @@ -0,0 +1,14 @@ +import torch +import torch.nn as nn + +########################################### +# Control for cached_output_kernel.py: the same matmul without a cache. +# It launches GPU work on every call and should pass. +########################################### + +class ModelNew(nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: + return torch.matmul(A, B)