gpt-5.5-priority · original · l123_single_gpt
correct 98_Matmul_AvgPool_GELU_Scale_Max.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
1.38 μs
ref runtime
2.70 μs
speedup
1.96x
started
2026-05-05T00:01:56Z
timingkernelbench.timing
kernel runtime
1.38 μs
ref runtime
2.70 μs
speedup
1.96x
kernel mean / median / std
1.38 / — / 0.00 μs
ref mean / median / std
2.70 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
max abs error
2.44e-06
mean abs error
4.59e-07
max rel error
6.90e-06
mean rel error
1.31e-06
gpu memoryextended_metrics.measure_memory
kernel peak
595.07 MB
ref peak
611.06 MB
kernel / ref
0.97x
kernel launches / fusiontorch.profiler
kernel launches
4
ref launches
20
fusion ratio (ref / kernel)
5.00x
total cuda time
66 μs
energyNVML (pynvml)
kernel mJ / run
318.70
ref mJ / run
1537.84
ratio (ref / kernel)
4.83x
avg power
232.34 W
ref avg power
568.79 W
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.854
dram util %
85.4%
compute util %
44.0%
bottleneck
memory-bound
dominant pipe
FP32
arithmetic intensity
—
ridge point
20.00
roofline / occupancynsight_hardware_counters
dram bandwidth
2859.97 GB/s
dram util %
85.4%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
236.2%
bottleneck
memory-bound
dominant pipe %
44.0%
arithmetic intensity
—
ridge point
20.00
L1 hit %
—
L2 hit %
159.4%
ld sectors / req
11.99
st sectors / req
—
regs / thread
85
smem / block
8192 B
block size
768
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
5314.7%
short_scoreboard
921.1%
mio_throttle
641.2%
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    A model implementing the pattern "Matmul_AvgPool_GELU_Scale_Max".
    """
    def __init__(self, in_features, out_features, pool_kernel_size, scale_factor):
        super(Model, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.avg_pool = nn.AvgPool1d(kernel_size=pool_kernel_size)
        self.scale_factor = scale_factor

    def forward(self, x):
        """
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_features).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_features).
        """
        x = self.matmul(x)
        x = self.avg_pool(x.unsqueeze(1)).squeeze(1)
        x = torch.nn.functional.gelu(x)
        x = x * self.scale_factor
        x = torch.max(x, dim=1).values
        return x

batch_size = 1024
in_features = 8192
out_features = 8192
pool_kernel_size = 16
scale_factor = 2.0

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

def get_init_inputs():
    return [in_features, out_features, pool_kernel_size, scale_factor]
turn 0 · FINAL · 1 tool call(s) · 83.7s turn · 83.7s LLM · 8,186 chars (click to expand)
turn 083.7s turn · 83.7s LLM · 0.0s tools · FINAL
reasoning
**Allocating CUDA tensor** I’m considering how to use `at::cuda::getCurrentCUDAStream`, which means I need to include `<ATen/cuda/CUDAContext.h>`. I'll allocate a tensor with `at::empty({K, N}, x.options())`. I need to ensure that all tensors are in float32 on CUDA, but I’m not sure if I’ll implement checks for that. Instead, I could just use `x.size()` to gather relevant dimensions. It feels a bit uncertain, but I’ll figure it out!
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 fused_forward_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool, double scale);\n\ntorch::Tensor fused_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool, double scale) {\n return fused_forward_cuda(x, weight, bias, pool, scale);\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#include <float.h>\n#include <math.h>\n\n__global__ void pool_weight_bias_kernel(const float* __restrict__ W,\n const float* __restrict__ bias,\n float* __restrict__ WP,\n float* __restrict__ BP,\n int K, int N, int pool) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = K * N;\n if (idx >= total) return;\n\n // idx laid out as (pooled-output, input-feature) for coalesced reads\n int n = idx / K;\n int k = idx - n * K;\n int base_o = n * pool;\n\n float s = 0.0f;\n #pragma unroll\n for (int r = 0; r < 16; ++r) {\n if (r < pool) s += W[(base_o + r) * K + k];\n }\n float invp = 1.0f / (float)pool;\n // Transposed/packed as [K, N], which is the layout consumed by the GEMM.\n WP[k * N + n] = s * invp;\n\n if (k == 0) {\n float bs = 0.0f;\n #pragma unroll\n for (int r = 0; r < 16; ++r) {\n if (r < pool) bs += bias[base_o + r];\n }\n BP[n] = bs * invp;\n }\n}\n\n#define BM 16\n#define BN 16\n#define BK 32\n\n__global__ void matmul_pooled_kernel(const float* __restrict__ X,\n const float* __restrict__ WP,\n const float* __restrict__ BP,\n float* __restrict__ C,\n int M, int K, int N) {\n __shared__ float As[BM][BK];\n __shared__ float Bs[BK][BN];\n\n int tx = threadIdx.x;\n int ty = threadIdx.y;\n int row = blockIdx.y * BM + ty;\n int col = blockIdx.x * BN + tx;\n int tid = ty * BN + tx;\n\n float acc = 0.0f;\n\n for (int t = 0; t < K; t += BK) {\n // Cooperative load A tile (BM x BK), 512 elements.\n for (int l = tid; l < BM * BK; l += BM * BN) {\n int i = l / BK;\n int kk = l - i * BK;\n int gr = blockIdx.y * BM + i;\n int gk = t + kk;\n As[i][kk] = (gr < M && gk < K) ? X[gr * K + gk] : 0.0f;\n }\n // Cooperative load packed pooled-weight tile (BK x BN), 512 elements.\n for (int l = tid; l < BK * BN; l += BM * BN) {\n int kk = l / BN;\n int j = l - kk * BN;\n int gk = t + kk;\n int gc = blockIdx.x * BN + j;\n Bs[kk][j] = (gk < K && gc < N) ? WP[gk * N + gc] : 0.0f;\n }\n __syncthreads();\n\n #pragma unroll\n for (int kk = 0; kk < BK; ++kk) {\n acc = fmaf(As[ty][kk], Bs[kk][tx], acc);\n }\n __syncthreads();\n }\n\n if (row < M && col < N) {\n C[row * N + col] = acc + BP[col];\n }\n}\n\n__device__ __forceinline__ float gelu_exact(float x) {\n return 0.5f * x * (1.0f + erff(x * 0.70710678118654752440f));\n}\n\n__global__ void gelu_scale_rowmax_kernel(const float* __restrict__ C,\n float* __restrict__ Y,\n int M, int N, float scale) {\n int row = blockIdx.x;\n int tid = threadIdx.x;\n __shared__ float smem[256];\n\n float m = -FLT_MAX;\n for (int j = tid; j < N; j += blockDim.x) {\n float v = gelu_exact(C[row * N + j]) * scale;\n m = fmaxf(m, v);\n }\n smem[tid] = m;\n __syncthreads();\n\n for (int stride = 128; stride > 0; stride >>= 1) {\n if (tid < stride) smem[tid] = fmaxf(smem[tid], smem[tid + stride]);\n __syncthreads();\n }\n if (tid == 0) Y[row] = smem[0];\n}\n\ntorch::Tensor fused_forward_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool64, double scale64) {\n const int M = (int)x.size(0);\n const int K = (int)x.size(1);\n const int O = (int)weight.size(0);\n const int pool = (int)pool64;\n const int N = O / pool;\n\n auto opts = x.options();\n torch::Tensor wp = torch::empty({K, N}, opts);\n torch::Tensor bp = torch::empty({N}, opts);\n torch::Tensor c = torch::empty({M, N}, opts);\n torch::Tensor y = torch::empty({M}, opts);\n\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n\n int total = K * N;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n pool_weight_bias_kernel<<<blocks, threads, 0, stream>>>(\n weight.data_ptr<float>(), bias.data_ptr<float>(), wp.data_ptr<float>(), bp.data_ptr<float>(), K, N, pool);\n\n dim3 block(BN, BM);\n dim3 grid((N + BN - 1) / BN, (M + BM - 1) / BM);\n matmul_pooled_kernel<<<grid, block, 0, stream>>>(\n x.data_ptr<float>(), wp.data_ptr<float>(), bp.data_ptr<float>(), c.data_ptr<float>(), M, K, N);\n\n gelu_scale_rowmax_kernel<<<M, 256, 0, stream>>>(\n c.data_ptr<float>(), y.data_ptr<float>(), M, N, (float)scale64);\n\n return y;\n}\n'''\n\n_ext = load_inline(\n name='matmul_avgpool_gelu_scale_max_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 verbose=False,\n)\n\nclass ModelNew(nn.Module):\n \"\"\"Fused implementation of Linear -> AvgPool1d -> GELU -> scale -> row max.\"\"\"\n def __init__(self, in_features, out_features, pool_kernel_size, scale_factor):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.avg_pool = nn.AvgPool1d(kernel_size=pool_kernel_size)\n self.scale_factor = scale_factor\n self.pool_kernel_size = pool_kernel_size\n\n def forward(self, x):\n return _ext.fused_forward(x.contiguous(), self.matmul.weight.contiguous(), self.matmul.bias.contiguous(), int(self.pool_kernel_size), float(self.scale_factor))\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (5 / 5) correctness trials all passed. Kernel runtime: 1.38 μs Runtime stats: mean=1.38μs median=?μs std=0.00μs Numerical precision: max_abs_err=2.44e-06 mean_abs_err=4.59e-07 max_rel_err=6.90e-06 Memory: 595.07 MB peak (ref: 611.06 MB, ratio: 0.9738x) Kernel launches: 4 (ref: 20, fusion ratio: 5.0) Energy: 318.7 mJ/run (ref: 1537.84 mJ, ratio: 4.8254x) SOL score: 0.8537
final submitted kernel (187 lines, 6,183 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 fused_forward_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool, double scale);

torch::Tensor fused_forward(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool, double scale) {
    return fused_forward_cuda(x, weight, bias, pool, scale);
}
'''

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

__global__ void pool_weight_bias_kernel(const float* __restrict__ W,
                                        const float* __restrict__ bias,
                                        float* __restrict__ WP,
                                        float* __restrict__ BP,
                                        int K, int N, int pool) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total = K * N;
    if (idx >= total) return;

    // idx laid out as (pooled-output, input-feature) for coalesced reads
    int n = idx / K;
    int k = idx - n * K;
    int base_o = n * pool;

    float s = 0.0f;
    #pragma unroll
    for (int r = 0; r < 16; ++r) {
        if (r < pool) s += W[(base_o + r) * K + k];
    }
    float invp = 1.0f / (float)pool;
    // Transposed/packed as [K, N], which is the layout consumed by the GEMM.
    WP[k * N + n] = s * invp;

    if (k == 0) {
        float bs = 0.0f;
        #pragma unroll
        for (int r = 0; r < 16; ++r) {
            if (r < pool) bs += bias[base_o + r];
        }
        BP[n] = bs * invp;
    }
}

#define BM 16
#define BN 16
#define BK 32

__global__ void matmul_pooled_kernel(const float* __restrict__ X,
                                     const float* __restrict__ WP,
                                     const float* __restrict__ BP,
                                     float* __restrict__ C,
                                     int M, int K, int N) {
    __shared__ float As[BM][BK];
    __shared__ float Bs[BK][BN];

    int tx = threadIdx.x;
    int ty = threadIdx.y;
    int row = blockIdx.y * BM + ty;
    int col = blockIdx.x * BN + tx;
    int tid = ty * BN + tx;

    float acc = 0.0f;

    for (int t = 0; t < K; t += BK) {
        // Cooperative load A tile (BM x BK), 512 elements.
        for (int l = tid; l < BM * BK; l += BM * BN) {
            int i = l / BK;
            int kk = l - i * BK;
            int gr = blockIdx.y * BM + i;
            int gk = t + kk;
            As[i][kk] = (gr < M && gk < K) ? X[gr * K + gk] : 0.0f;
        }
        // Cooperative load packed pooled-weight tile (BK x BN), 512 elements.
        for (int l = tid; l < BK * BN; l += BM * BN) {
            int kk = l / BN;
            int j = l - kk * BN;
            int gk = t + kk;
            int gc = blockIdx.x * BN + j;
            Bs[kk][j] = (gk < K && gc < N) ? WP[gk * N + gc] : 0.0f;
        }
        __syncthreads();

        #pragma unroll
        for (int kk = 0; kk < BK; ++kk) {
            acc = fmaf(As[ty][kk], Bs[kk][tx], acc);
        }
        __syncthreads();
    }

    if (row < M && col < N) {
        C[row * N + col] = acc + BP[col];
    }
}

__device__ __forceinline__ float gelu_exact(float x) {
    return 0.5f * x * (1.0f + erff(x * 0.70710678118654752440f));
}

__global__ void gelu_scale_rowmax_kernel(const float* __restrict__ C,
                                         float* __restrict__ Y,
                                         int M, int N, float scale) {
    int row = blockIdx.x;
    int tid = threadIdx.x;
    __shared__ float smem[256];

    float m = -FLT_MAX;
    for (int j = tid; j < N; j += blockDim.x) {
        float v = gelu_exact(C[row * N + j]) * scale;
        m = fmaxf(m, v);
    }
    smem[tid] = m;
    __syncthreads();

    for (int stride = 128; stride > 0; stride >>= 1) {
        if (tid < stride) smem[tid] = fmaxf(smem[tid], smem[tid + stride]);
        __syncthreads();
    }
    if (tid == 0) Y[row] = smem[0];
}

torch::Tensor fused_forward_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, int64_t pool64, double scale64) {
    const int M = (int)x.size(0);
    const int K = (int)x.size(1);
    const int O = (int)weight.size(0);
    const int pool = (int)pool64;
    const int N = O / pool;

    auto opts = x.options();
    torch::Tensor wp = torch::empty({K, N}, opts);
    torch::Tensor bp = torch::empty({N}, opts);
    torch::Tensor c = torch::empty({M, N}, opts);
    torch::Tensor y = torch::empty({M}, opts);

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    int total = K * N;
    int threads = 256;
    int blocks = (total + threads - 1) / threads;
    pool_weight_bias_kernel<<<blocks, threads, 0, stream>>>(
        weight.data_ptr<float>(), bias.data_ptr<float>(), wp.data_ptr<float>(), bp.data_ptr<float>(), K, N, pool);

    dim3 block(BN, BM);
    dim3 grid((N + BN - 1) / BN, (M + BM - 1) / BM);
    matmul_pooled_kernel<<<grid, block, 0, stream>>>(
        x.data_ptr<float>(), wp.data_ptr<float>(), bp.data_ptr<float>(), c.data_ptr<float>(), M, K, N);

    gelu_scale_rowmax_kernel<<<M, 256, 0, stream>>>(
        c.data_ptr<float>(), y.data_ptr<float>(), M, N, (float)scale64);

    return y;
}
'''

_ext = load_inline(
    name='matmul_avgpool_gelu_scale_max_ext',
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=['fused_forward'],
    extra_cflags=['-O3'],
    extra_cuda_cflags=['-O3'],
    verbose=False,
)

class ModelNew(nn.Module):
    """Fused implementation of Linear -> AvgPool1d -> GELU -> scale -> row max."""
    def __init__(self, in_features, out_features, pool_kernel_size, scale_factor):
        super(ModelNew, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.avg_pool = nn.AvgPool1d(kernel_size=pool_kernel_size)
        self.scale_factor = scale_factor
        self.pool_kernel_size = pool_kernel_size

    def forward(self, x):
        return _ext.fused_forward(x.contiguous(), self.matmul.weight.contiguous(), self.matmul.bias.contiguous(), int(self.pool_kernel_size), float(self.scale_factor))