From c5ed8496832ec270239356d1a19381a21f5437c9 Mon Sep 17 00:00:00 2001 From: zzw4257 <38639294+zzw4257@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:53:38 -0400 Subject: [PATCH 1/3] Fail kernels that return a cached output on repeated inputs (#171) A kernel can cache its output keyed on the input tensors (identity, data_ptr or version counter). It passes every correctness trial, since each trial uses new inputs, and the timing loop then times the cached calls as near zero. After correctness passes, count the GPU operations torch.profiler records when ModelNew is called again on inputs it has already seen, and on inputs it has not. A cached call launches nothing, so (0 repeated, >0 fresh) fails correctness with correctness_issue_name "cached_output". A kernel that needs no GPU work, or a call the profiler misses, reads 0 on both and passes. On by default; turn off with check_for_cached_output=False. --- src/kernelbench/eval.py | 54 +++++++++++++++++++ .../unit_tests/test_eval_adversarial.py | 30 +++++++++++ .../test_kernels/cached_output_kernel.py | 23 ++++++++ .../test_kernels/no_cache_kernel.py | 14 +++++ 4 files changed, 121 insertions(+) create mode 100644 src/kernelbench/unit_tests/test_kernels/cached_output_kernel.py create mode 100644 src/kernelbench/unit_tests/test_kernels/no_cache_kernel.py diff --git a/src/kernelbench/eval.py b/src/kernelbench/eval.py index 3557dc948f8611..152b363bea2632 100644 --- a/src/kernelbench/eval.py +++ b/src/kernelbench/eval.py @@ -391,6 +391,37 @@ def _process_input_tensor(input, device, backend="cuda", precision=torch.float32 return input_tensor.to(device=device) +def count_gpu_launches(fn, device) -> int: + """ + Number of GPU operations (kernels, memcpy, memset) torch.profiler records during one call of fn. + """ + torch.cuda.synchronize(device=device) + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: + fn() + torch.cuda.synchronize(device=device) + return sum(1 for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA) + + +def count_launches_on_repeated_input(model, inputs, fresh_inputs, device, repeats: int = 3) -> tuple[int, int]: + """ + Returns (launches when model is called again on inputs it has already seen, + launches on inputs it has not seen). + + A kernel that caches its output keyed on the input tensors (their identity, data_ptr + or version counter) launches nothing on the repeated call. A kernel that genuinely needs + no GPU work launches nothing on either call, and so does a call the profiler fails to + record, so only (0, >0) indicates a cache. The repeated count is the max over `repeats` + calls, so one unrecorded call cannot produce a 0. See issue #171. + """ + with torch.no_grad(): + # the first profiler session in a process can record no GPU activity + count_gpu_launches(lambda: torch.zeros(8, device=device).add_(1), device) + fresh = count_gpu_launches(lambda: model(*fresh_inputs), device) + model(*inputs) + repeated = max(count_gpu_launches(lambda: model(*inputs), device) for _ in range(repeats)) + return repeated, fresh + + def eval_kernel_against_ref( original_model_src: str, custom_model_src: str, @@ -410,6 +441,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 no GPU work when called again on the same inputs ) -> KernelExecResult: """ Evaluate the custom kernel against the original model @@ -604,6 +636,28 @@ 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: + set_seed(seed_num) + inputs = [_process_input_tensor(x, device, backend, precision) for x in get_inputs()] + set_seed(seed_num + 1) + fresh_inputs = [_process_input_tensor(x, device, backend, precision) for x in get_inputs()] + repeated, fresh = count_launches_on_repeated_input(custom_model, inputs, fresh_inputs, device) + kernel_exec_result.metadata["launches_on_repeated_input"] = repeated + kernel_exec_result.metadata["launches_on_fresh_input"] = fresh + if repeated == 0 and fresh > 0: + kernel_exec_result.correctness = False + kernel_exec_result.metadata["correctness_issue_name"] = "cached_output" + kernel_exec_result.metadata["correctness_issue"] = ( + f"ModelNew launched {fresh} GPU operations on new inputs but none 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..4cc2b80a928a18 100644 --- a/src/kernelbench/unit_tests/test_eval_adversarial.py +++ b/src/kernelbench/unit_tests/test_eval_adversarial.py @@ -101,10 +101,40 @@ 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_input"] == 0 + assert result.metadata["launches_on_fresh_input"] > 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_input"] > 0 + + def main(): test_result_cache_reuse() test_input_modification() test_non_default_stream() + test_cached_output() + 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/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) From f4fb3f9344c573194c1c4f4c12b464a35a165108 Mon Sep 17 00:00:00 2001 From: zzw4257 <38639294+zzw4257@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:28:39 -0400 Subject: [PATCH 2/3] Compare repeated calls with the first call on the same inputs A cache keyed on a fingerprint of the input values still launches the reads that compute its key on a hit, so it is never zero-launch. Count the first call on inputs the model has not seen and the repeated calls on the same inputs, and fail when the repeated calls launch fewer operations. Both calls see the same values, so a kernel without a cache launches the same operations. Raised in #173. --- src/kernelbench/eval.py | 41 +++++++++---------- .../unit_tests/test_eval_adversarial.py | 20 +++++++-- .../fingerprint_cached_output_kernel.py | 20 +++++++++ 3 files changed, 57 insertions(+), 24 deletions(-) create mode 100644 src/kernelbench/unit_tests/test_kernels/fingerprint_cached_output_kernel.py diff --git a/src/kernelbench/eval.py b/src/kernelbench/eval.py index 152b363bea2632..d63d35d37734b1 100644 --- a/src/kernelbench/eval.py +++ b/src/kernelbench/eval.py @@ -402,24 +402,24 @@ def count_gpu_launches(fn, device) -> int: return sum(1 for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA) -def count_launches_on_repeated_input(model, inputs, fresh_inputs, device, repeats: int = 3) -> tuple[int, int]: +def count_launches_on_repeated_input(model, inputs, device, repeats: int = 3) -> tuple[int, int]: """ - Returns (launches when model is called again on inputs it has already seen, - launches on inputs it has not seen). + Returns (launches on the first call with inputs the model has not seen, + launches when it is called again on the same inputs). - A kernel that caches its output keyed on the input tensors (their identity, data_ptr - or version counter) launches nothing on the repeated call. A kernel that genuinely needs - no GPU work launches nothing on either call, and so does a call the profiler fails to - record, so only (0, >0) indicates a cache. The repeated count is the max over `repeats` - calls, so one unrecorded call cannot produce a 0. See issue #171. + A kernel that caches its output keyed on its inputs (their identity, data_ptr, version + counter or a fingerprint of their values) does 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 takes the same path and launches the same operations. + The repeated count is the max over `repeats` calls, so a call the profiler fails to + record cannot make the repeated count look smaller. See issue #171. """ with torch.no_grad(): # the first profiler session in a process can record no GPU activity count_gpu_launches(lambda: torch.zeros(8, device=device).add_(1), device) - fresh = count_gpu_launches(lambda: model(*fresh_inputs), device) - model(*inputs) + first = count_gpu_launches(lambda: model(*inputs), device) repeated = max(count_gpu_launches(lambda: model(*inputs), device) for _ in range(repeats)) - return repeated, fresh + return first, repeated def eval_kernel_against_ref( @@ -441,7 +441,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 no GPU work when called again on the same inputs + 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 @@ -639,19 +639,18 @@ def eval_kernel_against_ref( # 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: - set_seed(seed_num) + # 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()] - set_seed(seed_num + 1) - fresh_inputs = [_process_input_tensor(x, device, backend, precision) for x in get_inputs()] - repeated, fresh = count_launches_on_repeated_input(custom_model, inputs, fresh_inputs, device) - kernel_exec_result.metadata["launches_on_repeated_input"] = repeated - kernel_exec_result.metadata["launches_on_fresh_input"] = fresh - if repeated == 0 and fresh > 0: + first, repeated = 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: kernel_exec_result.correctness = False kernel_exec_result.metadata["correctness_issue_name"] = "cached_output" kernel_exec_result.metadata["correctness_issue"] = ( - f"ModelNew launched {fresh} GPU operations on new inputs but none when called again " - "on the same inputs, so its output came from a cache" + f"ModelNew launched {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") diff --git a/src/kernelbench/unit_tests/test_eval_adversarial.py b/src/kernelbench/unit_tests/test_eval_adversarial.py index 4cc2b80a928a18..9f9f49008353c8 100644 --- a/src/kernelbench/unit_tests/test_eval_adversarial.py +++ b/src/kernelbench/unit_tests/test_eval_adversarial.py @@ -115,8 +115,21 @@ def test_cached_output(): 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_input"] == 0 - assert result.metadata["launches_on_fresh_input"] > 0 + 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_control(): @@ -126,7 +139,7 @@ def test_cached_output_control(): 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_input"] > 0 + assert result.metadata["launches_on_repeated_call"] == result.metadata["launches_on_first_call"] > 0 def main(): @@ -134,6 +147,7 @@ def main(): test_input_modification() test_non_default_stream() test_cached_output() + test_cached_output_fingerprint() test_cached_output_control() # we might add more adversarial tests in the future 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] From 6cc1b64c1ca45d147887f19d85d238d31d74dcad Mon Sep 17 00:00:00 2001 From: zzw4257 <38639294+zzw4257@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:04:40 -0400 Subject: [PATCH 3/3] Count host-side GPU work calls; do not flag a replayed CUDA graph In some environments torch.profiler stops receiving device-side kernel records once an extension has been loaded with torch.utils.cpp_extension, while host-side launch calls are still traced. Count the host-side calls that enqueue GPU work (kernel and graph launches, memcpy, memset) instead. A replayed CUDA graph does its work in one launch call, so a repeated call that launches a graph is not flagged; a control test covers it. --- src/kernelbench/eval.py | 48 ++++++++++++------- .../unit_tests/test_eval_adversarial.py | 12 +++++ .../test_kernels/cuda_graph_kernel.py | 29 +++++++++++ 3 files changed, 71 insertions(+), 18 deletions(-) create mode 100644 src/kernelbench/unit_tests/test_kernels/cuda_graph_kernel.py diff --git a/src/kernelbench/eval.py b/src/kernelbench/eval.py index d63d35d37734b1..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,35 +392,46 @@ def _process_input_tensor(input, device, backend="cuda", precision=torch.float32 return input_tensor.to(device=device) -def count_gpu_launches(fn, device) -> int: +_GPU_WORK_CALL = re.compile(r"Launch|Memcpy|Memset") + + +def gpu_work_calls(fn, device) -> list[str]: """ - Number of GPU operations (kernels, memcpy, memset) torch.profiler records during one call of fn. + 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 sum(1 for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA) + 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]: +def count_launches_on_repeated_input(model, inputs, device, repeats: int = 3) -> tuple[int, int, bool]: """ - Returns (launches on the first call with inputs the model has not seen, - launches when it is called again on the same inputs). + 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) does less GPU work on the repeated call: + 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 takes the same path and launches the same operations. - The repeated count is the max over `repeats` calls, so a call the profiler fails to - record cannot make the repeated count look smaller. See issue #171. + 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 no GPU activity - count_gpu_launches(lambda: torch.zeros(8, device=device).add_(1), device) - first = count_gpu_launches(lambda: model(*inputs), device) - repeated = max(count_gpu_launches(lambda: model(*inputs), device) for _ in range(repeats)) - return first, repeated + # 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( @@ -642,14 +654,14 @@ def eval_kernel_against_ref( # 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 = count_launches_on_repeated_input(custom_model, inputs, device) + 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: + 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 launched {first} GPU operations on new inputs but only {repeated} when called " + 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: diff --git a/src/kernelbench/unit_tests/test_eval_adversarial.py b/src/kernelbench/unit_tests/test_eval_adversarial.py index 9f9f49008353c8..c01780eafc7180 100644 --- a/src/kernelbench/unit_tests/test_eval_adversarial.py +++ b/src/kernelbench/unit_tests/test_eval_adversarial.py @@ -132,6 +132,17 @@ def test_cached_output_fingerprint(): 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. @@ -148,6 +159,7 @@ def main(): 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/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