correct
76_Gemm_Add_ReLU.py
started
2026-05-05T01:16:41Z
timingkernelbench.timing
kernel mean / median / std
0.35 / — / 0.00 μs
ref mean / median / std
0.39 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
9.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
2371.88 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 bias term, and applies ReLU.
"""
def __init__(self, in_features, out_features, bias_shape):
super(Model, self).__init__()
self.gemm = nn.Linear(in_features, out_features, bias=False)
self.bias = nn.Parameter(torch.randn(bias_shape))
def forward(self, x):
"""
Args:
x (torch.Tensor): Input tensor with shape (batch_size, in_features).
Returns:
torch.Tensor: Output tensor with shape (batch_size, out_features).
"""
x = self.gemm(x)
x = x + self.bias
x = torch.relu(x)
return x
batch_size = 1024
in_features = 8192
out_features = 8192
bias_shape = (out_features,)
def get_inputs():
return [torch.rand(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, bias_shape]turn 0 · FINAL · 1 tool call(s) · 61.9s turn · 61.9s LLM · 7,861 chars (click to expand)
turn 061.9s turn · 61.9s LLM · 0.0s tools · FINAL
reasoning
**Evaluating matrix multiplication settings**
I want to compare using full precision with TF32 and check what the PyTorch default is for version 2.x. It turns out that in PyTorch, the default for `torch.backends.cuda.matmul.allow_tf32` is set to False since version 1.12. In NVIDIA NGC, it might be True. Most benchmark tasks typically use FP32, so environments likely don't support TF32. I'll need to consider the cublas and whether to change the math mode based on the current CUDA Blas handle.
**Evaluating code considerations**
I think about whether to use `contiguous` for `x`, but maybe that’s not necessary. If I transpose `x`, it could cause a failure, which is something to avoid. The constructor imports from `torch.nn`, but I wonder if the extension compiled at module load takes additional time. Also, I’m considering whether including a hash in the name is helpful. Should I issue a warning not to write "PYBIND" in cpp_sources? Lastly, I’m pondering if extra flags would affect cublas, but I might be overthinking it. Let's just submit it!
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_bias_relu_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/types.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n\n#define CUBLAS_CHECK(stmt) do { \\\n cublasStatus_t _status = (stmt); \\\n TORCH_CHECK(_status == CUBLAS_STATUS_SUCCESS, \\\n \"cuBLAS error: \", static_cast<int>(_status)); \\\n} while (0)\n\n__device__ __forceinline__ float relu_f(float x) {\n return x > 0.0f ? x : 0.0f;\n}\n\n__global__ void add_bias_relu_vec4_kernel(float4* __restrict__ out4,\n const float4* __restrict__ bias4,\n int rows, int n4) {\n int c = blockIdx.x * blockDim.x + threadIdx.x;\n int r = blockIdx.y;\n if (c < n4) {\n long long idx = static_cast<long long>(r) * n4 + c;\n float4 v = out4[idx];\n float4 b = bias4[c];\n v.x = relu_f(v.x + b.x);\n v.y = relu_f(v.y + b.y);\n v.z = relu_f(v.z + b.z);\n v.w = relu_f(v.w + b.w);\n out4[idx] = v;\n }\n}\n\n__global__ void add_bias_relu_scalar_kernel(float* __restrict__ out,\n const float* __restrict__ bias,\n long long total, int n) {\n long long idx = static_cast<long long>(blockIdx.x) * blockDim.x + threadIdx.x;\n long long stride = static_cast<long long>(blockDim.x) * gridDim.x;\n for (; idx < total; idx += stride) {\n int c = static_cast<int>(idx % n);\n float v = out[idx] + bias[c];\n out[idx] = v > 0.0f ? v : 0.0f;\n }\n}\n\ntorch::Tensor linear_bias_relu_forward(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() == at::kFloat && weight.scalar_type() == at::kFloat && bias.scalar_type() == at::kFloat,\n \"only float32 tensors are 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, \"x and weight must be 2D\");\n\n const int M = static_cast<int>(x.size(0));\n const int K = static_cast<int>(x.size(1));\n const int N = static_cast<int>(weight.size(0));\n TORCH_CHECK(static_cast<int>(weight.size(1)) == K, \"incompatible matrix dimensions\");\n TORCH_CHECK(bias.numel() == N, \"bias has wrong size\");\n\n auto out = torch::empty({M, N}, x.options());\n\n const float alpha = 1.0f;\n const float beta = 0.0f;\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n CUBLAS_CHECK(cublasSetStream(handle, stream));\n\n // Row-major C = x @ weight.T. Interpreting row-major buffers as column-major,\n // compute C^T (N x M) = weight (N x K) * x^T (K x M).\n CUBLAS_CHECK(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 out.data_ptr<float>(), N));\n\n const int threads = 256;\n if ((N % 4) == 0) {\n int n4 = N >> 2;\n dim3 block(threads);\n dim3 grid((n4 + threads - 1) / threads, M);\n add_bias_relu_vec4_kernel<<<grid, block, 0, stream>>>(\n reinterpret_cast<float4*>(out.data_ptr<float>()),\n reinterpret_cast<const float4*>(bias.data_ptr<float>()),\n M, n4);\n } else {\n long long total = static_cast<long long>(M) * N;\n int blocks = static_cast<int>((total + threads - 1) / threads);\n if (blocks > 4096) blocks = 4096;\n add_bias_relu_scalar_kernel<<<blocks, threads, 0, stream>>>(out.data_ptr<float>(), bias.data_ptr<float>(), total, N);\n }\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"linear_bias_relu_cublas_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"linear_bias_relu_forward\"],\n with_cuda=True,\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\n\nclass ModelNew(nn.Module):\n \"\"\"\n Drop-in replacement for the reference module. Parameters are kept with the\n same names/layout so external initialization or state_dict copying works.\n \"\"\"\n def __init__(self, in_features, out_features, bias_shape):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(in_features, out_features, bias=False)\n self.bias = nn.Parameter(torch.randn(bias_shape))\n\n def forward(self, x):\n return _ext.linear_bias_relu_forward(x, self.gemm.weight, self.bias)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.35 μs
Runtime stats: mean=0.35μs median=?μs std=0.00μs
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
Memory: 609.06 MB peak (ref: 641.06 MB, ratio: 0.9501x)
Kernel launches: 1 (ref: 9, fusion ratio: 9.0)
Energy: 240.64 mJ/run (ref: 0.0 mJ, ratio: -1x)
SOL score: 0.8109
final submitted kernel (134 lines, 5,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_bias_relu_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);
"""
_cuda_src = r"""
#include <torch/types.h>
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cublas_v2.h>
#include <cuda_runtime.h>
#define CUBLAS_CHECK(stmt) do { \
cublasStatus_t _status = (stmt); \
TORCH_CHECK(_status == CUBLAS_STATUS_SUCCESS, \
"cuBLAS error: ", static_cast<int>(_status)); \
} while (0)
__device__ __forceinline__ float relu_f(float x) {
return x > 0.0f ? x : 0.0f;
}
__global__ void add_bias_relu_vec4_kernel(float4* __restrict__ out4,
const float4* __restrict__ bias4,
int rows, int n4) {
int c = blockIdx.x * blockDim.x + threadIdx.x;
int r = blockIdx.y;
if (c < n4) {
long long idx = static_cast<long long>(r) * n4 + c;
float4 v = out4[idx];
float4 b = bias4[c];
v.x = relu_f(v.x + b.x);
v.y = relu_f(v.y + b.y);
v.z = relu_f(v.z + b.z);
v.w = relu_f(v.w + b.w);
out4[idx] = v;
}
}
__global__ void add_bias_relu_scalar_kernel(float* __restrict__ out,
const float* __restrict__ bias,
long long total, int n) {
long long idx = static_cast<long long>(blockIdx.x) * blockDim.x + threadIdx.x;
long long stride = static_cast<long long>(blockDim.x) * gridDim.x;
for (; idx < total; idx += stride) {
int c = static_cast<int>(idx % n);
float v = out[idx] + bias[c];
out[idx] = v > 0.0f ? v : 0.0f;
}
}
torch::Tensor linear_bias_relu_forward(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() == at::kFloat && weight.scalar_type() == at::kFloat && bias.scalar_type() == at::kFloat,
"only float32 tensors are supported");
TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() && bias.is_contiguous(), "tensors must be contiguous");
TORCH_CHECK(x.dim() == 2 && weight.dim() == 2, "x and weight must be 2D");
const int M = static_cast<int>(x.size(0));
const int K = static_cast<int>(x.size(1));
const int N = static_cast<int>(weight.size(0));
TORCH_CHECK(static_cast<int>(weight.size(1)) == K, "incompatible matrix dimensions");
TORCH_CHECK(bias.numel() == N, "bias has wrong size");
auto out = torch::empty({M, N}, x.options());
const float alpha = 1.0f;
const float beta = 0.0f;
cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
CUBLAS_CHECK(cublasSetStream(handle, stream));
// Row-major C = x @ weight.T. Interpreting row-major buffers as column-major,
// compute C^T (N x M) = weight (N x K) * x^T (K x M).
CUBLAS_CHECK(cublasSgemm(handle,
CUBLAS_OP_T, CUBLAS_OP_N,
N, M, K,
&alpha,
weight.data_ptr<float>(), K,
x.data_ptr<float>(), K,
&beta,
out.data_ptr<float>(), N));
const int threads = 256;
if ((N % 4) == 0) {
int n4 = N >> 2;
dim3 block(threads);
dim3 grid((n4 + threads - 1) / threads, M);
add_bias_relu_vec4_kernel<<<grid, block, 0, stream>>>(
reinterpret_cast<float4*>(out.data_ptr<float>()),
reinterpret_cast<const float4*>(bias.data_ptr<float>()),
M, n4);
} else {
long long total = static_cast<long long>(M) * N;
int blocks = static_cast<int>((total + threads - 1) / threads);
if (blocks > 4096) blocks = 4096;
add_bias_relu_scalar_kernel<<<blocks, threads, 0, stream>>>(out.data_ptr<float>(), bias.data_ptr<float>(), total, N);
}
C10_CUDA_KERNEL_LAUNCH_CHECK();
return out;
}
"""
_ext = load_inline(
name="linear_bias_relu_cublas_ext_v1",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["linear_bias_relu_forward"],
with_cuda=True,
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3"],
verbose=False,
)
class ModelNew(nn.Module):
"""
Drop-in replacement for the reference module. Parameters are kept with the
same names/layout so external initialization or state_dict copying works.
"""
def __init__(self, in_features, out_features, bias_shape):
super(ModelNew, self).__init__()
self.gemm = nn.Linear(in_features, out_features, bias=False)
self.bias = nn.Parameter(torch.randn(bias_shape))
def forward(self, x):
return _ext.linear_bias_relu_forward(x, self.gemm.weight, self.bias)