correct
70_Gemm_Sigmoid_Scaling_ResidualAdd.py
started
2026-05-05T00:09:28Z
timingkernelbench.timing
kernel mean / median / std
2.71 / — / 0.05 μs
ref mean / median / std
2.77 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
2.00x
energyNVML (pynvml)
ratio (ref / kernel)
0.50x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
2315.14 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):
"""
Model implementing the pattern "Gemm_Sigmoid_Scaling_ResidualAdd".
"""
def __init__(self, input_size, hidden_size, scaling_factor):
super(Model, self).__init__()
self.gemm = nn.Linear(input_size, hidden_size)
self.scaling_factor = scaling_factor
def forward(self, x):
"""
Forward pass of the model.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, input_size).
Returns:
torch.Tensor: Output tensor of shape (batch_size, hidden_size).
"""
x = self.gemm(x)
original_x = x
x = torch.sigmoid(x)
x = x * self.scaling_factor
x = x + original_x
return x
batch_size = 1024
input_size = 8192
hidden_size = 8192
scaling_factor = 2.0
def get_inputs():
return [torch.rand(batch_size, input_size)]
def get_init_inputs():
return [input_size, hidden_size, scaling_factor]turn 0 · FINAL · 1 tool call(s) · 36.1s turn · 36.1s LLM · 6,055 chars (click to expand)
turn 036.1s turn · 36.1s LLM · 0.0s tools · FINAL
reasoning
**Considering implementation strategies**
I need to produce the final submission and understand the environment first. I’m looking to implement ModelNew using nn.Linear weights, possibly with torch.mm for efficiency. The challenge is to make it faster than PyTorch's reference, which involves fused linear and sigmoid operations. Custom CUDA GEMM might not outperform cuBLAS, but I might explore using cublasLt for optimization. I’ll think about fusing operations in the forward pass and ensure proper handling of parameters during weight copying. Let’s keep working on the details!
**Optimizing C++ and CUDA integration**
I want to reduce Python overhead and potentially speed things up by fusing post-operations. I need to compile via load_inline, avoiding PYBIND if possible. So, I’m thinking of including function declarations in cpp_sources while ensuring my C++ functions in cuda_sources are accessible. It seems load_inline can compile both C++ and CUDA code effectively. I’ll need to define a host wrapper for my CUDA kernel launcher as well, and use ATen for better performance.
**Developing the fused forward function**
I need to ensure that the bias Tensor is always passed in from Python. I’m defining the function `fused_forward` that takes input, weight, bias, and a scale. I'll use `at::linear` to compute the output, and I may need to include `ATen/Functions.h`, or possibly just torch extension will do. Instead of doing everything manually, I can also consider using `at::addmm` for computing the output as it might streamline the process.
**Considering CUDA settings**
I'm wondering if I should use the TORCH_CUDA_ARCH_LIST. It looks like the default compiles everything, but I might want to cut that down a bit. Could I use half of it instead? My current task is in fp32, so that’s pretty specific. I need to make sure I call submit just once. Let's see how that affects the process!
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#include <ATen/ops/addmm.h>\n\nvoid sigmoid_scale_add_launcher(torch::Tensor y, double scale);\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, double scale) {\n // Equivalent to torch.nn.functional.linear(input, weight, bias), using cuBLAS via ATen.\n auto y = at::addmm(bias, input, weight.t(), 1.0, 1.0);\n sigmoid_scale_add_launcher(y, scale);\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/CUDAException.h>\n#include <stdint.h>\n\nstatic __forceinline__ __device__ float post_op(float x, float scale) {\n return x + scale / (1.0f + __expf(-x));\n}\n\n__global__ void sigmoid_scale_add_kernel(float* __restrict__ y, long long n, float scale) {\n long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n if (i < n) {\n float v = y[i];\n y[i] = post_op(v, scale);\n }\n}\n\n__global__ void sigmoid_scale_add_vec4_kernel(float4* __restrict__ y4, long long n4, float scale) {\n long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n if (i < n4) {\n float4 v = y4[i];\n v.x = post_op(v.x, scale);\n v.y = post_op(v.y, scale);\n v.z = post_op(v.z, scale);\n v.w = post_op(v.w, scale);\n y4[i] = v;\n }\n}\n\nvoid sigmoid_scale_add_launcher(torch::Tensor y, double scale_d) {\n const long long n = (long long)y.numel();\n if (n == 0) return;\n const float scale = (float)scale_d;\n constexpr int threads = 256;\n auto stream = at::cuda::getCurrentCUDAStream();\n float* ptr = y.data_ptr<float>();\n uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);\n if ((addr & 15) == 0 && (n & 3LL) == 0) {\n long long n4 = n >> 2;\n int blocks = (int)((n4 + threads - 1) / threads);\n sigmoid_scale_add_vec4_kernel<<<blocks, threads, 0, stream>>>(reinterpret_cast<float4*>(ptr), n4, scale);\n } else {\n int blocks = (int)((n + threads - 1) / threads);\n sigmoid_scale_add_kernel<<<blocks, threads, 0, stream>>>(ptr, n, scale);\n }\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n}\n'''\n\n_ext = load_inline(\n name='gemm_sigmoid_scale_residual_ext',\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=['fused_forward'],\n extra_cflags=['-O3'],\n extra_cuda_cflags=['-O3'],\n with_cuda=True,\n verbose=False,\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self, input_size, hidden_size, scaling_factor):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(input_size, hidden_size)\n self.scaling_factor = float(scaling_factor)\n\n def forward(self, x):\n return _ext.fused_forward(x, self.gemm.weight, self.gemm.bias, self.scaling_factor)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 2.71 μs
Runtime stats: mean=2.71μs median=?μs std=0.05μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=7.04e-09 max_rel_err=2.25e-06
Memory: 609.06 MB peak (ref: 673.06 MB, ratio: 0.9049x)
Kernel launches: 4 (ref: 8, fusion ratio: 2.0)
Energy: 459.34 mJ/run (ref: 229.54 mJ, ratio: 0.4997x)
SOL score: 0.95
final submitted kernel (90 lines, 2,843 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>
#include <ATen/ops/addmm.h>
void sigmoid_scale_add_launcher(torch::Tensor y, double scale);
torch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, double scale) {
// Equivalent to torch.nn.functional.linear(input, weight, bias), using cuBLAS via ATen.
auto y = at::addmm(bias, input, weight.t(), 1.0, 1.0);
sigmoid_scale_add_launcher(y, scale);
return y;
}
'''
_cuda_src = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <stdint.h>
static __forceinline__ __device__ float post_op(float x, float scale) {
return x + scale / (1.0f + __expf(-x));
}
__global__ void sigmoid_scale_add_kernel(float* __restrict__ y, long long n, float scale) {
long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
float v = y[i];
y[i] = post_op(v, scale);
}
}
__global__ void sigmoid_scale_add_vec4_kernel(float4* __restrict__ y4, long long n4, float scale) {
long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
if (i < n4) {
float4 v = y4[i];
v.x = post_op(v.x, scale);
v.y = post_op(v.y, scale);
v.z = post_op(v.z, scale);
v.w = post_op(v.w, scale);
y4[i] = v;
}
}
void sigmoid_scale_add_launcher(torch::Tensor y, double scale_d) {
const long long n = (long long)y.numel();
if (n == 0) return;
const float scale = (float)scale_d;
constexpr int threads = 256;
auto stream = at::cuda::getCurrentCUDAStream();
float* ptr = y.data_ptr<float>();
uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
if ((addr & 15) == 0 && (n & 3LL) == 0) {
long long n4 = n >> 2;
int blocks = (int)((n4 + threads - 1) / threads);
sigmoid_scale_add_vec4_kernel<<<blocks, threads, 0, stream>>>(reinterpret_cast<float4*>(ptr), n4, scale);
} else {
int blocks = (int)((n + threads - 1) / threads);
sigmoid_scale_add_kernel<<<blocks, threads, 0, stream>>>(ptr, n, scale);
}
C10_CUDA_KERNEL_LAUNCH_CHECK();
}
'''
_ext = load_inline(
name='gemm_sigmoid_scale_residual_ext',
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=['fused_forward'],
extra_cflags=['-O3'],
extra_cuda_cflags=['-O3'],
with_cuda=True,
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, input_size, hidden_size, scaling_factor):
super(ModelNew, self).__init__()
self.gemm = nn.Linear(input_size, hidden_size)
self.scaling_factor = float(scaling_factor)
def forward(self, x):
return _ext.fused_forward(x, self.gemm.weight, self.gemm.bias, self.scaling_factor)