correct
20_GatedDeltaNetLinearAttention.py
started
2026-05-11T12:00:01Z
timingkernelbench.timing
kernel mean / median / std
2.65 / — / 0.00 μs
ref mean / median / std
6.13 / — / 1.20 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
993.75x
energyNVML (pynvml)
ratio (ref / kernel)
1.38x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Scalar-gated delta-rule linear attention recurrence.
A recurrent state matrix is decayed by a scalar gate per head, updated by a
rank-1 key/value outer product, then read out by a query vector.
"""
def __init__(self):
super().__init__()
def forward(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
gate: torch.Tensor,
beta: torch.Tensor,
) -> torch.Tensor:
batch_size, seq_len, num_heads, head_dim = q.shape
state = torch.zeros(batch_size, num_heads, head_dim, head_dim, dtype=q.dtype, device=q.device)
outputs = []
for t in range(seq_len):
gate_t = gate[:, t].unsqueeze(-1).unsqueeze(-1)
beta_t = beta[:, t].unsqueeze(-1).unsqueeze(-1)
kv_outer = k[:, t].unsqueeze(-1) * v[:, t].unsqueeze(-2)
state = gate_t * state + beta_t * kv_outer
y_t = (q[:, t].unsqueeze(-1) * state).sum(dim=-2)
outputs.append(y_t)
return torch.stack(outputs, dim=1)
batch_size = 2
seq_len = 128
num_heads = 4
head_dim = 24
def get_inputs():
p = popcorn_pri
q = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
k = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
v = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
gate = torch.sigmoid(torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_heads), dtype=torch.float32))
beta = torch.sigmoid(torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_heads), dtype=torch.float32))
return [q, k, v, gate, beta]
def get_init_inputs():
return []
turn 01428.0s turn · 11.9s LLM · 1416.2s tools · tokens in=1,675 · out=6 · total=2,379
reasoning
The task is to replace the forward computation of this PyTorch model with a custom CUDA kernel. The model is a scalar-gated delta-rule linear attention recurrence.
I need to replace the forward computation of a PyTorch model with a custom CUDA kernel for a scalar-gated delta-rule linear attention recurrence. The new ModelNew class should accept the same inputs as the original Model, have the same forward signature, and produce the same outputs numerically.
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 189.1s turn · 16.2s LLM · 72.9s tools · tokens in=2,612 · out=637 · total=3,355
reasoning
GPU is H100, good.
I need to implement the 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 delta_rule_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\n const float* __restrict__ beta,\n float* __restrict__ output,\n int batch_size,\n int seq_len,\n int num_heads,\n int head_dim\n) {\n int bh = blockIdx.x;\n int b = bh / num_heads;\n int h = bh % num_heads;\n if (b >= batch_size) return;\n\n extern __shared__ float state[]; // head_dim * head_dim\n\n int D = head_dim;\n for (int i = threadIdx.x; i < D * D; i += blockDim.x) {\n state[i] = 0.0f;\n }\n __syncthreads();\n\n const float* q_bh = q + (b * seq_len * num_heads + h) * D;\n const float* k_bh = k + (b * seq_len * num_heads + h) * D;\n const float* v_bh = v + (b * seq_len * num_heads + h) * D;\n const float* g_bh = gate + (b * seq_len * num_heads + h);\n const float* be_bh = beta + (b * seq_len * num_heads + h);\n float* out_bh = output + (b * seq_len * num_heads + h) * D;\n\n for (int t = 0; t < seq_len; t++) {\n float gt = g_bh[t * num_heads]; // wait, stride wrong\n // fix strides\n }\n}\n\nat::Tensor delta_rule_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate,\n torch::Tensor beta\n) {\n auto batch_size = q.size(0);\n auto seq_len = q.size(1);\n auto num_heads = q.size(2);\n auto head_dim = q.size(3);\n\n auto output = torch::zeros({batch_size, seq_len, num_heads, head_dim}, q.options());\n\n int threads = 256;\n int blocks = batch_size * num_heads;\n size_t smem = head_dim * head_dim * sizeof(float);\n\n // placeholder, kernel not implemented yet\n return output;\n}\n'''\n\ncpp_source = '''\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta);\n'''\n\nmodule = load_inline(\n name='delta_rule',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['delta_rule_cuda'],\n verbose=True\n)\n'''\n\nprint(\"Compile test\")"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: ModelNew class not found or syntax error prevented execution.
Syntax Error in custom generated code or Compilation Error unterminated triple-quoted string literal (detected at line 86) (<string>, line 84)
turn 2489.6s turn · 22.0s LLM · 467.6s tools · tokens in=3,408 · out=840 · total=4,466
reasoning
Oops, syntax error because of the way I wrote the string. I need to write the full proper code.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void delta_rule_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\n const float* __restrict__ beta,\n float* __restrict__ output,\n int B, int S, int H, int D\n) {\n extern __shared__ float state[];\n int bh = blockIdx.x;\n int b = bh / H;\n int h = bh % H;\n if (b >= B) return;\n\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n state[i] = 0.0f;\n }\n __syncthreads();\n\n for (int t = 0; t < S; t++) {\n float g = gate[((b * S + t) * H + h)];\n float be = beta[((b * S + t) * H + h)];\n\n // outer = k[t] outer v[t]\n // state = g * state + be * outer\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kval = k[((b * S + t) * H + h) * D + row];\n float vval = v[((b * S + t) * H + h) * D + col];\n float outer = kval * vval;\n state[i] = g * state[i] + be * outer;\n }\n __syncthreads();\n\n // y = q[t] @ state (q row vector * matrix)\n for (int col = threadIdx.x; col < D; col += blockDim.x) {\n float sum = 0.0f;\n for (int r = 0; r < D; r++) {\n float qval = q[((b * S + t) * H + h) * D + r];\n sum += qval * state[r * D + col];\n }\n output[((b * S + t) * H + h) * D + col] = sum;\n }\n __syncthreads();\n }\n}\n\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta) {\n auto B = q.size(0);\n auto S = q.size(1);\n auto H = q.size(2);\n auto D = q.size(3);\n auto output = torch::zeros({B, S, H, D}, q.options());\n dim3 blocks(B * H);\n int threads = 256;\n size_t smem = D * D * sizeof(float);\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),\n gate.data_ptr<float>(), beta.data_ptr<float>(),\n output.data_ptr<float>(), B, S, H, D);\n cudaDeviceSynchronize();\n return output;\n}\n'''\n\ncpp_source = '''\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta);\n'''\n\nmodule = load_inline(\n name='delta_rule',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['delta_rule_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, q, k, v, gate, beta):\n return self.module.delta_rule_cuda(q, k, v, gate, beta)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 3314.9s turn · 7.8s LLM · 307.1s tools · tokens in=4,483 · out=841 · total=5,331
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void delta_rule_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\n const float* __restrict__ beta,\n float* __restrict__ output,\n int B, int S, int H, int D\n) {\n extern __shared__ float state[];\n int bh = blockIdx.x;\n int b = bh / H;\n int h = bh % H;\n if (b >= B) return;\n\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n state[i] = 0.0f;\n }\n __syncthreads();\n\n for (int t = 0; t < S; t++) {\n float g = gate[((b * S + t) * H + h)];\n float be = beta[((b * S + t) * H + h)];\n\n // outer = k[t] outer v[t]\n // state = g * state + be * outer\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kval = k[((b * S + t) * H + h) * D + row];\n float vval = v[((b * S + t) * H + h) * D + col];\n float outer = kval * vval;\n state[i] = g * state[i] + be * outer;\n }\n __syncthreads();\n\n // y = q[t] @ state (q row vector * matrix)\n for (int col = threadIdx.x; col < D; col += blockDim.x) {\n float sum = 0.0f;\n for (int r = 0; r < D; r++) {\n float qval = q[((b * S + t) * H + h) * D + r];\n sum += qval * state[r * D + col];\n }\n output[((b * S + t) * H + h) * D + col] = sum;\n }\n __syncthreads();\n }\n}\n\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta) {\n auto B = q.size(0);\n auto S = q.size(1);\n auto H = q.size(2);\n auto D = q.size(3);\n auto output = torch::zeros({B, S, H, D}, q.options());\n dim3 blocks(B * H);\n int threads = 256;\n size_t smem = D * D * sizeof(float);\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),\n gate.data_ptr<float>(), beta.data_ptr<float>(),\n output.data_ptr<float>(), B, S, H, D);\n cudaDeviceSynchronize();\n return output;\n}\n'''\n\ncpp_source = '''\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta);\n'''\n\nmodule = load_inline(\n name='delta_rule',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['delta_rule_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, q, k, v, gate, beta):\n return self.module.delta_rule_cuda(q, k, v, gate, beta)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=6.68e-06 mean_abs_err=2.16e-07 max_rel_err=1.27e-02
turn 4505.1s turn · 7.7s LLM · 497.4s tools · tokens in=5,391 · out=840 · total=6,280 · FINAL
reasoning
Correct! Now, to submit, but is it faster? We need to check, but since submit will do timing.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void delta_rule_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\n const float* __restrict__ beta,\n float* __restrict__ output,\n int B, int S, int H, int D\n) {\n extern __shared__ float state[];\n int bh = blockIdx.x;\n int b = bh / H;\n int h = bh % H;\n if (b >= B) return;\n\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n state[i] = 0.0f;\n }\n __syncthreads();\n\n for (int t = 0; t < S; t++) {\n float g = gate[((b * S + t) * H + h)];\n float be = beta[((b * S + t) * H + h)];\n\n // outer = k[t] outer v[t]\n // state = g * state + be * outer\n for (int i = threadIdx.x; i < D*D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kval = k[((b * S + t) * H + h) * D + row];\n float vval = v[((b * S + t) * H + h) * D + col];\n float outer = kval * vval;\n state[i] = g * state[i] + be * outer;\n }\n __syncthreads();\n\n // y = q[t] @ state (q row vector * matrix)\n for (int col = threadIdx.x; col < D; col += blockDim.x) {\n float sum = 0.0f;\n for (int r = 0; r < D; r++) {\n float qval = q[((b * S + t) * H + h) * D + r];\n sum += qval * state[r * D + col];\n }\n output[((b * S + t) * H + h) * D + col] = sum;\n }\n __syncthreads();\n }\n}\n\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta) {\n auto B = q.size(0);\n auto S = q.size(1);\n auto H = q.size(2);\n auto D = q.size(3);\n auto output = torch::zeros({B, S, H, D}, q.options());\n dim3 blocks(B * H);\n int threads = 256;\n size_t smem = D * D * sizeof(float);\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),\n gate.data_ptr<float>(), beta.data_ptr<float>(),\n output.data_ptr<float>(), B, S, H, D);\n cudaDeviceSynchronize();\n return output;\n}\n'''\n\ncpp_source = '''\nat::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta);\n'''\n\nmodule = load_inline(\n name='delta_rule',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['delta_rule_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, q, k, v, gate, beta):\n return self.module.delta_rule_cuda(q, k, v, gate, beta)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 2.65 μs
Runtime stats: mean=2.65μs median=?μs std=0.00μs
Numerical precision: max_abs_err=6.68e-06 mean_abs_err=2.16e-07 max_rel_err=1.27e-02
Memory: 0.38 MB peak (ref: 0.54 MB, ratio: 0.705x)
Kernel launches: 4 (ref: 3975, fusion ratio: 993.75)
Energy: 1941.38 mJ/run (ref: 2670.08 mJ, ratio: 1.3754x)
SOL score: 0.005
final submitted kernel (95 lines, 2,830 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = r'''
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void delta_rule_kernel(
const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ v,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ output,
int B, int S, int H, int D
) {
extern __shared__ float state[];
int bh = blockIdx.x;
int b = bh / H;
int h = bh % H;
if (b >= B) return;
for (int i = threadIdx.x; i < D*D; i += blockDim.x) {
state[i] = 0.0f;
}
__syncthreads();
for (int t = 0; t < S; t++) {
float g = gate[((b * S + t) * H + h)];
float be = beta[((b * S + t) * H + h)];
// outer = k[t] outer v[t]
// state = g * state + be * outer
for (int i = threadIdx.x; i < D*D; i += blockDim.x) {
int row = i / D;
int col = i % D;
float kval = k[((b * S + t) * H + h) * D + row];
float vval = v[((b * S + t) * H + h) * D + col];
float outer = kval * vval;
state[i] = g * state[i] + be * outer;
}
__syncthreads();
// y = q[t] @ state (q row vector * matrix)
for (int col = threadIdx.x; col < D; col += blockDim.x) {
float sum = 0.0f;
for (int r = 0; r < D; r++) {
float qval = q[((b * S + t) * H + h) * D + r];
sum += qval * state[r * D + col];
}
output[((b * S + t) * H + h) * D + col] = sum;
}
__syncthreads();
}
}
at::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta) {
auto B = q.size(0);
auto S = q.size(1);
auto H = q.size(2);
auto D = q.size(3);
auto output = torch::zeros({B, S, H, D}, q.options());
dim3 blocks(B * H);
int threads = 256;
size_t smem = D * D * sizeof(float);
delta_rule_kernel<<<blocks, threads, smem>>>(
q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),
gate.data_ptr<float>(), beta.data_ptr<float>(),
output.data_ptr<float>(), B, S, H, D);
cudaDeviceSynchronize();
return output;
}
'''
cpp_source = '''
at::Tensor delta_rule_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate, torch::Tensor beta);
'''
module = load_inline(
name='delta_rule',
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=['delta_rule_cuda'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.module = module
def forward(self, q, k, v, gate, beta):
return self.module.delta_rule_cuda(q, k, v, gate, beta)