correct
24_KimiDeltaAttentionChannelwise.py
started
2026-05-05T00:06:52Z
timingkernelbench.timing
kernel mean / median / std
0.04 / — / 5.93e-04 μs
ref mean / median / std
6.04 / — / 0.55 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
1411.50x
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 061.1s turn · 61.1s LLM · 0.0s tools · FINAL
reasoning
**Evaluating CUDA and PyBind settings**
I'm considering setting `extra_cuda_cflags` for CUDA, like `-O3` and `--fmad=false`. I need to ensure that the module load time isn't too high and use a unique name for `load_inline`. There's a potential issue where `load_inline` might auto-bind functions from C++ sources only. The declaration seems fine since the definition is linked in CUDA. I’ll include necessary headers carefully to avoid nvcc issues. Lastly, defining the model with no arguments in `__init__` should work well.
**Designing a Python class**
I need to create a Python class that doesn’t take any constructor arguments. I’ll define it with `def __init__(self): super().__init__()` to initialize it properly. It's pretty straightforward, but I want to ensure I have it set up correctly without any complications. Once I’m done, I can think about submitting it! Simple and clean—hopefully, it works as intended!
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor gated_delta_forward(torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/types.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void gated_delta_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n const float* __restrict__ gate,\n float* __restrict__ out,\n int T, int H, int D) {\n const int j = blockIdx.x; // output/value channel\n const int h = blockIdx.y;\n const int b = blockIdx.z;\n const int lane = threadIdx.x; // key/query channel within a warp\n const unsigned mask = 0xffffffffu;\n\n float s = 0.0f; // state[lane, j] for this (b,h,j)\n\n for (int t = 0; t < T; ++t) {\n const int base = ((b * T + t) * H + h) * D;\n\n float gt = 0.0f;\n float vv = 0.0f;\n if (lane == 0) {\n gt = gate[base + j];\n vv = v[base + j];\n }\n gt = __shfl_sync(mask, gt, 0);\n vv = __shfl_sync(mask, vv, 0);\n\n float acc = 0.0f;\n if (lane < D) {\n const float kval = k[base + lane];\n const float qval = q[base + lane];\n const float kv = kval * vv;\n const float decayed = gt * s;\n s = decayed + kv;\n acc = qval * s;\n }\n\n // Sum over the key/query dimension to produce y[t, j].\n acc += __shfl_down_sync(mask, acc, 16);\n acc += __shfl_down_sync(mask, acc, 8);\n acc += __shfl_down_sync(mask, acc, 4);\n acc += __shfl_down_sync(mask, acc, 2);\n acc += __shfl_down_sync(mask, acc, 1);\n\n if (lane == 0) {\n out[base + j] = acc;\n }\n }\n}\n\ntorch::Tensor gated_delta_forward(torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate) {\n const at::cuda::CUDAGuard device_guard(q.device());\n const int B = (int)q.size(0);\n const int T = (int)q.size(1);\n const int H = (int)q.size(2);\n const int D = (int)q.size(3);\n\n auto out = torch::empty_like(q);\n\n dim3 grid(D, H, B);\n dim3 block(32);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n gated_delta_kernel<<<grid, block, 0, stream>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), gate.data_ptr<float>(),\n out.data_ptr<float>(), T, H, D);\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"gated_delta_attention_ext_v1\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"gated_delta_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--fmad=false\"],\n with_cuda=True,\n verbose=False,\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:\n return _ext.gated_delta_forward(q, k, v, gate)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.04 μs
Runtime stats: mean=0.04μs median=?μs std=0.00μs
Numerical precision: max_abs_err=5.72e-06 mean_abs_err=2.77e-07 max_rel_err=2.42e-02
Memory: 33.47 MB peak (ref: 33.63 MB, ratio: 0.9952x)
Kernel launches: 2 (ref: 2823, fusion ratio: 1411.5)
SOL score: 0.003
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (110 lines, 3,422 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
torch::Tensor gated_delta_forward(torch::Tensor q,
torch::Tensor k,
torch::Tensor v,
torch::Tensor gate);
"""
_cuda_src = r"""
#include <torch/types.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void gated_delta_kernel(const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ v,
const float* __restrict__ gate,
float* __restrict__ out,
int T, int H, int D) {
const int j = blockIdx.x; // output/value channel
const int h = blockIdx.y;
const int b = blockIdx.z;
const int lane = threadIdx.x; // key/query channel within a warp
const unsigned mask = 0xffffffffu;
float s = 0.0f; // state[lane, j] for this (b,h,j)
for (int t = 0; t < T; ++t) {
const int base = ((b * T + t) * H + h) * D;
float gt = 0.0f;
float vv = 0.0f;
if (lane == 0) {
gt = gate[base + j];
vv = v[base + j];
}
gt = __shfl_sync(mask, gt, 0);
vv = __shfl_sync(mask, vv, 0);
float acc = 0.0f;
if (lane < D) {
const float kval = k[base + lane];
const float qval = q[base + lane];
const float kv = kval * vv;
const float decayed = gt * s;
s = decayed + kv;
acc = qval * s;
}
// Sum over the key/query dimension to produce y[t, j].
acc += __shfl_down_sync(mask, acc, 16);
acc += __shfl_down_sync(mask, acc, 8);
acc += __shfl_down_sync(mask, acc, 4);
acc += __shfl_down_sync(mask, acc, 2);
acc += __shfl_down_sync(mask, acc, 1);
if (lane == 0) {
out[base + j] = acc;
}
}
}
torch::Tensor gated_delta_forward(torch::Tensor q,
torch::Tensor k,
torch::Tensor v,
torch::Tensor gate) {
const at::cuda::CUDAGuard device_guard(q.device());
const int B = (int)q.size(0);
const int T = (int)q.size(1);
const int H = (int)q.size(2);
const int D = (int)q.size(3);
auto out = torch::empty_like(q);
dim3 grid(D, H, B);
dim3 block(32);
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
gated_delta_kernel<<<grid, block, 0, stream>>>(
q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), gate.data_ptr<float>(),
out.data_ptr<float>(), T, H, D);
return out;
}
"""
_ext = load_inline(
name="gated_delta_attention_ext_v1",
cpp_sources=[_cpp_src],
cuda_sources=[_cuda_src],
functions=["gated_delta_forward"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--fmad=false"],
with_cuda=True,
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
return _ext.gated_delta_forward(q, k, v, gate)