grok-4.3 · popcorn · pop_l123_st_gpt
incorrect 6_HyenaOperator.py
model
grok-4.3
turns / max
1 / 1
tool calls
1
tokens (total)
3043
wall clock
4007.6s
truncated
no
backend
cuda fp32
variant
popcorn
runtime
—
ref runtime
6.04 μs
speedup
—
started
2026-05-11T09:17:06Z
correctness issue: Output mismatch
timingkernelbench.timing
kernel runtime
—
ref runtime
6.04 μs
speedup
—
kernel mean / median / std
—
ref mean / median / std
6.04 / — / 5.03 μs
roofline / occupancyheuristic
dram bandwidth
—
dram util %
—
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
—
bottleneck
—
dominant pipe %
—
arithmetic intensity
—
ridge point
—
L1 hit %
—
L2 hit %
—
ld sectors / req
—
st sectors / req
—
regs / thread
—
smem / block
—
block size
—
peak bw
—
peak fp32 tflops
—
peak fp16 tflops
—
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    """
    Full Hyena operator (order 2): projects input into value (v), query-like (q), and key-like (k)
    branches, applies short depthwise convolutions to q and k, generates a long convolution filter
    via a small MLP, convolves v with the filter via FFT, then applies two rounds of elementwise
    gating. This is the core sequence mixing operator in StripedHyena, HyenaDNA, and Evo
    for subquadratic long-range dependency modeling.

    Args:
        d_model (int): Model dimension.
        seq_len (int): Maximum sequence length.
        order (int): Hyena recurrence order (number of gating rounds, typically 2).
        short_filter_size (int): Kernel size for short depthwise convolutions.
    """
    def __init__(self, d_model: int, seq_len: int, order: int, short_filter_size: int):
        super(Model, self).__init__()
        self.d_model = d_model
        self.seq_len = seq_len
        self.order = order
        self.fft_size = 2 * seq_len

        self.in_proj = nn.Linear(d_model, d_model * (order + 1), bias=True)

        self.short_convs = nn.ModuleList([
            nn.Conv1d(d_model, d_model, short_filter_size,
                      padding=short_filter_size // 2, groups=d_model)
            for _ in range(order)
        ])

        self.filter_mlp = nn.Sequential(
            nn.Linear(1, 64),
            nn.SiLU(),
            nn.Linear(64, d_model),
        )
        t = torch.linspace(0, 1, seq_len).unsqueeze(-1)
        self.register_buffer('filter_positions', t)

        self.out_proj = nn.Linear(d_model, d_model, bias=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, L, D = x.shape

        projected = self.in_proj(x)
        chunks = projected.chunk(self.order + 1, dim=-1)
        v = chunks[0].transpose(1, 2)
        gates = [c.transpose(1, 2) for c in chunks[1:]]

        for i in range(self.order):
            gates[i] = self.short_convs[i](gates[i])

        h = self.filter_mlp(self.filter_positions).transpose(0, 1)

        v_padded = F.pad(v, (0, self.seq_len))
        h_padded = F.pad(h, (0, self.seq_len))
        v_f = torch.fft.rfft(v_padded, dim=-1)
        h_f = torch.fft.rfft(h_padded, dim=-1)
        y_f = v_f * h_f.unsqueeze(0)
        y = torch.fft.irfft(y_f, n=self.fft_size, dim=-1)[..., :L]

        for gate in gates:
            y = y * gate

        y = y.transpose(1, 2)
        y = self.out_proj(y)
        return y

batch_size = 16
d_model = 256
seq_len = 8192
order = 2
short_filter_size = 3

def get_inputs():
    return [torch.randn(popcorn_pri.jitter_int(batch_size), seq_len, d_model)]

def get_init_inputs():
    return [d_model, seq_len, order, short_filter_size]
turn 04007.6s turn · 3621.4s LLM · 386.2s tools · tokens in=1,597 · out=983 · total=3,043 · FINAL
reasoning
The task is to replace the forward computation of the PyTorch Hyena operator model with a custom CUDA kernel that's faster but numerically equivalent. I need to replace the forward computation of the PyTorch Hyena operator model with a custom CUDA kernel that's faster but numerically equivalent. The goal is to write a complete Python file defining `ModelNew` that uses `torch.utils.cpp_extension.load_inline` to compile CUDA code.
call → submit_kernel
callsubmit_kernel { "kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\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#include <c10/cuda/CUDAGuard.h>\n\n__global__ void hyena_gating_kernel(const float* __restrict__ y, const float* __restrict__ g1, const float* __restrict__ g2,\n float* __restrict__ out, int B, int D, int L) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D * L;\n if (idx < total) {\n int l = idx % L;\n int d = (idx / L) % D;\n int b = idx / (L * D);\n float val = y[idx];\n float gate1 = g1[b * D * L + d * L + l];\n float gate2 = g2[b * D * L + d * L + l];\n out[idx] = val * gate1 * gate2;\n }\n}\n\ntorch::Tensor hyena_gating_cuda(torch::Tensor y, torch::Tensor g1, torch::Tensor g2) {\n const at::cuda::CUDAGuard device_guard(y.device());\n auto options = y.options();\n auto out = torch::empty_like(y);\n int B = y.size(0);\n int D = y.size(1);\n int L = y.size(2);\n int total = B * D * L;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n hyena_gating_kernel<<<blocks, threads>>>(y.data_ptr<float>(), g1.data_ptr<float>(), g2.data_ptr<float>(),\n out.data_ptr<float>(), B, D, L);\n return out;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor hyena_gating_cuda(torch::Tensor y, torch::Tensor g1, torch::Tensor g2);\n'''\n\nhyena_ext = load_inline(\n name='hyena_gating',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['hyena_gating_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, seq_len: int, order: int, short_filter_size: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.seq_len = seq_len\n self.order = order\n self.fft_size = 2 * seq_len\n\n self.in_proj = nn.Linear(d_model, d_model * (order + 1), bias=True)\n\n self.short_convs = nn.ModuleList([\n nn.Conv1d(d_model, d_model, short_filter_size,\n padding=short_filter_size // 2, groups=d_model)\n for _ in range(order)\n ])\n\n self.filter_mlp = nn.Sequential(\n nn.Linear(1, 64),\n nn.SiLU(),\n nn.Linear(64, d_model),\n )\n t = torch.linspace(0, 1, seq_len).unsqueeze(-1)\n self.register_buffer('filter_positions', t)\n\n self.out_proj = nn.Linear(d_model, d_model, bias=True)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n\n projected = self.in_proj(x)\n chunks = projected.chunk(self.order + 1, dim=-1)\n v = chunks[0].transpose(1, 2)\n gates = [c.transpose(1, 2) for c in chunks[1:]]\n\n for i in range(self.order):\n gates[i] = self.short_convs[i](gates[i])\n\n h = self.filter_mlp(self.filter_positions).transpose(0, 1)\n\n v_padded = F.pad(v, (0, self.seq_len))\n h_padded = F.pad(h, (0, self.seq_len))\n v_f = torch.fft.rfft(v_padded, dim=-1)\n h_f = torch.fft.rfft(h_padded, dim=-1)\n y_f = v_f * h_f.unsqueeze(0)\n y = torch.fft.irfft(y_f, n=self.fft_size, dim=-1)[..., :L]\n\n # Use custom CUDA kernel for gating\n y = hyena_ext.hyena_gating_cuda(y, gates[0], gates[1])\n\n y = y.transpose(1, 2)\n y = self.out_proj(y)\n return y\n" }
result ← submit_kernel (fail)
failsubmit_kernel submit_kernel FAILED: correctness check did not pass ((0 / 5) trials). correctness_issue: Output mismatch max_difference: ['52.522064', '55.500923', '51.063675', '54.225250', '56.443398'] avg_difference: ['4.310791', '4.294653', '4.417722', '4.308419', '4.354278']
final submitted kernel (107 lines, 3,483 chars) — full source, untruncated
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

cuda_source = '''
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <c10/cuda/CUDAGuard.h>

__global__ void hyena_gating_kernel(const float* __restrict__ y, const float* __restrict__ g1, const float* __restrict__ g2,
                                    float* __restrict__ out, int B, int D, int L) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total = B * D * L;
    if (idx < total) {
        int l = idx % L;
        int d = (idx / L) % D;
        int b = idx / (L * D);
        float val = y[idx];
        float gate1 = g1[b * D * L + d * L + l];
        float gate2 = g2[b * D * L + d * L + l];
        out[idx] = val * gate1 * gate2;
    }
}

torch::Tensor hyena_gating_cuda(torch::Tensor y, torch::Tensor g1, torch::Tensor g2) {
    const at::cuda::CUDAGuard device_guard(y.device());
    auto options = y.options();
    auto out = torch::empty_like(y);
    int B = y.size(0);
    int D = y.size(1);
    int L = y.size(2);
    int total = B * D * L;
    int threads = 256;
    int blocks = (total + threads - 1) / threads;
    hyena_gating_kernel<<<blocks, threads>>>(y.data_ptr<float>(), g1.data_ptr<float>(), g2.data_ptr<float>(),
                                              out.data_ptr<float>(), B, D, L);
    return out;
}
'''

cpp_source = '''
torch::Tensor hyena_gating_cuda(torch::Tensor y, torch::Tensor g1, torch::Tensor g2);
'''

hyena_ext = load_inline(
    name='hyena_gating',
    cpp_sources=[cpp_source],
    cuda_sources=[cuda_source],
    functions=['hyena_gating_cuda'],
    verbose=False
)

class ModelNew(nn.Module):
    def __init__(self, d_model: int, seq_len: int, order: int, short_filter_size: int):
        super(ModelNew, self).__init__()
        self.d_model = d_model
        self.seq_len = seq_len
        self.order = order
        self.fft_size = 2 * seq_len

        self.in_proj = nn.Linear(d_model, d_model * (order + 1), bias=True)

        self.short_convs = nn.ModuleList([
            nn.Conv1d(d_model, d_model, short_filter_size,
                      padding=short_filter_size // 2, groups=d_model)
            for _ in range(order)
        ])

        self.filter_mlp = nn.Sequential(
            nn.Linear(1, 64),
            nn.SiLU(),
            nn.Linear(64, d_model),
        )
        t = torch.linspace(0, 1, seq_len).unsqueeze(-1)
        self.register_buffer('filter_positions', t)

        self.out_proj = nn.Linear(d_model, d_model, bias=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, L, D = x.shape

        projected = self.in_proj(x)
        chunks = projected.chunk(self.order + 1, dim=-1)
        v = chunks[0].transpose(1, 2)
        gates = [c.transpose(1, 2) for c in chunks[1:]]

        for i in range(self.order):
            gates[i] = self.short_convs[i](gates[i])

        h = self.filter_mlp(self.filter_positions).transpose(0, 1)

        v_padded = F.pad(v, (0, self.seq_len))
        h_padded = F.pad(h, (0, self.seq_len))
        v_f = torch.fft.rfft(v_padded, dim=-1)
        h_f = torch.fft.rfft(h_padded, dim=-1)
        y_f = v_f * h_f.unsqueeze(0)
        y = torch.fft.irfft(y_f, n=self.fft_size, dim=-1)[..., :L]

        # Use custom CUDA kernel for gating
        y = hyena_ext.hyena_gating_cuda(y, gates[0], gates[1])

        y = y.transpose(1, 2)
        y = self.out_proj(y)
        return y