correct
95_Matmul_Add_Swish_Tanh_GELU_Hardtanh.py
started
2026-05-05T00:18:55Z
timingkernelbench.timing
kernel mean / median / std
2.72 / — / 0.01 μs
ref mean / median / std
2.84 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
3.20x
energyNVML (pynvml)
ratio (ref / kernel)
0.17x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1256.58 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):
"""
Simple model that performs a matrix multiplication, adds a value, applies Swish, Tanh, GELU, and Hardtanh activation functions.
"""
def __init__(self, in_features, out_features, add_value_shape):
super(Model, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.add_value = nn.Parameter(torch.randn(add_value_shape))
def forward(self, x):
x = self.matmul(x)
x = x + self.add_value
x = torch.sigmoid(x) * x # Swish
x = torch.tanh(x)
x = torch.nn.functional.gelu(x) # GELU
x = torch.nn.functional.hardtanh(x, min_val=-1, max_val=1) # Hardtanh
return x
batch_size = 1024
in_features = 8192
out_features = 8192
add_value_shape = (out_features,)
def get_inputs():
return [torch.rand(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, add_value_shape]turn 046.8s turn · 46.8s LLM · 0.0s tools · FINAL
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\nvoid activation_launch(torch::Tensor y);\n\ntorch::Tensor fused_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n // Combine the Linear bias and the extra add_value vector, then use addmm for\n // the GEMM. The remaining elementwise activation chain is fused in CUDA.\n auto combined_bias = at::add(bias, add_value);\n auto y = at::addmm(combined_bias, x, weight.t());\n activation_launch(y);\n return y;\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n\n__global__ void activation_kernel(float* __restrict__ p, int64_t n) {\n int64_t idx = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;\n int64_t stride = (int64_t)blockDim.x * gridDim.x;\n const float inv_sqrt2 = 0.70710678118654752440f;\n for (int64_t i = idx; i < n; i += stride) {\n float x = p[i];\n // Swish: x * sigmoid(x)\n float sig = 1.0f / (1.0f + __expf(-x));\n x = x * sig;\n // tanh\n x = tanhf(x);\n // exact GELU form used by torch.nn.functional.gelu default\n x = 0.5f * x * (1.0f + erff(x * inv_sqrt2));\n // hardtanh(-1, 1) is a no-op here: after tanh, GELU is in [-~0.17, ~0.84].\n p[i] = x;\n }\n}\n\nvoid activation_launch(torch::Tensor y) {\n const auto n = y.numel();\n if (n == 0) return;\n c10::cuda::CUDAGuard device_guard(y.device());\n const int threads = 256;\n int blocks = (int)((n + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n activation_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(y.data_ptr<float>(), n);\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_swish_tanh_gelu_ext\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 2.72 μs
Runtime stats: mean=2.72μs median=?μs std=0.01μs
Numerical precision: max_abs_err=8.23e-06 mean_abs_err=7.99e-07 max_rel_err=1.61e-02
Memory: 609.16 MB peak (ref: 673.12 MB, ratio: 0.905x)
Kernel launches: 5 (ref: 16, fusion ratio: 3.2)
Energy: 1453.8 mJ/run (ref: 242.6 mJ, ratio: 0.1669x)
SOL score: 0.3751
final submitted kernel (75 lines, 2,481 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>
void activation_launch(torch::Tensor y);
torch::Tensor fused_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {
// Combine the Linear bias and the extra add_value vector, then use addmm for
// the GEMM. The remaining elementwise activation chain is fused in CUDA.
auto combined_bias = at::add(bias, add_value);
auto y = at::addmm(combined_bias, x, weight.t());
activation_launch(y);
return y;
}
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <stdint.h>
__global__ void activation_kernel(float* __restrict__ p, int64_t n) {
int64_t idx = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
int64_t stride = (int64_t)blockDim.x * gridDim.x;
const float inv_sqrt2 = 0.70710678118654752440f;
for (int64_t i = idx; i < n; i += stride) {
float x = p[i];
// Swish: x * sigmoid(x)
float sig = 1.0f / (1.0f + __expf(-x));
x = x * sig;
// tanh
x = tanhf(x);
// exact GELU form used by torch.nn.functional.gelu default
x = 0.5f * x * (1.0f + erff(x * inv_sqrt2));
// hardtanh(-1, 1) is a no-op here: after tanh, GELU is in [-~0.17, ~0.84].
p[i] = x;
}
}
void activation_launch(torch::Tensor y) {
const auto n = y.numel();
if (n == 0) return;
c10::cuda::CUDAGuard device_guard(y.device());
const int threads = 256;
int blocks = (int)((n + threads - 1) / threads);
if (blocks > 65535) blocks = 65535;
activation_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(y.data_ptr<float>(), n);
}
"""
_ext = load_inline(
name="fused_linear_swish_tanh_gelu_ext",
cpp_sources=[_cpp_src],
cuda_sources=[_cuda_src],
functions=["fused_forward"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, in_features, out_features, add_value_shape):
super(ModelNew, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.add_value = nn.Parameter(torch.randn(add_value_shape))
def forward(self, x):
return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)