correct
59_Matmul_Swish_Scaling.py
started
2026-05-05T02:12:50Z
timingkernelbench.timing
kernel mean / median / std
5.28 / — / 0.01 μs
ref mean / median / std
5.31 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
8.00x
energyNVML (pynvml)
ratio (ref / kernel)
0.68x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1984.89 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 Swish activation, and scales the result.
"""
def __init__(self, in_features, out_features, scaling_factor):
super(Model, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.scaling_factor = scaling_factor
def forward(self, x):
x = self.matmul(x)
x = x * torch.sigmoid(x) # Swish activation
x = x * self.scaling_factor
return x
batch_size = 128
in_features = 32768
out_features = 32768
scaling_factor = 2.0
def get_inputs():
return [torch.rand(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, scaling_factor]turn 0 · FINAL · 1 tool call(s) · 64.5s turn · 64.5s LLM · 6,285 chars (click to expand)
turn 064.5s turn · 64.5s LLM · 0.0s tools · FINAL
reasoning
**Considering compile cache conflicts**
I'm pondering what happens with compile cache name conflicts across submissions. Maybe a unique name like "linear_swish_ext_v1" could work. I'm also thinking about potential hidden tests concerning input and output features, with the constructor being the same, but likely fixed.
I've confirmed our GEMM is general with M, K, N, and it's float32 only. There are concerns about using cuBLAS directly with custom CUDA kernels, but I might improve performance by using cublasSgemm with beta, assuming bias is null. Using CUDA graph? No, maybe not.
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_swish_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scaling);\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_runtime.h>\n#include <cublas_v2.h>\n\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__global__ void bias_swish_scale_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n int M, int N, float scale) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (row < M && col < N) {\n int idx = row * N + col;\n float v = y[idx] + bias[col];\n float s = 1.0f / (1.0f + expf(-v));\n y[idx] = (v * s) * scale;\n }\n}\n\ntorch::Tensor linear_swish_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scaling) {\n CHECK_CUDA(x);\n CHECK_CUDA(weight);\n CHECK_CUDA(bias);\n CHECK_CONTIGUOUS(x);\n CHECK_CONTIGUOUS(weight);\n CHECK_CONTIGUOUS(bias);\n CHECK_FLOAT(x);\n CHECK_FLOAT(weight);\n CHECK_FLOAT(bias);\n\n TORCH_CHECK(x.dim() == 2, \"x must be 2D\");\n TORCH_CHECK(weight.dim() == 2, \"weight must be 2D\");\n\n const int64_t M64 = x.size(0);\n const int64_t K64 = x.size(1);\n const int64_t N64 = weight.size(0);\n TORCH_CHECK(weight.size(1) == K64, \"incompatible weight shape\");\n TORCH_CHECK(bias.numel() == N64, \"incompatible bias shape\");\n TORCH_CHECK(M64 <= INT_MAX && N64 <= INT_MAX && K64 <= INT_MAX, \"dimensions too large\");\n\n const int M = (int)M64;\n const int N = (int)N64;\n const int K = (int)K64;\n\n c10::cuda::CUDAGuard device_guard(x.device());\n auto y = torch::empty({M64, N64}, x.options());\n\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n cublasSetStream(handle, at::cuda::getCurrentCUDAStream());\n // Keep full fp32 SGEMM semantics for fp32-precision correctness.\n cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH);\n\n const float alpha = 1.0f;\n const float beta = 0.0f;\n\n // Row-major Y[M,N] is interpreted as column-major C[N,M].\n // Computes C = W * X^T, i.e. Y = X * W^T.\n cublasStatus_t st = cublasSgemm(handle,\n CUBLAS_OP_T, CUBLAS_OP_N,\n N, M, K,\n &alpha,\n weight.data_ptr<float>(), K,\n x.data_ptr<float>(), K,\n &beta,\n y.data_ptr<float>(), N);\n TORCH_CHECK(st == CUBLAS_STATUS_SUCCESS, \"cublasSgemm failed\");\n\n dim3 block(256);\n dim3 grid((N + block.x - 1) / block.x, M);\n bias_swish_scale_kernel<<<grid, block, 0, at::cuda::getCurrentCUDAStream()>>>(\n y.data_ptr<float>(), bias.data_ptr<float>(), M, N, (float)scaling);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"linear_swish_cublas_fused_ext\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"linear_swish_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\n\nclass ModelNew(nn.Module):\n \"\"\"\n Linear layer followed by Swish activation and scalar scaling, with the\n GEMM launched through cuBLAS and the bias/activation/scale fused in one\n CUDA kernel.\n \"\"\"\n def __init__(self, in_features, out_features, scaling_factor):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.scaling_factor = scaling_factor\n\n def forward(self, x):\n return _ext.linear_swish_cuda(x, self.matmul.weight, self.matmul.bias, float(self.scaling_factor))\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 5.28 μs
Runtime stats: mean=5.28μs median=?μs std=0.01μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=4.93e-09 max_rel_err=3.48e-07
Memory: 8257.25 MB peak (ref: 8289.25 MB, ratio: 0.9961x)
Kernel launches: 1 (ref: 8, fusion ratio: 8.0)
Energy: 2238.46 mJ/run (ref: 1533.18 mJ, ratio: 0.6849x)
SOL score: 0.9222
final submitted kernel (118 lines, 4,148 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_swish_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scaling);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x " must be float32")
__global__ void bias_swish_scale_kernel(float* __restrict__ y,
const float* __restrict__ bias,
int M, int N, float scale) {
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y;
if (row < M && col < N) {
int idx = row * N + col;
float v = y[idx] + bias[col];
float s = 1.0f / (1.0f + expf(-v));
y[idx] = (v * s) * scale;
}
}
torch::Tensor linear_swish_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scaling) {
CHECK_CUDA(x);
CHECK_CUDA(weight);
CHECK_CUDA(bias);
CHECK_CONTIGUOUS(x);
CHECK_CONTIGUOUS(weight);
CHECK_CONTIGUOUS(bias);
CHECK_FLOAT(x);
CHECK_FLOAT(weight);
CHECK_FLOAT(bias);
TORCH_CHECK(x.dim() == 2, "x must be 2D");
TORCH_CHECK(weight.dim() == 2, "weight must be 2D");
const int64_t M64 = x.size(0);
const int64_t K64 = x.size(1);
const int64_t N64 = weight.size(0);
TORCH_CHECK(weight.size(1) == K64, "incompatible weight shape");
TORCH_CHECK(bias.numel() == N64, "incompatible bias shape");
TORCH_CHECK(M64 <= INT_MAX && N64 <= INT_MAX && K64 <= INT_MAX, "dimensions too large");
const int M = (int)M64;
const int N = (int)N64;
const int K = (int)K64;
c10::cuda::CUDAGuard device_guard(x.device());
auto y = torch::empty({M64, N64}, x.options());
cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
cublasSetStream(handle, at::cuda::getCurrentCUDAStream());
// Keep full fp32 SGEMM semantics for fp32-precision correctness.
cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH);
const float alpha = 1.0f;
const float beta = 0.0f;
// Row-major Y[M,N] is interpreted as column-major C[N,M].
// Computes C = W * X^T, i.e. Y = X * W^T.
cublasStatus_t st = cublasSgemm(handle,
CUBLAS_OP_T, CUBLAS_OP_N,
N, M, K,
&alpha,
weight.data_ptr<float>(), K,
x.data_ptr<float>(), K,
&beta,
y.data_ptr<float>(), N);
TORCH_CHECK(st == CUBLAS_STATUS_SUCCESS, "cublasSgemm failed");
dim3 block(256);
dim3 grid((N + block.x - 1) / block.x, M);
bias_swish_scale_kernel<<<grid, block, 0, at::cuda::getCurrentCUDAStream()>>>(
y.data_ptr<float>(), bias.data_ptr<float>(), M, N, (float)scaling);
C10_CUDA_KERNEL_LAUNCH_CHECK();
return y;
}
"""
_ext = load_inline(
name="linear_swish_cublas_fused_ext",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["linear_swish_cuda"],
with_cuda=True,
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
extra_ldflags=["-lcublas"],
verbose=False,
)
class ModelNew(nn.Module):
"""
Linear layer followed by Swish activation and scalar scaling, with the
GEMM launched through cuBLAS and the bias/activation/scale fused in one
CUDA kernel.
"""
def __init__(self, in_features, out_features, scaling_factor):
super(ModelNew, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.scaling_factor = scaling_factor
def forward(self, x):
return _ext.linear_swish_cuda(x, self.matmul.weight, self.matmul.bias, float(self.scaling_factor))