correct
4_MambaBlock.py
started
2026-05-11T21:04:35Z
timingkernelbench.timing
kernel mean / median / std
7.25 / — / 0.05 μs
ref mean / median / std
164.00 / — / 163.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
250.04x
energyNVML (pynvml)
ratio (ref / kernel)
12.33x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
27269.33 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Full Mamba block: RMSNorm -> linear expansion into two branches -> causal depthwise Conv1d ->
SiLU -> selective scan (input-dependent SSM) -> elementwise gate -> linear projection -> residual.
This is the complete Mamba architecture block as described in Gu & Dao (2023), used in Mamba,
Caduceus (bidirectional DNA), and various protein/genomic language models.
Args:
d_model (int): Model dimension.
d_state (int): SSM state dimension (N).
d_conv (int): Causal convolution kernel size.
expand (int): Expansion factor for inner dimension.
"""
def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):
super(Model, self).__init__()
self.d_model = d_model
self.d_inner = d_model * expand
self.d_state = d_state
self.d_conv = d_conv
self.norm = nn.RMSNorm(d_model)
self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)
self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,
padding=d_conv - 1, groups=self.d_inner, bias=True)
self.activation = nn.SiLU()
self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))
self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)
self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)
self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)
self.D = nn.Parameter(torch.ones(self.d_inner))
self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, L, D = x.shape
residual = x
x = self.norm(x)
xz = self.in_proj(x)
x_branch, z = xz.chunk(2, dim=-1)
x_branch = x_branch.transpose(1, 2)
x_branch = self.conv1d(x_branch)[..., :L]
x_branch = x_branch.transpose(1, 2)
x_branch = self.activation(x_branch)
N = self.d_state
delta = torch.nn.functional.softplus(self.proj_delta(x_branch))
B_t = self.proj_B(x_branch)
C_t = self.proj_C(x_branch)
A = -torch.exp(self.A_log)
dA = torch.exp(delta.unsqueeze(-1) * A.unsqueeze(0).unsqueeze(0))
dB = delta.unsqueeze(-1) * B_t.unsqueeze(2)
x_db = x_branch.unsqueeze(-1) * dB
h = torch.zeros(B, self.d_inner, N, device=x.device, dtype=x.dtype)
outputs = []
for t in range(L):
h = dA[:, t] * h + x_db[:, t]
y_t = (h * C_t[:, t].unsqueeze(1)).sum(dim=-1)
outputs.append(y_t)
y = torch.stack(outputs, dim=1)
y = y + x_branch * self.D.unsqueeze(0).unsqueeze(0)
z = self.activation(z)
y = y * z
y = self.out_proj(y)
y = y + residual
return y
batch_size = 16
d_model = 256
d_state = 16
d_conv = 4
expand = 2
seq_len = 2048
def get_inputs():
return [torch.randn(popcorn_pri.jitter_int(batch_size), popcorn_pri.jitter_int(seq_len), d_model)]
def get_init_inputs():
return [d_model, d_state, d_conv, expand]turn 066.7s turn · 2.9s LLM · 63.8s tools · tokens in=2,582 · out=6 · total=2,766
reasoning
The task is to replace the forward computation of this Mamba block with a custom CUDA kernel that's faster than the PyTorch reference while producing equivalent 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 1197.4s turn · 18.9s LLM · 178.5s tools · tokens in=2,999 · out=508 · total=4,030
reasoning
It's an H100, great for high performance.
The reference model uses a sequential Python loop for the SSM scan, which is slow because it's not parallelized. Since the SSM recurrence is associative, I can replace it with a work-efficient parallel prefix sum technique in a custom CUDA kernel. The H100 GPU is powerful for this.
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 selective_scan_kernel(\n const float* __restrict__ delta, // (B, L, D)\n const float* __restrict__ B_t, // (B, L, N)\n const float* __restrict__ C_t, // (B, L, N)\n const float* __restrict__ x_branch, // (B, L, D)\n const float* __restrict__ A, // (D, N) negative exp already\n const float* __restrict__ D_param, // (D,)\n float* __restrict__ y, // (B, L, D)\n int B, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[16]; // assume N<=16\n for(int n=0; n<N; n++) h[n] = 0.0f;\n\n const float* A_d = A + d * N;\n float Dd = D_param[d];\n\n for(int t=0; t<L; t++) {\n float del = delta[b*L*D + t*D + d];\n float del_exp = __expf(del); // wait, no: delta is already softplus, dA = exp(delta * A) but A negative\n // actually in ref: A = -exp(A_log), dA = exp(delta * A) = exp( - delta * exp(A_log) )\n // but passed delta already, wait let's match ref\n // I need to pass precomputed or adjust\n }\n}\n'''\n\ncpp_source = '''\ntorch::Tensor selective_scan(torch::Tensor delta, torch::Tensor B_t, torch::Tensor C_t, torch::Tensor x_branch, torch::Tensor A, torch::Tensor D);\n'''\n\nmodule = load_inline(\n name='mamba_scan',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['selective_scan'],\n verbose=True\n)\nprint(\"Compiled successfully\")\n"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: ImportError.
ImportError: /scratch/abaner/KernelBench/runs/pop_l123_all_gpt/popcorn/grok-4.3/level_3_problem_4_cache/k_344eb38a0831/mamba_scan/mamba_scan.so: undefined symbol: _Z14selective_scanN2at6TensorES0_S0_S0_S0_S0_
turn 2182.2s turn · 12.6s LLM · 169.6s tools · tokens in=4,118 · out=724 · total=5,073
reasoning
The cpp source is incomplete. I need a proper wrapper function definition.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta, // (B, L, D)\n const float* Bt, // (B, L, N)\n const float* Ct, // (B, L, N)\n const float* xbranch, // (B, L, D)\n const float* A, // (D, N) precomputed negative exp(A_log)\n const float* Dp, // (D,)\n float* y_out, // (B, L, D)\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float dd = Dp[d];\n float yt = dd * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmodule = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=True\n)\nprint(\"Compiled successfully\")\n"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: ModelNew class not found or syntax error prevented execution.
Compiled successfully
turn 3212.3s turn · 10.7s LLM · 201.6s tools · tokens in=5,098 · out=1,113 · total=6,254
reasoning
It compiled the module but the whole thing is not defining ModelNew. The kernel_code must define the full ModelNew class.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta,\n const float* Bt,\n const float* Ct,\n const float* xbranch,\n const float* A,\n const float* Dp,\n float* y_out,\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float yt = Dp[d] * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmamba_module = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.d_inner = d_model * expand\n self.d_state = d_state\n self.d_conv = d_conv\n\n self.norm = nn.RMSNorm(d_model)\n self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)\n self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,\n padding=d_conv - 1, groups=self.d_inner, bias=True)\n self.activation = nn.SiLU()\n\n self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))\n self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)\n self.D = nn.Parameter(torch.ones(self.d_inner))\n\n self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n residual = x\n x = self.norm(x)\n\n xz = self.in_proj(x)\n x_branch, z = xz.chunk(2, dim=-1)\n\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.conv1d(x_branch)[..., :L]\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.activation(x_branch)\n\n delta = torch.nn.functional.softplus(self.proj_delta(x_branch))\n B_t = self.proj_B(x_branch)\n C_t = self.proj_C(x_branch)\n\n A = -torch.exp(self.A_log)\n\n y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)\n\n z = self.activation(z)\n y = y * z\n y = self.out_proj(y)\n y = y + residual\n return y\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 4102.3s turn · 9.8s LLM · 92.5s tools · tokens in=6,271 · out=1,114 · total=7,392
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta,\n const float* Bt,\n const float* Ct,\n const float* xbranch,\n const float* A,\n const float* Dp,\n float* y_out,\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float yt = Dp[d] * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmamba_module = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.d_inner = d_model * expand\n self.d_state = d_state\n self.d_conv = d_conv\n\n self.norm = nn.RMSNorm(d_model)\n self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)\n self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,\n padding=d_conv - 1, groups=self.d_inner, bias=True)\n self.activation = nn.SiLU()\n\n self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))\n self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)\n self.D = nn.Parameter(torch.ones(self.d_inner))\n\n self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n residual = x\n x = self.norm(x)\n\n xz = self.in_proj(x)\n x_branch, z = xz.chunk(2, dim=-1)\n\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.conv1d(x_branch)[..., :L]\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.activation(x_branch)\n\n delta = torch.nn.functional.softplus(self.proj_delta(x_branch))\n B_t = self.proj_B(x_branch)\n C_t = self.proj_C(x_branch)\n\n A = -torch.exp(self.A_log)\n\n y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)\n\n z = self.activation(z)\n y = y * z\n y = self.out_proj(y)\n y = y + residual\n return y\n"
}
result ← run_correctness (fail)
failrun_correctness
run_correctness FAILED: (0 / 3) trials did not all match.
correctness_issue: Output mismatch
max_difference: ['0.433353', '0.420082', '0.431655']
avg_difference: ['0.046452', '0.046472', '0.046413']
turn 5 · 1 tool call(s) · 175.2s turn · 63.2s LLM · tokens in=7,465 · out=1,165 · total=10,290 · 6,040 chars (click to expand)
turn 5175.2s turn · 63.2s LLM · 112.0s tools · tokens in=7,465 · out=1,165 · total=10,290
reasoning
There's a mismatch. Need to debug the kernel.
I noticed a mismatch in the CUDA kernel implementation compared to the PyTorch reference. The dimensions seem correct: delta is (B,L,D), A and B_t are appropriately unsqueezed and broadc broadcasting to (B,L,D,N), and the computations for dA, dB, and the accumulation in h match the reference: dA = exp(delta * A), dB = delta * B_t, then h = dA * h + x_branch * dB, and finally y_t = (h * C_t).sum(-1) + D * x_branch.
Despite this, there's a large numerical difference of 0.0001 or something, but accesses are full. Indexing appears row-major correct for both x_branch, B_t, and parameters A, B, C, D which are (D,N), (D,N), (D,N), (D) I think D is (D,) or something, no in code 1D.
The issue was traced back possibly due to floating point accumulation differences or block/thread configuration, but threads 256, blocks 32 sufficient for B=16, D=512, N=16.
I suspected the kernel assumes float32, inputs are float32.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta,\n const float* Bt,\n const float* Ct,\n const float* xbranch,\n const float* A,\n const float* Dp,\n float* y_out,\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float yt = Dp[d] * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n delta = delta.contiguous();\n Bt = Bt.contiguous();\n Ct = Ct.contiguous();\n xbranch = xbranch.contiguous();\n A = A.contiguous();\n Dp = Dp.contiguous();\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n cudaDeviceSynchronize();\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmamba_module = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.d_inner = d_model * expand\n self.d_state = d_state\n self.d_conv = d_conv\n\n self.norm = nn.RMSNorm(d_model)\n self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)\n self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,\n padding=d_conv - 1, groups=self.d_inner, bias=True)\n self.activation = nn.SiLU()\n\n self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))\n self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)\n self.D = nn.Parameter(torch.ones(self.d_inner))\n\n self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n residual = x\n x = self.norm(x)\n\n xz = self.in_proj(x)\n x_branch, z = xz.chunk(2, dim=-1)\n\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.conv1d(x_branch)[..., :L]\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.activation(x_branch)\n\n delta = torch.nn.functional.softplus(self.proj_delta(x_branch))\n B_t = self.proj_B(x_branch)\n C_t = self.proj_C(x_branch)\n\n A = -torch.exp(self.A_log)\n\n y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)\n\n z = self.activation(z)\n y = y * z\n y = self.out_proj(y)\n y = y + residual\n return y\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 676.4s turn · 12.8s LLM · 63.6s tools · tokens in=10,307 · out=1,166 · total=11,481
reasoning
Still same. Let's check correctness again.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta,\n const float* Bt,\n const float* Ct,\n const float* xbranch,\n const float* A,\n const float* Dp,\n float* y_out,\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float yt = Dp[d] * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n delta = delta.contiguous();\n Bt = Bt.contiguous();\n Ct = Ct.contiguous();\n xbranch = xbranch.contiguous();\n A = A.contiguous();\n Dp = Dp.contiguous();\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n cudaDeviceSynchronize();\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmamba_module = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.d_inner = d_model * expand\n self.d_state = d_state\n self.d_conv = d_conv\n\n self.norm = nn.RMSNorm(d_model)\n self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)\n self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,\n padding=d_conv - 1, groups=self.d_inner, bias=True)\n self.activation = nn.SiLU()\n\n self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))\n self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)\n self.D = nn.Parameter(torch.ones(self.d_inner))\n\n self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n residual = x\n x = self.norm(x)\n\n xz = self.in_proj(x)\n x_branch, z = xz.chunk(2, dim=-1)\n\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.conv1d(x_branch)[..., :L]\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.activation(x_branch)\n\n delta = torch.nn.functional.softplus(self.proj_delta(x_branch))\n B_t = self.proj_B(x_branch)\n C_t = self.proj_C(x_branch)\n\n A = -torch.exp(self.A_log)\n\n y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)\n\n z = self.activation(z)\n y = y * z\n y = self.out_proj(y)\n y = y + residual\n return y\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=6.90e-09 max_rel_err=5.32e-02
turn 7142.3s turn · 11.9s LLM · 130.4s tools · tokens in=11,541 · out=1,165 · total=12,752 · FINAL
reasoning
Great, now it passes! The contiguous and sync helped? Or previous had issue but now good. Max err 4e-7, perfect within 1e-4.
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 = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mamba_scan_kernel(\n const float* delta,\n const float* Bt,\n const float* Ct,\n const float* xbranch,\n const float* A,\n const float* Dp,\n float* y_out,\n int Bsz, int L, int D, int N\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= Bsz * D) return;\n int b = idx / D;\n int d = idx % D;\n\n float h[32];\n for (int n = 0; n < N; ++n) h[n] = 0.0f;\n\n for (int t = 0; t < L; ++t) {\n float del = delta[(b * L + t) * D + d];\n float xb = xbranch[(b * L + t) * D + d];\n float yt = Dp[d] * xb;\n for (int n = 0; n < N; ++n) {\n float aa = A[d * N + n];\n float bb = Bt[(b * L + t) * N + n];\n float cc = Ct[(b * L + t) * N + n];\n float dA = expf(del * aa);\n float dB = del * bb;\n h[n] = dA * h[n] + xb * dB;\n yt += h[n] * cc;\n }\n y_out[(b * L + t) * D + d] = yt;\n }\n}\n\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {\n int B = delta.size(0);\n int L = delta.size(1);\n int D = delta.size(2);\n int N = Bt.size(2);\n delta = delta.contiguous();\n Bt = Bt.contiguous();\n Ct = Ct.contiguous();\n xbranch = xbranch.contiguous();\n A = A.contiguous();\n Dp = Dp.contiguous();\n auto y = torch::empty({B, L, D}, delta.options());\n int threads = 256;\n int blocks = (B * D + threads - 1) / threads;\n mamba_scan_kernel<<<blocks, threads>>>(\n delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),\n xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),\n y.data_ptr<float>(), B, L, D, N);\n cudaDeviceSynchronize();\n return y;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,\n torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);\n'''\n\nmamba_module = load_inline(\n name='mamba_scan',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['mamba_scan'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):\n super(ModelNew, self).__init__()\n self.d_model = d_model\n self.d_inner = d_model * expand\n self.d_state = d_state\n self.d_conv = d_conv\n\n self.norm = nn.RMSNorm(d_model)\n self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)\n self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,\n padding=d_conv - 1, groups=self.d_inner, bias=True)\n self.activation = nn.SiLU()\n\n self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))\n self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)\n self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)\n self.D = nn.Parameter(torch.ones(self.d_inner))\n\n self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n B, L, D = x.shape\n residual = x\n x = self.norm(x)\n\n xz = self.in_proj(x)\n x_branch, z = xz.chunk(2, dim=-1)\n\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.conv1d(x_branch)[..., :L]\n x_branch = x_branch.transpose(1, 2)\n x_branch = self.activation(x_branch)\n\n delta = torch.nn.functional.softplus(self.proj_delta(x_branch))\n B_t = self.proj_B(x_branch)\n C_t = self.proj_C(x_branch)\n\n A = -torch.exp(self.A_log)\n\n y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)\n\n z = self.activation(z)\n y = y * z\n y = self.out_proj(y)\n y = y + residual\n return y\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (3 / 3) correctness trials all passed.
Kernel runtime: 7.25 μs
Runtime stats: mean=7.25μs median=?μs std=0.05μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=6.90e-09 max_rel_err=5.32e-02
Memory: 554.25 MB peak (ref: 3690.75 MB, ratio: 0.1502x)
Kernel launches: 107 (ref: 26754, fusion ratio: 250.0374)
Energy: 725.68 mJ/run (ref: 8950.94 mJ, ratio: 12.3346x)
SOL score: 1.0
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (129 lines, 4,064 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = r'''
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void mamba_scan_kernel(
const float* delta,
const float* Bt,
const float* Ct,
const float* xbranch,
const float* A,
const float* Dp,
float* y_out,
int Bsz, int L, int D, int N
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= Bsz * D) return;
int b = idx / D;
int d = idx % D;
float h[32];
for (int n = 0; n < N; ++n) h[n] = 0.0f;
for (int t = 0; t < L; ++t) {
float del = delta[(b * L + t) * D + d];
float xb = xbranch[(b * L + t) * D + d];
float yt = Dp[d] * xb;
for (int n = 0; n < N; ++n) {
float aa = A[d * N + n];
float bb = Bt[(b * L + t) * N + n];
float cc = Ct[(b * L + t) * N + n];
float dA = expf(del * aa);
float dB = del * bb;
h[n] = dA * h[n] + xb * dB;
yt += h[n] * cc;
}
y_out[(b * L + t) * D + d] = yt;
}
}
torch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,
torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp) {
int B = delta.size(0);
int L = delta.size(1);
int D = delta.size(2);
int N = Bt.size(2);
delta = delta.contiguous();
Bt = Bt.contiguous();
Ct = Ct.contiguous();
xbranch = xbranch.contiguous();
A = A.contiguous();
Dp = Dp.contiguous();
auto y = torch::empty({B, L, D}, delta.options());
int threads = 256;
int blocks = (B * D + threads - 1) / threads;
mamba_scan_kernel<<<blocks, threads>>>(
delta.data_ptr<float>(), Bt.data_ptr<float>(), Ct.data_ptr<float>(),
xbranch.data_ptr<float>(), A.data_ptr<float>(), Dp.data_ptr<float>(),
y.data_ptr<float>(), B, L, D, N);
cudaDeviceSynchronize();
return y;
}
'''
cpp_source = '''
torch::Tensor mamba_scan(torch::Tensor delta, torch::Tensor Bt, torch::Tensor Ct,
torch::Tensor xbranch, torch::Tensor A, torch::Tensor Dp);
'''
mamba_module = load_inline(
name='mamba_scan',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['mamba_scan'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, d_model: int, d_state: int, d_conv: int, expand: int):
super(ModelNew, self).__init__()
self.d_model = d_model
self.d_inner = d_model * expand
self.d_state = d_state
self.d_conv = d_conv
self.norm = nn.RMSNorm(d_model)
self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)
self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv,
padding=d_conv - 1, groups=self.d_inner, bias=True)
self.activation = nn.SiLU()
self.A_log = nn.Parameter(torch.randn(self.d_inner, d_state))
self.proj_B = nn.Linear(self.d_inner, d_state, bias=False)
self.proj_C = nn.Linear(self.d_inner, d_state, bias=False)
self.proj_delta = nn.Linear(self.d_inner, self.d_inner, bias=True)
self.D = nn.Parameter(torch.ones(self.d_inner))
self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, L, D = x.shape
residual = x
x = self.norm(x)
xz = self.in_proj(x)
x_branch, z = xz.chunk(2, dim=-1)
x_branch = x_branch.transpose(1, 2)
x_branch = self.conv1d(x_branch)[..., :L]
x_branch = x_branch.transpose(1, 2)
x_branch = self.activation(x_branch)
delta = torch.nn.functional.softplus(self.proj_delta(x_branch))
B_t = self.proj_B(x_branch)
C_t = self.proj_C(x_branch)
A = -torch.exp(self.A_log)
y = mamba_module.mamba_scan(delta, B_t, C_t, x_branch, A, self.D)
z = self.activation(z)
y = y * z
y = self.out_proj(y)
y = y + residual
return y