gpt-5.5-priority · original · l123_single_gpt
correct 12_Gemm_Multiply_LeakyReLU.py
model
gpt-5.5-priority
turns / max
1 / 1
tool calls
1
tokens (total)
0
wall clock
—
truncated
no
backend
cuda fp32
variant
original
runtime
2.74 μs
ref runtime
2.73 μs
speedup
1.00x
started
2026-05-05T00:32:58Z
timingkernelbench.timing
kernel runtime
2.74 μs
ref runtime
2.73 μs
speedup
1.00x
kernel mean / median / std
2.74 / — / 0.01 μs
ref mean / median / std
2.73 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
max abs error
0.00
mean abs error
0.00
max rel error
0.00
mean rel error
0.00
gpu memoryextended_metrics.measure_memory
kernel peak
609.06 MB
ref peak
641.06 MB
kernel / ref
0.95x
kernel launches / fusiontorch.profiler
kernel launches
1
ref launches
7
fusion ratio (ref / kernel)
7.00x
total cuda time
22 μs
energyNVML (pynvml)
kernel mJ / run
485.94
ref mJ / run
1944.42
ratio (ref / kernel)
4.00x
avg power
177.23 W
ref avg power
712.01 W
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.963
dram util %
69.6%
compute util %
96.3%
bottleneck
compute-bound
dominant pipe
FP32
arithmetic intensity
—
ridge point
20.00
roofline / occupancynsight_hardware_counters
dram bandwidth
2332.30 GB/s
dram util %
69.6%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
91.1%
bottleneck
compute-bound
dominant pipe %
96.3%
arithmetic intensity
—
ridge point
20.00
L1 hit %
—
L2 hit %
148.9%
ld sectors / req
20.00
st sectors / req
—
regs / thread
287
smem / block
35328 B
block size
384
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
1529.6%
short_scoreboard
86.0%
mio_throttle
26.1%
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Simple model that performs a Gemm, multiplies the result, and applies LeakyReLU.
    """
    def __init__(self, in_features, out_features, multiplier, negative_slope):
        super(Model, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.multiplier = multiplier
        self.leaky_relu = nn.LeakyReLU(negative_slope)

    def forward(self, x):
        x = self.gemm(x)
        x = x * self.multiplier
        x = self.leaky_relu(x)
        return x

batch_size = 1024
in_features  = 8192  
out_features = 8192
multiplier = 2.0
negative_slope = 0.1

def get_inputs():
    return [torch.rand(batch_size, in_features)]

def get_init_inputs():
    return [in_features, out_features, multiplier, negative_slope]
turn 0 · FINAL · 1 tool call(s) · 54.8s turn · 54.8s LLM · 8,709 chars (click to expand)
turn 054.8s turn · 54.8s LLM · 0.0s tools · FINAL
reasoning
**Analyzing cuBLAS and PyTorch performance** I’m exploring how torch.addmm might utilize cuBLAS with parameters like beta and C bias. It seems that for the bias vector, I can't use the beta matrix directly unless it's expanded, possibly incorporating cuBLASLt for bias processing. PyTorch's Linear could be leveraging cublasLt for optimized matmul with a fused bias. I wonder about the efficiency of one versus two kernels in terms of memory passes, especially considering the GEMM performance compared to pointwise operations. Speedup appears modest, though.
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#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cublas_v2.h>\n\nvoid linear_epilogue_launch(torch::Tensor y, torch::Tensor bias, double bias_scale, double negative_slope);\n\ntorch::Tensor fused_linear_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias,\n double multiplier, double negative_slope) {\n TORCH_CHECK(x.is_cuda(), \"x must be CUDA\");\n TORCH_CHECK(weight.is_cuda(), \"weight must be CUDA\");\n TORCH_CHECK(bias.is_cuda(), \"bias must be CUDA\");\n TORCH_CHECK(x.scalar_type() == at::kFloat, \"only fp32 supported\");\n TORCH_CHECK(weight.scalar_type() == at::kFloat, \"only fp32 supported\");\n TORCH_CHECK(bias.scalar_type() == at::kFloat, \"only fp32 supported\");\n TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1, \"bad dimensions\");\n TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() && bias.is_contiguous(), \"inputs must be contiguous\");\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 && bias.size(0) == N64, \"incompatible dimensions\");\n TORCH_CHECK(M64 <= INT_MAX && N64 <= INT_MAX && K64 <= INT_MAX, \"dimensions too large\");\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 // Row-major Y = X * W^T. Interpreting the same storage as column-major,\n // compute Y^T (N x M) = W (N x K) * X^T (K x M), where W is obtained as\n // transpose of the column-major K x N view of the row-major weight tensor.\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n const float alpha = static_cast<float>(multiplier);\n const float beta = 0.0f;\n cublasStatus_t stat = 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(stat == CUBLAS_STATUS_SUCCESS, \"cublasSgemm failed\");\n\n linear_epilogue_launch(y, bias, multiplier, negative_slope);\n return y;\n}\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void epilogue_scalar_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n long long total,\n int n,\n float bias_scale,\n float negative_slope) {\n long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n long long stride = (long long)blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int col = (int)(idx % n);\n float v = y[idx] + bias[col] * bias_scale;\n y[idx] = (v >= 0.0f) ? v : v * negative_slope;\n }\n}\n\n__global__ void epilogue_vec4_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n long long vec_total,\n int n,\n float bias_scale,\n float negative_slope) {\n long long vidx = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n long long stride = (long long)blockDim.x * gridDim.x;\n float4* __restrict__ y4 = reinterpret_cast<float4*>(y);\n for (; vidx < vec_total; vidx += stride) {\n long long base = vidx * 4LL;\n int col = (int)(base % n);\n float4 v = y4[vidx];\n // Fast path used by the benchmark dimensions (n is a multiple of 4).\n float b0 = bias[col + 0] * bias_scale;\n float b1 = bias[col + 1] * bias_scale;\n float b2 = bias[col + 2] * bias_scale;\n float b3 = bias[col + 3] * bias_scale;\n v.x += b0; v.y += b1; v.z += b2; v.w += b3;\n v.x = (v.x >= 0.0f) ? v.x : v.x * negative_slope;\n v.y = (v.y >= 0.0f) ? v.y : v.y * negative_slope;\n v.z = (v.z >= 0.0f) ? v.z : v.z * negative_slope;\n v.w = (v.w >= 0.0f) ? v.w : v.w * negative_slope;\n y4[vidx] = v;\n }\n}\n\nvoid linear_epilogue_launch(torch::Tensor y, torch::Tensor bias, double bias_scale, double negative_slope) {\n const long long total = y.numel();\n const int n = (int)y.size(1);\n const int threads = 256;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n float bs = static_cast<float>(bias_scale);\n float ns = static_cast<float>(negative_slope);\n\n // Vectorized path for aligned, four-divisible rows. The supplied problem has\n // N=8192 and CUDA allocations are suitably aligned.\n if ((total % 4LL) == 0 && (n % 4) == 0) {\n long long vt = total / 4LL;\n int blocks = (int)((vt + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n epilogue_vec4_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), vt, n, bs, ns);\n } else {\n int blocks = (int)((total + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n epilogue_scalar_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), total, n, bs, ns);\n }\n}\n'''\n\n_ext = load_inline(\n name=\"fused_linear_leakyrelu_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_linear_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n extra_ldflags=[\"-lcublas\"],\n with_cuda=True,\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, multiplier, negative_slope):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(in_features, out_features)\n self.multiplier = multiplier\n self.negative_slope = negative_slope\n\n def forward(self, x):\n return _ext.fused_linear_forward(x, self.gemm.weight, self.gemm.bias,\n float(self.multiplier), float(self.negative_slope))\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (5 / 5) correctness trials all passed. Kernel runtime: 2.74 μs Runtime stats: mean=2.74μs median=?μs std=0.01μ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: 7, fusion ratio: 7.0) Energy: 485.94 mJ/run (ref: 1944.42 mJ, ratio: 4.0014x) SOL score: 0.9628
final submitted kernel (150 lines, 6,482 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/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cublas_v2.h>

void linear_epilogue_launch(torch::Tensor y, torch::Tensor bias, double bias_scale, double negative_slope);

torch::Tensor fused_linear_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias,
                                  double multiplier, double negative_slope) {
    TORCH_CHECK(x.is_cuda(), "x must be CUDA");
    TORCH_CHECK(weight.is_cuda(), "weight must be CUDA");
    TORCH_CHECK(bias.is_cuda(), "bias must be CUDA");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "only fp32 supported");
    TORCH_CHECK(weight.scalar_type() == at::kFloat, "only fp32 supported");
    TORCH_CHECK(bias.scalar_type() == at::kFloat, "only fp32 supported");
    TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1, "bad dimensions");
    TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() && bias.is_contiguous(), "inputs must be contiguous");

    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 && bias.size(0) == N64, "incompatible dimensions");
    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());

    // Row-major Y = X * W^T.  Interpreting the same storage as column-major,
    // compute Y^T (N x M) = W (N x K) * X^T (K x M), where W is obtained as
    // transpose of the column-major K x N view of the row-major weight tensor.
    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
    const float alpha = static_cast<float>(multiplier);
    const float beta = 0.0f;
    cublasStatus_t stat = 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(stat == CUBLAS_STATUS_SUCCESS, "cublasSgemm failed");

    linear_epilogue_launch(y, bias, multiplier, negative_slope);
    return y;
}
'''

_cuda_src = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>

__global__ void epilogue_scalar_kernel(float* __restrict__ y,
                                       const float* __restrict__ bias,
                                       long long total,
                                       int n,
                                       float bias_scale,
                                       float negative_slope) {
    long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    long long stride = (long long)blockDim.x * gridDim.x;
    for (; idx < total; idx += stride) {
        int col = (int)(idx % n);
        float v = y[idx] + bias[col] * bias_scale;
        y[idx] = (v >= 0.0f) ? v : v * negative_slope;
    }
}

__global__ void epilogue_vec4_kernel(float* __restrict__ y,
                                     const float* __restrict__ bias,
                                     long long vec_total,
                                     int n,
                                     float bias_scale,
                                     float negative_slope) {
    long long vidx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    long long stride = (long long)blockDim.x * gridDim.x;
    float4* __restrict__ y4 = reinterpret_cast<float4*>(y);
    for (; vidx < vec_total; vidx += stride) {
        long long base = vidx * 4LL;
        int col = (int)(base % n);
        float4 v = y4[vidx];
        // Fast path used by the benchmark dimensions (n is a multiple of 4).
        float b0 = bias[col + 0] * bias_scale;
        float b1 = bias[col + 1] * bias_scale;
        float b2 = bias[col + 2] * bias_scale;
        float b3 = bias[col + 3] * bias_scale;
        v.x += b0; v.y += b1; v.z += b2; v.w += b3;
        v.x = (v.x >= 0.0f) ? v.x : v.x * negative_slope;
        v.y = (v.y >= 0.0f) ? v.y : v.y * negative_slope;
        v.z = (v.z >= 0.0f) ? v.z : v.z * negative_slope;
        v.w = (v.w >= 0.0f) ? v.w : v.w * negative_slope;
        y4[vidx] = v;
    }
}

void linear_epilogue_launch(torch::Tensor y, torch::Tensor bias, double bias_scale, double negative_slope) {
    const long long total = y.numel();
    const int n = (int)y.size(1);
    const int threads = 256;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    float bs = static_cast<float>(bias_scale);
    float ns = static_cast<float>(negative_slope);

    // Vectorized path for aligned, four-divisible rows.  The supplied problem has
    // N=8192 and CUDA allocations are suitably aligned.
    if ((total % 4LL) == 0 && (n % 4) == 0) {
        long long vt = total / 4LL;
        int blocks = (int)((vt + threads - 1) / threads);
        if (blocks > 65535) blocks = 65535;
        epilogue_vec4_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), vt, n, bs, ns);
    } else {
        int blocks = (int)((total + threads - 1) / threads);
        if (blocks > 65535) blocks = 65535;
        epilogue_scalar_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), total, n, bs, ns);
    }
}
'''

_ext = load_inline(
    name="fused_linear_leakyrelu_ext_v1",
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=["fused_linear_forward"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--use_fast_math"],
    extra_ldflags=["-lcublas"],
    with_cuda=True,
    verbose=False,
)

class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, multiplier, negative_slope):
        super(ModelNew, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.multiplier = multiplier
        self.negative_slope = negative_slope

    def forward(self, x):
        return _ext.fused_linear_forward(x, self.gemm.weight, self.gemm.bias,
                                         float(self.multiplier), float(self.negative_slope))