correct
24_KimiDeltaAttentionChannelwise.py
started
2026-05-11T17:36:20Z
timingkernelbench.timing
kernel mean / median / std
0.26 / — / 4.48e-04 μs
ref mean / median / std
6.16 / — / 0.41 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
705.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):
"""
Channel-wise gated delta attention recurrence.
The recurrent state decays independently for each output channel, which
makes the update closer to channel-gated delta attention variants used in
fast long-context baselines.
"""
def __init__(self):
super().__init__()
def forward(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
gate: 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(-2)
kv_outer = k[:, t].unsqueeze(-1) * v[:, t].unsqueeze(-2)
state = gate_t * state + 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), p.jitter_int(head_dim, align=8), dtype=torch.float32))
return [q, k, v, gate]
def get_init_inputs():
return []
turn 055.0s turn · 24.9s LLM · 30.1s tools · tokens in=2,150 · out=6 · total=3,181
reasoning
The task is to replace the forward computation of this PyTorch model with a custom CUDA kernel. The model performs a channel-wise gated delta attention recurrence.
I need to replace the forward computation of the PyTorch model with a custom CUDA kernel. The task involves creating a ModelNew class that mimics the original Model's behavior but uses a faster CUDA implementation for the forward pass.
The original forward pass implements a channel-wise gated delta attention recurrence. It loops over the sequence length, 128 steps, maintaining a shared state across time steps. This state is batch-dependent, batch x heads x head_dim x head_dim, about 4k elements per batch.
To speed it up, I'll parallelize over batch and heads, and implement the recurrence using 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 1143.4s turn · 13.4s LLM · 130.0s tools · tokens in=3,414 · out=879 · total=4,449
reasoning
H100, good. Now, 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 gated_delta_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\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 int d = head_dim;\n\n extern __shared__ float state[];\n \n // Initialize state to 0\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 // Update state: state[i][j] = gate[b,h,t,j] * state[i][j] + k[b,h,t,i] * v[b,h,t,j]\n for (int idx = threadIdx.x; idx < d * d; idx += blockDim.x) {\n int i = idx / d;\n int j = idx % d;\n float g = gate[((b * seq_len + t) * num_heads + h) * d + j];\n float kv = k[((b * seq_len + t) * num_heads + h) * d + i] * \n v[((b * seq_len + t) * num_heads + h) * d + j];\n state[idx] = g * state[idx] + kv;\n }\n __syncthreads();\n\n // Compute y: y[j] = sum_i q[b,h,t,i] * state[i][j]\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 sum += q[((b * seq_len + t) * num_heads + h) * d + i] * 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 gated_delta_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate\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 bh = batch_size * num_heads;\n int threads = 256; // enough for d=24, 576 elements\n size_t shmem = head_dim * head_dim * sizeof(float);\n\n gated_delta_attention_kernel<<<bh, threads, shmem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size,\n seq_len,\n num_heads,\n head_dim\n );\n\n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor gated_delta_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate);\n'''\n\nmodule = load_inline(\n name='gated_delta_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['gated_delta_attention_cuda'],\n verbose=True\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):\n return self.module.gated_delta_attention_cuda(q, k, v, gate)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 230.4s turn · 9.6s LLM · 20.8s tools · tokens in=4,466 · out=880 · total=5,353
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 gated_delta_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\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 int d = head_dim;\n\n extern __shared__ float state[];\n \n // Initialize state to 0\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 // Update state: state[i][j] = gate[b,h,t,j] * state[i][j] + k[b,h,t,i] * v[b,h,t,j]\n for (int idx = threadIdx.x; idx < d * d; idx += blockDim.x) {\n int i = idx / d;\n int j = idx % d;\n float g = gate[((b * seq_len + t) * num_heads + h) * d + j];\n float kv = k[((b * seq_len + t) * num_heads + h) * d + i] * \n v[((b * seq_len + t) * num_heads + h) * d + j];\n state[idx] = g * state[idx] + kv;\n }\n __syncthreads();\n\n // Compute y: y[j] = sum_i q[b,h,t,i] * state[i][j]\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 sum += q[((b * seq_len + t) * num_heads + h) * d + i] * 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 gated_delta_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate\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 bh = batch_size * num_heads;\n int threads = 256; // enough for d=24, 576 elements\n size_t shmem = head_dim * head_dim * sizeof(float);\n\n gated_delta_attention_kernel<<<bh, threads, shmem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size,\n seq_len,\n num_heads,\n head_dim\n );\n\n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor gated_delta_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate);\n'''\n\nmodule = load_inline(\n name='gated_delta_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['gated_delta_attention_cuda'],\n verbose=True\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):\n return self.module.gated_delta_attention_cuda(q, k, v, gate)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=9.54e-06 mean_abs_err=4.36e-07 max_rel_err=2.56e-02
turn 389.7s turn · 10.4s LLM · 79.3s tools · tokens in=5,413 · out=879 · total=6,353 · FINAL
reasoning
Correct! Now, to check if faster, but since we submit with submit_kernel, which will time it.
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 gated_delta_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\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 int d = head_dim;\n\n extern __shared__ float state[];\n \n // Initialize state to 0\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 // Update state: state[i][j] = gate[b,h,t,j] * state[i][j] + k[b,h,t,i] * v[b,h,t,j]\n for (int idx = threadIdx.x; idx < d * d; idx += blockDim.x) {\n int i = idx / d;\n int j = idx % d;\n float g = gate[((b * seq_len + t) * num_heads + h) * d + j];\n float kv = k[((b * seq_len + t) * num_heads + h) * d + i] * \n v[((b * seq_len + t) * num_heads + h) * d + j];\n state[idx] = g * state[idx] + kv;\n }\n __syncthreads();\n\n // Compute y: y[j] = sum_i q[b,h,t,i] * state[i][j]\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 sum += q[((b * seq_len + t) * num_heads + h) * d + i] * 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 gated_delta_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate\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 bh = batch_size * num_heads;\n int threads = 256; // enough for d=24, 576 elements\n size_t shmem = head_dim * head_dim * sizeof(float);\n\n gated_delta_attention_kernel<<<bh, threads, shmem>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n gate.data_ptr<float>(),\n output.data_ptr<float>(),\n batch_size,\n seq_len,\n num_heads,\n head_dim\n );\n\n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor gated_delta_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate);\n'''\n\nmodule = load_inline(\n name='gated_delta_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['gated_delta_attention_cuda'],\n verbose=True\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):\n return self.module.gated_delta_attention_cuda(q, k, v, gate)\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=9.54e-06 mean_abs_err=4.36e-07 max_rel_err=2.56e-02
Memory: 0.47 MB peak (ref: 0.63 MB, ratio: 0.7453x)
Kernel launches: 4 (ref: 2823, fusion ratio: 705.75)
SOL score: 0.001
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (110 lines, 3,075 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 gated_delta_attention_kernel(
const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ v,
const float* __restrict__ gate,
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;
int d = head_dim;
extern __shared__ float state[];
// Initialize state to 0
for (int i = threadIdx.x; i < d * d; i += blockDim.x) {
state[i] = 0.0f;
}
__syncthreads();
for (int t = 0; t < seq_len; t++) {
// Update state: state[i][j] = gate[b,h,t,j] * state[i][j] + k[b,h,t,i] * v[b,h,t,j]
for (int idx = threadIdx.x; idx < d * d; idx += blockDim.x) {
int i = idx / d;
int j = idx % d;
float g = gate[((b * seq_len + t) * num_heads + h) * d + j];
float kv = k[((b * seq_len + t) * num_heads + h) * d + i] *
v[((b * seq_len + t) * num_heads + h) * d + j];
state[idx] = g * state[idx] + kv;
}
__syncthreads();
// Compute y: y[j] = sum_i q[b,h,t,i] * state[i][j]
for (int j = threadIdx.x; j < d; j += blockDim.x) {
float sum = 0.0f;
for (int i = 0; i < d; i++) {
sum += q[((b * seq_len + t) * num_heads + h) * d + i] * state[i * d + j];
}
output[((b * seq_len + t) * num_heads + h) * d + j] = sum;
}
__syncthreads();
}
}
torch::Tensor gated_delta_attention_cuda(
torch::Tensor q,
torch::Tensor k,
torch::Tensor v,
torch::Tensor gate
) {
auto batch_size = q.size(0);
auto seq_len = q.size(1);
auto num_heads = q.size(2);
auto head_dim = q.size(3);
auto output = torch::zeros({batch_size, seq_len, num_heads, head_dim}, q.options());
int bh = batch_size * num_heads;
int threads = 256; // enough for d=24, 576 elements
size_t shmem = head_dim * head_dim * sizeof(float);
gated_delta_attention_kernel<<<bh, threads, shmem>>>(
q.data_ptr<float>(),
k.data_ptr<float>(),
v.data_ptr<float>(),
gate.data_ptr<float>(),
output.data_ptr<float>(),
batch_size,
seq_len,
num_heads,
head_dim
);
return output;
}
'''
cpp_source = '''
torch::Tensor gated_delta_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor gate);
'''
module = load_inline(
name='gated_delta_attention',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['gated_delta_attention_cuda'],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.module = module
def forward(self, q, k, v, gate):
return self.module.gated_delta_attention_cuda(q, k, v, gate)