correct
9_AssociativeScan.py
started
2026-05-11T10:47:10Z
timingkernelbench.timing
kernel mean / median / std
1.73 / — / 0.00 μs
ref mean / median / std
89.90 / — / 5.44 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
24583.00x
energyNVML (pynvml)
ratio (ref / kernel)
44.02x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
225.07 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Performs a parallel associative scan (linear recurrence) over a 1D sequence.
Given coefficient a and input b at each timestep, computes:
h_0 = b_0
h_t = a_t * h_{t-1} + b_t for t > 0
This is the core parallelizable primitive underlying Mamba's selective scan and
other SSM architectures. Sequential in naive PyTorch but can be parallelized
via the associative scan algorithm in O(L log L) span.
Args:
d_model (int): Number of independent recurrence channels.
"""
def __init__(self, d_model: int):
super(Model, self).__init__()
self.d_model = d_model
def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
B, L, D = a.shape
h = torch.zeros(B, D, device=a.device, dtype=a.dtype)
outputs = []
for t in range(L):
h = a[:, t] * h + b[:, t]
outputs.append(h)
return torch.stack(outputs, dim=1)
batch_size = 32
d_model = 256
seq_len = 4096
def get_inputs():
a = torch.sigmoid(torch.randn(popcorn_pri.jitter_int(batch_size), popcorn_pri.jitter_int(seq_len), d_model))
b = torch.randn(popcorn_pri.jitter_int(batch_size), popcorn_pri.jitter_int(seq_len), d_model)
return [a, b]
def get_init_inputs():
return [d_model]turn 08.8s turn · 8.8s LLM · 0.0s tools · tokens in=1,562 · out=6 · total=1,948
reasoning
The task is to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model performs a parallel associative scan for a linear recurrence: h_t = a_t * h_{t-1} + b_t.
The task involves replacing the forward computation of a PyTorch model with a custom CUDA kernel.
call → get_gpu_specs
callget_gpu_specs
{}
result ← get_gpu_specs (ok)
okget_gpu_specs
GPU specs for NVIDIA H100 80GB HBM3:
total memory (runtime): 79.1 GB
spec entry: H100
GPU Architecture: Hopper
GPU Memory: 80GB
Memory Bandwidth: 3.35 TB/s
FP64 TFLOPS: 34
FP64 Tensor Core TFLOPS: 67
FP32 TFLOPS: 67
TF32 Tensor Core TFLOPS: 989 with sparsity
BFLOAT16 Tensore Core TFLOPS: 1979 with sparsity
FP16 Tensor Core TFLOPS: 1979 with sparsity
FP8 Tensor Core TFLOPS: 3958 with sparsity
INT8 Tensor Core TOPS: 3958 with sparsity
Register File Size: 64K 32-bit registers per SM
Maximum number of registers per thread: 255
Maximum number of thread blocks per SM: 32
Shared memory capacity per SM: 228 KB
Maximum shared memory per thread block: 227 KB
turn 191.3s turn · 14.1s LLM · 77.2s tools · tokens in=2,181 · out=468 · total=2,997
reasoning
H100 GPU, high bandwidth.
I need to replace the forward computation of a PyTorch model with a custom CUDA kernel.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void scan_kernel(const float* a, const float* b, float* out, int B, int L, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n \n int batch = idx / D;\n int dim = idx % D;\n \n float h = 0.0f;\n for (int t = 0; t < L; t++) {\n int offset = (batch * L + t) * D + dim;\n float at = a[offset];\n float bt = b[offset];\n h = at * h + bt;\n out[offset] = h;\n }\n}\n\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b) {\n auto B = a.size(0);\n auto L = a.size(1);\n auto D = a.size(2);\n \n auto out = torch::empty({B, L, D}, a.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n scan_kernel<<<blocks, threads>>>(\n a.data_ptr<float>(),\n b.data_ptr<float>(),\n out.data_ptr<float>(),\n B, L, D\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b);\n\"\"\"\n\nmodule = load_inline(\n name='scan_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['parallel_scan'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.module = module\n\n def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n return self.module.parallel_scan(a, b)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2263.5s turn · 5.7s LLM · 257.8s tools · tokens in=3,014 · out=469 · total=3,490
reasoning
Compiled successfully. Now check correctness.
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void scan_kernel(const float* a, const float* b, float* out, int B, int L, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n \n int batch = idx / D;\n int dim = idx % D;\n \n float h = 0.0f;\n for (int t = 0; t < L; t++) {\n int offset = (batch * L + t) * D + dim;\n float at = a[offset];\n float bt = b[offset];\n h = at * h + bt;\n out[offset] = h;\n }\n}\n\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b) {\n auto B = a.size(0);\n auto L = a.size(1);\n auto D = a.size(2);\n \n auto out = torch::empty({B, L, D}, a.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n scan_kernel<<<blocks, threads>>>(\n a.data_ptr<float>(),\n b.data_ptr<float>(),\n out.data_ptr<float>(),\n B, L, D\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b);\n\"\"\"\n\nmodule = load_inline(\n name='scan_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['parallel_scan'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.module = module\n\n def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n return self.module.parallel_scan(a, b)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=9.54e-07 mean_abs_err=2.04e-08 max_rel_err=1.75e+00
turn 3344.0s turn · 8.3s LLM · 335.7s tools · tokens in=3,550 · out=468 · total=4,172 · FINAL
reasoning
Correct! Now, to submit, but is it faster? The task requires faster than reference, so I need to check timing implicitly by submitting, but since it says run faster, and this sequential per thread sho...
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void scan_kernel(const float* a, const float* b, float* out, int B, int L, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n \n int batch = idx / D;\n int dim = idx % D;\n \n float h = 0.0f;\n for (int t = 0; t < L; t++) {\n int offset = (batch * L + t) * D + dim;\n float at = a[offset];\n float bt = b[offset];\n h = at * h + bt;\n out[offset] = h;\n }\n}\n\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b) {\n auto B = a.size(0);\n auto L = a.size(1);\n auto D = a.size(2);\n \n auto out = torch::empty({B, L, D}, a.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n scan_kernel<<<blocks, threads>>>(\n a.data_ptr<float>(),\n b.data_ptr<float>(),\n out.data_ptr<float>(),\n B, L, D\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b);\n\"\"\"\n\nmodule = load_inline(\n name='scan_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['parallel_scan'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.module = module\n\n def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n return self.module.parallel_scan(a, b)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 1.73 μs
Runtime stats: mean=1.73μs median=?μs std=0.00μs
Numerical precision: max_abs_err=9.54e-07 mean_abs_err=2.04e-08 max_rel_err=1.75e+00
Memory: 417.0 MB peak (ref: 545.0 MB, ratio: 0.7651x)
Kernel launches: 1 (ref: 24583, fusion ratio: 24583.0)
Energy: 232.42 mJ/run (ref: 10230.94 mJ, ratio: 44.0192x)
SOL score: 0.0672
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (70 lines, 1,665 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void scan_kernel(const float* a, const float* b, float* out, int B, int L, int D) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int total = B * D;
if (idx >= total) return;
int batch = idx / D;
int dim = idx % D;
float h = 0.0f;
for (int t = 0; t < L; t++) {
int offset = (batch * L + t) * D + dim;
float at = a[offset];
float bt = b[offset];
h = at * h + bt;
out[offset] = h;
}
}
torch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b) {
auto B = a.size(0);
auto L = a.size(1);
auto D = a.size(2);
auto out = torch::empty({B, L, D}, a.options());
int total = B * D;
int threads = 256;
int blocks = (total + threads - 1) / threads;
scan_kernel<<<blocks, threads>>>(
a.data_ptr<float>(),
b.data_ptr<float>(),
out.data_ptr<float>(),
B, L, D
);
return out;
}
"""
cpp_source = """
torch::Tensor parallel_scan(torch::Tensor a, torch::Tensor b);
"""
module = load_inline(
name='scan_module',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['parallel_scan'],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self, d_model: int):
super(ModelNew, self).__init__()
self.d_model = d_model
self.module = module
def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return self.module.parallel_scan(a, b)