correct
56_Matmul_Sigmoid_Sum.py
started
2026-05-05T00:02:00Z
timingkernelbench.timing
kernel mean / median / std
5.32 / — / 0.01 μs
ref mean / median / std
5.29 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
3.50x
energyNVML (pynvml)
ratio (ref / kernel)
1.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1118.53 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, applies sigmoid, and sums the result.
"""
def __init__(self, input_size, hidden_size):
super(Model, self).__init__()
self.linear = nn.Linear(input_size, hidden_size)
def forward(self, x):
"""
Args:
x: Input tensor of shape (batch_size, input_size).
Returns:
Output tensor of shape (batch_size, 1).
"""
x = self.linear(x)
x = torch.sigmoid(x)
x = torch.sum(x, dim=1, keepdim=True)
return x
batch_size = 128
input_size = 32768
hidden_size = 32768
def get_inputs():
return [torch.rand(batch_size, input_size)]
def get_init_inputs():
return [input_size, hidden_size]turn 0 · FINAL · 1 tool call(s) · 137.1s turn · 137.1s LLM · 7,794 chars (click to expand)
turn 0137.1s turn · 137.1s LLM · 0.0s tools · FINAL
reasoning
**Crafting a custom kernel**
I need to create a complete Python setup involving a custom kernel for a linear operation on large matrices. I want to ensure I use the right parameters and load the necessary weights. The forward function should calculate the sum of the bias and the matrix multiplication, followed by a sigmoid activation for output. Since this involves large operations, I’m considering optimizing with fused functions to reduce overhead, possibly utilizing cuBLAS for efficiency. This is going to require careful implementation!
**Exploring kernel and performance**
I'm considering using a C++ wrapper to call the linear function for better performance than PyTorch. I might exploit random initialization for inputs and weights while implementing a GEMM operation tailored for large matrices. The idea is to perform computations efficiently by using cuBLAS for matrix multiplication and then a custom sigmoid reduction. It could also involve using the at::addmm function for optimized performance. I really want to get this right for maximum efficiency!
**Considering C++ implementation**
I’m thinking about implementing a host wrapper in C++ to allocate temporary memory for the batch size and height, then call the at::linear function. However, since fallback isn't allowed, I'm exploring if this is my only option. The goal is to increase speed, potentially by fusing the reduction after calculations with a combination of at::addmm and a fused sigmoid-sum. I really want to streamline this for better performance!
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\ntorch::Tensor linear_sigmoid_sum_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\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 <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n\n#define CUBLAS_CHECK_(expr) do { \\\n cublasStatus_t _status = (expr); \\\n TORCH_CHECK(_status == CUBLAS_STATUS_SUCCESS, \"cuBLAS error\"); \\\n} while (0)\n\nstatic __device__ __forceinline__ float warp_sum(float v) {\n v += __shfl_down_sync(0xffffffff, v, 16);\n v += __shfl_down_sync(0xffffffff, v, 8);\n v += __shfl_down_sync(0xffffffff, v, 4);\n v += __shfl_down_sync(0xffffffff, v, 2);\n v += __shfl_down_sync(0xffffffff, v, 1);\n return v;\n}\n\n__global__ void sigmoid_sum_kernel(const float* __restrict__ mm,\n const float* __restrict__ bias,\n float* __restrict__ out,\n int B, int H) {\n int row = blockIdx.x;\n int tid = threadIdx.x;\n float acc = 0.0f;\n const float* base = mm + (long long)row * H;\n\n // Grid is one CTA per batch row. H is large (32768), so this gives each\n // thread enough independent work to hide the SFU latency from expf.\n for (int j = tid; j < H; j += blockDim.x) {\n float z = base[j] + bias[j];\n // Fast sigmoid; final sum is O(1.6e4), so the reference tolerance is\n // dominated by relative error and this is well within bounds.\n acc += 1.0f / (1.0f + __expf(-z));\n }\n\n acc = warp_sum(acc);\n __shared__ float smem[32];\n int lane = tid & 31;\n int wid = tid >> 5;\n if (lane == 0) smem[wid] = acc;\n __syncthreads();\n\n float v = (tid < (blockDim.x >> 5)) ? smem[lane] : 0.0f;\n if (wid == 0) {\n v = warp_sum(v);\n if (tid == 0) out[row] = v;\n }\n}\n\ntorch::Tensor linear_sigmoid_sum_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {\n TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(), \"all tensors must be CUDA tensors\");\n TORCH_CHECK(x.scalar_type() == torch::kFloat32, \"only float32 is supported\");\n TORCH_CHECK(weight.scalar_type() == torch::kFloat32 && bias.scalar_type() == torch::kFloat32, \"only float32 is supported\");\n TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() && bias.is_contiguous(), \"tensors must be contiguous\");\n TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1, \"bad tensor rank\");\n\n const int B = (int)x.size(0);\n const int K = (int)x.size(1);\n const int H = (int)weight.size(0);\n TORCH_CHECK(weight.size(1) == K && bias.size(0) == H, \"incompatible dimensions\");\n\n c10::cuda::CUDAGuard device_guard(x.device());\n auto tmp = torch::empty({B, H}, x.options());\n auto out = torch::empty({B, 1}, x.options());\n\n // Row-major C = X * W^T is issued to cuBLAS as column-major\n // C_col(H,B) = op(W_col(K,H))^T * X_col(K,B).\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n const float alpha = 1.0f;\n const float beta = 0.0f;\n CUBLAS_CHECK_(cublasSgemm(handle,\n CUBLAS_OP_T, CUBLAS_OP_N,\n H, B, K,\n &alpha,\n weight.data_ptr<float>(), K,\n x.data_ptr<float>(), K,\n &beta,\n tmp.data_ptr<float>(), H));\n\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n constexpr int THREADS = 256;\n sigmoid_sum_kernel<<<B, THREADS, 0, stream>>>(tmp.data_ptr<float>(),\n bias.data_ptr<float>(),\n out.data_ptr<float>(),\n B, H);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"linear_sigmoid_sum_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"linear_sigmoid_sum_cuda\"],\n with_cuda=True,\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n extra_ldflags=[\"-lcublas\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(ModelNew, self).__init__()\n self.linear = nn.Linear(input_size, hidden_size)\n\n def forward(self, x):\n return _ext.linear_sigmoid_sum_cuda(x, self.linear.weight, self.linear.bias)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 5.32 μs
Runtime stats: mean=5.32μs median=?μs std=0.01μs
Numerical precision: max_abs_err=3.91e-03 mean_abs_err=5.49e-04 max_rel_err=2.38e-07
Memory: 8257.25 MB peak (ref: 8273.25 MB, ratio: 0.9981x)
Kernel launches: 2 (ref: 7, fusion ratio: 3.5)
Energy: 483.2 mJ/run (ref: 483.42 mJ, ratio: 1.0005x)
SOL score: 0.824
final submitted kernel (126 lines, 4,709 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 linear_sigmoid_sum_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>
#define CUBLAS_CHECK_(expr) do { \
cublasStatus_t _status = (expr); \
TORCH_CHECK(_status == CUBLAS_STATUS_SUCCESS, "cuBLAS error"); \
} while (0)
static __device__ __forceinline__ float warp_sum(float v) {
v += __shfl_down_sync(0xffffffff, v, 16);
v += __shfl_down_sync(0xffffffff, v, 8);
v += __shfl_down_sync(0xffffffff, v, 4);
v += __shfl_down_sync(0xffffffff, v, 2);
v += __shfl_down_sync(0xffffffff, v, 1);
return v;
}
__global__ void sigmoid_sum_kernel(const float* __restrict__ mm,
const float* __restrict__ bias,
float* __restrict__ out,
int B, int H) {
int row = blockIdx.x;
int tid = threadIdx.x;
float acc = 0.0f;
const float* base = mm + (long long)row * H;
// Grid is one CTA per batch row. H is large (32768), so this gives each
// thread enough independent work to hide the SFU latency from expf.
for (int j = tid; j < H; j += blockDim.x) {
float z = base[j] + bias[j];
// Fast sigmoid; final sum is O(1.6e4), so the reference tolerance is
// dominated by relative error and this is well within bounds.
acc += 1.0f / (1.0f + __expf(-z));
}
acc = warp_sum(acc);
__shared__ float smem[32];
int lane = tid & 31;
int wid = tid >> 5;
if (lane == 0) smem[wid] = acc;
__syncthreads();
float v = (tid < (blockDim.x >> 5)) ? smem[lane] : 0.0f;
if (wid == 0) {
v = warp_sum(v);
if (tid == 0) out[row] = v;
}
}
torch::Tensor linear_sigmoid_sum_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {
TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(), "all tensors must be CUDA tensors");
TORCH_CHECK(x.scalar_type() == torch::kFloat32, "only float32 is supported");
TORCH_CHECK(weight.scalar_type() == torch::kFloat32 && bias.scalar_type() == torch::kFloat32, "only float32 is supported");
TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() && bias.is_contiguous(), "tensors must be contiguous");
TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1, "bad tensor rank");
const int B = (int)x.size(0);
const int K = (int)x.size(1);
const int H = (int)weight.size(0);
TORCH_CHECK(weight.size(1) == K && bias.size(0) == H, "incompatible dimensions");
c10::cuda::CUDAGuard device_guard(x.device());
auto tmp = torch::empty({B, H}, x.options());
auto out = torch::empty({B, 1}, x.options());
// Row-major C = X * W^T is issued to cuBLAS as column-major
// C_col(H,B) = op(W_col(K,H))^T * X_col(K,B).
cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
const float alpha = 1.0f;
const float beta = 0.0f;
CUBLAS_CHECK_(cublasSgemm(handle,
CUBLAS_OP_T, CUBLAS_OP_N,
H, B, K,
&alpha,
weight.data_ptr<float>(), K,
x.data_ptr<float>(), K,
&beta,
tmp.data_ptr<float>(), H));
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
constexpr int THREADS = 256;
sigmoid_sum_kernel<<<B, THREADS, 0, stream>>>(tmp.data_ptr<float>(),
bias.data_ptr<float>(),
out.data_ptr<float>(),
B, H);
C10_CUDA_KERNEL_LAUNCH_CHECK();
return out;
}
"""
_ext = load_inline(
name="linear_sigmoid_sum_ext_v1",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["linear_sigmoid_sum_cuda"],
with_cuda=True,
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
extra_ldflags=["-lcublas"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, input_size, hidden_size):
super(ModelNew, self).__init__()
self.linear = nn.Linear(input_size, hidden_size)
def forward(self, x):
return _ext.linear_sigmoid_sum_cuda(x, self.linear.weight, self.linear.bias)