gpt-5.5-priority · popcorn · l123_single_gpt
correct 20_GatedDeltaNetLinearAttention.py
model
gpt-5.5-priority
turns / max
1 / 1
tool calls
1
tokens (total)
0
wall clock
—
truncated
no
backend
cuda fp32
variant
popcorn
runtime
0.07 μs
ref runtime
8.27 μs
speedup
111.31x
started
2026-05-05T02:32:11Z
timingkernelbench.timing
kernel runtime
0.07 μs
ref runtime
8.27 μs
speedup
111.31x
kernel mean / median / std
0.07 / — / 8.83e-04 μs
ref mean / median / std
8.27 / — / 0.78 μs
numerical precisioneval_kernel_against_ref
max abs error
5.72e-06
mean abs error
2.03e-07
max rel error
0.17
mean rel error
2.05e-06
gpu memoryextended_metrics.measure_memory
kernel peak
32.38 MB
ref peak
32.54 MB
kernel / ref
1.00x
kernel launches / fusiontorch.profiler
kernel launches
2
ref launches
3975
fusion ratio (ref / kernel)
1987.50x
total cuda time
58 μs
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.001
dram util %
0.1%
compute util %
0.0%
bottleneck
unknown
dominant pipe
None
arithmetic intensity
—
ridge point
20.00
roofline / occupancynsight_hardware_counters
dram bandwidth
4.31 GB/s
dram util %
0.1%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
2.2%
bottleneck
unknown
dominant pipe %
—
arithmetic intensity
—
ridge point
20.00
L1 hit %
—
L2 hit %
91.6%
ld sectors / req
1.80
st sectors / req
—
regs / thread
32
smem / block
1024 B
block size
32
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
1662.1%
short_scoreboard
247.8%
flagssubmit_kernel guard
excessive speedup
flagged
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 038.0s turn · 38.0s LLM · 0.0s tools · FINAL
reasoning
**Binding CUDA functions** I'm figuring out that binding to a function in C++ source is easier, but the host launch in C++ can’t see the kernel unless I declare a CUDA launcher. I need two sources: one for C++ with the function definitions and another for CUDA that defines the kernel. I also wonder about handling CPU evaluations — if there's no fallback allowed for CUDA, but that might not be a concern after all. I think I'm ready to submit this!
call → submit_kernel
callsubmit_kernel { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor delta_rule_forward_cuda(torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate,\n torch::Tensor beta);\n\ntorch::Tensor delta_rule_forward(torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate,\n torch::Tensor beta) {\n return delta_rule_forward_cuda(q, k, v, gate, beta);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <c10/cuda/CUDAStream.h>\n\n__global__ __launch_bounds__(32, 8)\nvoid delta_rule_kernel(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__ out,\n int B, int T, int H, int D) {\n const int lane = threadIdx.x; // one warp per (batch, head, output column)\n const int col = blockIdx.x % D;\n int tmp = blockIdx.x / D;\n const int h = tmp % H;\n const int b = tmp / H;\n\n float state_i = 0.0f; // element S[i, col], owned by lane i\n\n const int bh_base = (b * T * H + h) * D;\n const int gh_base = b * T * H + h;\n\n #pragma unroll 1\n for (int t = 0; t < T; ++t) {\n const int vec_base = bh_base + t * H * D;\n const int scalar_idx = gh_base + t * H;\n const float g = gate[scalar_idx];\n const float be = beta[scalar_idx];\n const float v_col = v[vec_base + col];\n\n float acc = 0.0f;\n if (lane < D) {\n state_i = g * state_i + be * k[vec_base + lane] * v_col;\n acc = q[vec_base + lane] * state_i;\n }\n\n // Warp reduction over the 24 contributing rows.\n acc += __shfl_down_sync(0xffffffffu, acc, 16);\n acc += __shfl_down_sync(0xffffffffu, acc, 8);\n acc += __shfl_down_sync(0xffffffffu, acc, 4);\n acc += __shfl_down_sync(0xffffffffu, acc, 2);\n acc += __shfl_down_sync(0xffffffffu, acc, 1);\n\n if (lane == 0) {\n out[vec_base + col] = acc;\n }\n }\n}\n\ntorch::Tensor delta_rule_forward_cuda(torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v,\n torch::Tensor gate,\n torch::Tensor beta) {\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 const int blocks = B * H * D;\n const dim3 grid(blocks);\n const dim3 threads(32);\n cudaStream_t stream = c10::cuda::getCurrentCUDAStream();\n\n delta_rule_kernel<<<grid, threads, 0, stream>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),\n gate.data_ptr<float>(), beta.data_ptr<float>(), out.data_ptr<float>(),\n B, T, H, D);\n\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"delta_rule_linear_attention_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"delta_rule_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\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,\n gate: torch.Tensor, beta: torch.Tensor) -> torch.Tensor:\n return _ext.delta_rule_forward(q, k, v, gate, beta)\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (5 / 5) correctness trials all passed. Kernel runtime: 0.07 μs Runtime stats: mean=0.07μs median=?μs std=0.00μs Numerical precision: max_abs_err=5.72e-06 mean_abs_err=2.03e-07 max_rel_err=1.67e-01 Memory: 32.38 MB peak (ref: 32.54 MB, ratio: 0.9951x) Kernel launches: 2 (ref: 3975, fusion ratio: 1987.5) SOL score: 0.0013 Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (121 lines, 3,912 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 delta_rule_forward_cuda(torch::Tensor q,
                                      torch::Tensor k,
                                      torch::Tensor v,
                                      torch::Tensor gate,
                                      torch::Tensor beta);

torch::Tensor delta_rule_forward(torch::Tensor q,
                                 torch::Tensor k,
                                 torch::Tensor v,
                                 torch::Tensor gate,
                                 torch::Tensor beta) {
    return delta_rule_forward_cuda(q, k, v, gate, beta);
}
"""

_cuda_src = r"""
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <c10/cuda/CUDAStream.h>

__global__ __launch_bounds__(32, 8)
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__ out,
                       int B, int T, int H, int D) {
    const int lane = threadIdx.x;  // one warp per (batch, head, output column)
    const int col = blockIdx.x % D;
    int tmp = blockIdx.x / D;
    const int h = tmp % H;
    const int b = tmp / H;

    float state_i = 0.0f;  // element S[i, col], owned by lane i

    const int bh_base = (b * T * H + h) * D;
    const int gh_base = b * T * H + h;

    #pragma unroll 1
    for (int t = 0; t < T; ++t) {
        const int vec_base = bh_base + t * H * D;
        const int scalar_idx = gh_base + t * H;
        const float g = gate[scalar_idx];
        const float be = beta[scalar_idx];
        const float v_col = v[vec_base + col];

        float acc = 0.0f;
        if (lane < D) {
            state_i = g * state_i + be * k[vec_base + lane] * v_col;
            acc = q[vec_base + lane] * state_i;
        }

        // Warp reduction over the 24 contributing rows.
        acc += __shfl_down_sync(0xffffffffu, acc, 16);
        acc += __shfl_down_sync(0xffffffffu, acc, 8);
        acc += __shfl_down_sync(0xffffffffu, acc, 4);
        acc += __shfl_down_sync(0xffffffffu, acc, 2);
        acc += __shfl_down_sync(0xffffffffu, acc, 1);

        if (lane == 0) {
            out[vec_base + col] = acc;
        }
    }
}

torch::Tensor delta_rule_forward_cuda(torch::Tensor q,
                                      torch::Tensor k,
                                      torch::Tensor v,
                                      torch::Tensor gate,
                                      torch::Tensor beta) {
    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);

    const int blocks = B * H * D;
    const dim3 grid(blocks);
    const dim3 threads(32);
    cudaStream_t stream = c10::cuda::getCurrentCUDAStream();

    delta_rule_kernel<<<grid, threads, 0, stream>>>(
        q.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(),
        gate.data_ptr<float>(), beta.data_ptr<float>(), out.data_ptr<float>(),
        B, T, H, D);

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return out;
}
"""

_ext = load_inline(
    name="delta_rule_linear_attention_ext_v1",
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=["delta_rule_forward"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    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, beta: torch.Tensor) -> torch.Tensor:
        return _ext.delta_rule_forward(q, k, v, gate, beta)