correct
20_GatedDeltaNetLinearAttention.py
started
2026-05-11T19:21:25Z
timingkernelbench.timing
kernel mean / median / std
0.26 / — / 0.00 μs
ref mean / median / std
8.44 / — / 0.13 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
993.75x
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 0174.6s turn · 9.9s LLM · 164.6s tools · tokens in=2,206 · out=6 · total=2,752
reasoning
The task is to replace the forward computation of a 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 model class, ModelNew, must accept the same inputs as the original and implement forward with the same signature, producing identical outputs.
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 188.8s turn · 14.4s LLM · 74.4s tools · tokens in=2,985 · out=912 · total=3,975
reasoning
GPU is H100, plenty of resources. D=24 small.
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 for (int t = 0; t < seq_len; t++) {\n float g = gate[(b * seq_len + t) * num_heads + h];\n float be = beta[(b * seq_len + t) * num_heads + h];\n\n // update state: state = g * state + be * outer(k, v)\n for (int i = threadIdx.x; i < D * D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kv = k[((b * seq_len + t) * num_heads + h) * D + row] *\n v[((b * seq_len + t) * num_heads + h) * D + col];\n float old = state[i];\n state[i] = g * old + be * kv;\n }\n __syncthreads();\n\n // compute y = q @ state (sum over dim -2, i.e. q row vector * state)\n for (int j = threadIdx.x; j < D; j += blockDim.x) {\n float sum = 0.0f;\n for (int i = 0; i < D; i++) {\n float qval = q[((b * seq_len + t) * num_heads + h) * D + i];\n sum += qval * state[i * D + j];\n }\n output[((b * seq_len + t) * num_heads + h) * D + j] = sum;\n }\n __syncthreads();\n }\n}\n\ntorch::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 int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_heads = q.size(2);\n int 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 int smem = head_dim * head_dim * sizeof(float);\n\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n beta.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size, seq_len, num_heads, head_dim\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::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 extra_cuda_cflags=['-O3']\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 2150.3s turn · 10.7s LLM · 139.6s tools · tokens in=3,992 · out=913 · total=4,912
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 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 for (int t = 0; t < seq_len; t++) {\n float g = gate[(b * seq_len + t) * num_heads + h];\n float be = beta[(b * seq_len + t) * num_heads + h];\n\n // update state: state = g * state + be * outer(k, v)\n for (int i = threadIdx.x; i < D * D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kv = k[((b * seq_len + t) * num_heads + h) * D + row] *\n v[((b * seq_len + t) * num_heads + h) * D + col];\n float old = state[i];\n state[i] = g * old + be * kv;\n }\n __syncthreads();\n\n // compute y = q @ state (sum over dim -2, i.e. q row vector * state)\n for (int j = threadIdx.x; j < D; j += blockDim.x) {\n float sum = 0.0f;\n for (int i = 0; i < D; i++) {\n float qval = q[((b * seq_len + t) * num_heads + h) * D + i];\n sum += qval * state[i * D + j];\n }\n output[((b * seq_len + t) * num_heads + h) * D + j] = sum;\n }\n __syncthreads();\n }\n}\n\ntorch::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 int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_heads = q.size(2);\n int 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 int smem = head_dim * head_dim * sizeof(float);\n\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n beta.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size, seq_len, num_heads, head_dim\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::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 extra_cuda_cflags=['-O3']\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: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=6.68e-06 mean_abs_err=2.12e-07 max_rel_err=1.53e-03
turn 3106.8s turn · 11.0s LLM · 95.7s tools · tokens in=4,972 · out=912 · total=5,933 · FINAL
reasoning
Correct! Now, to check speed, I should profile or just submit since it should be faster than the loop in PyTorch.
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 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 for (int t = 0; t < seq_len; t++) {\n float g = gate[(b * seq_len + t) * num_heads + h];\n float be = beta[(b * seq_len + t) * num_heads + h];\n\n // update state: state = g * state + be * outer(k, v)\n for (int i = threadIdx.x; i < D * D; i += blockDim.x) {\n int row = i / D;\n int col = i % D;\n float kv = k[((b * seq_len + t) * num_heads + h) * D + row] *\n v[((b * seq_len + t) * num_heads + h) * D + col];\n float old = state[i];\n state[i] = g * old + be * kv;\n }\n __syncthreads();\n\n // compute y = q @ state (sum over dim -2, i.e. q row vector * state)\n for (int j = threadIdx.x; j < D; j += blockDim.x) {\n float sum = 0.0f;\n for (int i = 0; i < D; i++) {\n float qval = q[((b * seq_len + t) * num_heads + h) * D + i];\n sum += qval * state[i * D + j];\n }\n output[((b * seq_len + t) * num_heads + h) * D + j] = sum;\n }\n __syncthreads();\n }\n}\n\ntorch::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 int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_heads = q.size(2);\n int 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 int smem = head_dim * head_dim * sizeof(float);\n\n delta_rule_kernel<<<blocks, threads, smem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n beta.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size, seq_len, num_heads, head_dim\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::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 extra_cuda_cflags=['-O3']\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: (3 / 3) correctness trials all passed.
Kernel runtime: 0.26 μs
Runtime stats: mean=0.26μs median=?μs std=0.00μs
Numerical precision: max_abs_err=6.68e-06 mean_abs_err=2.12e-07 max_rel_err=1.53e-03
Memory: 33.38 MB peak (ref: 33.54 MB, ratio: 0.9952x)
Kernel launches: 4 (ref: 3975, fusion ratio: 993.75)
SOL score: 0.0008
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (115 lines, 3,220 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 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 batch_size,
int seq_len,
int num_heads,
int head_dim
) {
int bh = blockIdx.x;
int b = bh / num_heads;
int h = bh % num_heads;
if (b >= batch_size) return;
extern __shared__ float state[]; // head_dim * head_dim
int D = head_dim;
for (int i = threadIdx.x; i < D * D; i += blockDim.x) {
state[i] = 0.0f;
}
__syncthreads();
for (int t = 0; t < seq_len; t++) {
float g = gate[(b * seq_len + t) * num_heads + h];
float be = beta[(b * seq_len + t) * num_heads + h];
// update state: state = g * state + be * outer(k, v)
for (int i = threadIdx.x; i < D * D; i += blockDim.x) {
int row = i / D;
int col = i % D;
float kv = k[((b * seq_len + t) * num_heads + h) * D + row] *
v[((b * seq_len + t) * num_heads + h) * D + col];
float old = state[i];
state[i] = g * old + be * kv;
}
__syncthreads();
// compute y = q @ state (sum over dim -2, i.e. q row vector * state)
for (int j = threadIdx.x; j < D; j += blockDim.x) {
float sum = 0.0f;
for (int i = 0; i < D; i++) {
float qval = q[((b * seq_len + t) * num_heads + h) * D + i];
sum += qval * state[i * D + j];
}
output[((b * seq_len + t) * num_heads + h) * D + j] = sum;
}
__syncthreads();
}
}
torch::Tensor delta_rule_cuda(
torch::Tensor q,
torch::Tensor k,
torch::Tensor v,
torch::Tensor gate,
torch::Tensor beta
) {
int batch_size = q.size(0);
int seq_len = q.size(1);
int num_heads = q.size(2);
int head_dim = q.size(3);
auto output = torch::zeros({batch_size, seq_len, num_heads, head_dim}, q.options());
int threads = 256;
int blocks = batch_size * num_heads;
int smem = head_dim * head_dim * 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>(),
batch_size, seq_len, num_heads, head_dim
);
return output;
}
"""
cpp_source = """
torch::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,
extra_cuda_cflags=['-O3']
)
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)