← Back to Leaderboard

The AI CUDA Engineer 👷

98_Matmul_AvgPool_GELU_Scale_Maxunrolled_fused_pipeline_base_base

Level 2 • Task 98
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(
    x: torch.Tensor,
    pool_kernel_size: int,
    scale_factor: float,
    weight: torch.Tensor,
    bias: torch.Tensor,
) -> torch.Tensor:
    """
    Implements Matmul_AvgPool_GELU_Scale_Max pattern using functional operations.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_features)
        pool_kernel_size (int): Kernel size for average pooling
        scale_factor (float): Scale factor to multiply features by
        weight (torch.Tensor): Weight matrix for linear layer
        bias (torch.Tensor): Bias vector for linear layer

    Returns:
        torch.Tensor: Output tensor of shape (batch_size,)
    """
    x = F.linear(x, weight, bias)
    x = F.avg_pool1d(x.unsqueeze(1), kernel_size=pool_kernel_size).squeeze(1)
    x = F.gelu(x)
    x = x * scale_factor
    x = torch.max(x, dim=1).values
    return x


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__()
        gemm = nn.Linear(in_features, out_features)
        self.weight = gemm.weight
        self.bias = gemm.bias

    def forward(self, x, pool_kernel_size, scale_factor, fn=module_fn):
        return fn(x, pool_kernel_size, scale_factor, self.weight, self.bias)


batch_size = 128
in_features = 512
out_features = 256
pool_kernel_size = 4
scale_factor = 2.0


def get_inputs():
    return [torch.randn(batch_size, in_features), pool_kernel_size, scale_factor]


def get_init_inputs():
    return [in_features, out_features, pool_kernel_size, scale_factor]
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 = 128
in_features = 512
out_features = 256
pool_kernel_size = 4
scale_factor = 2.0

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

def get_init_inputs():
    return [in_features, out_features, pool_kernel_size, scale_factor]

Kernel Information

Related Kernels (Level 2, Task 98 • 98_Matmul_AvgPool_GELU_Scale_Max)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 unrolled_fused_pipeline_base_base 0.03 1.04 1.50
🥇 shared_memory_optimization_base 0.03 1.04 1.50
🥇 modular_fused_pipeline_base 0.03 1.04 1.50
🥇 strided_fused_pipeline_optimization_base 0.03 1.04 1.50
🥇 fused_pipeline_base 0.03 1.04 1.50
6 fused_pipeline_optimized_block_size_base 0.03 1.01 1.45
6 shared_memory_optimized_base_base 0.03 1.01 1.45
6 strided_fused_pipeline_optimization_base 0.03 1.01 1.45
6 memory_coalesced_fused_pipeline_base 0.03 1.01 1.45
6 even_workload_fused_kernel_base 0.03 1.01 1.45
6 warp_divergence_optimized_base 0.03 1.01 1.45
6 fused_pool_act_max_warp_base 0.03 1.01 1.45
13 constant_memory_fusion_base 0.03 0.97 1.41
14 fusedpoolactmax_base 0.03 0.95 1.37
14 constant_memory_optimization_base_base 0.03 0.95 1.37
16 fused_pipeline_shared_memory_base 0.03 0.92 1.33
17 fused_actmax_atomic_base 0.04 0.80 1.16
17 aligned_matmul_pool_act_max_edit_1 0.04 0.80 1.16
17 aligned_vectorized_ldg_optimized_base 0.04 0.80 1.16
17 fused_matmul_pool_act_max_base 0.04 0.80 1.16
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
#include <float.h>

#ifndef TILE_SIZE
#define TILE_SIZE 16
#endif

//--------------------------------------------------------------------------
// Fused Matrix Multiplication with Bias Addition Kernel
// Computes: C = A * (B^T) + bias, where A is [M x K], B is [N x K] (stored row-wise),
// and bias is a vector of length N. Uses shared memory tiling for improved performance.
//--------------------------------------------------------------------------
__global__ void FusedMatMulBiasKernel(const float* __restrict__ A,
                                      const float* __restrict__ B,
                                      const float* __restrict__ bias,
                                      float* __restrict__ C,
                                      int M, int N, int K) {
    __shared__ float Asub[TILE_SIZE][TILE_SIZE];
    __shared__ float Bsub[TILE_SIZE][TILE_SIZE];

    int row = blockIdx.y * TILE_SIZE + threadIdx.y;
    int col = blockIdx.x * TILE_SIZE + threadIdx.x;
    float sum = 0.0f;

    // Loop over tiles
    for (int t = 0; t < (K + TILE_SIZE - 1) / TILE_SIZE; t++) {
        int tiled_k = t * TILE_SIZE;
        // Load A tile
        if (row < M && (tiled_k + threadIdx.x) < K)
            Asub[threadIdx.y][threadIdx.x] = A[row * K + tiled_k + threadIdx.x];
        else
            Asub[threadIdx.y][threadIdx.x] = 0.0f;

        // Load B tile (B is stored such that we use its transpose logic)
        if (col < N && (tiled_k + threadIdx.y) < K)
            Bsub[threadIdx.y][threadIdx.x] = B[col * K + tiled_k + threadIdx.y];
        else
            Bsub[threadIdx.y][threadIdx.x] = 0.0f;

        __syncthreads();

#pragma unroll
        // Multiply the two tiles together
        for (int i = 0; i < TILE_SIZE; i++) {
            sum += Asub[threadIdx.y][i] * Bsub[i][threadIdx.x];
        }
        __syncthreads();
    }

    // Write result with bias addition
    if (row < M && col < N) {
        C[row * N + col] = sum + bias[col];
    }
}

//--------------------------------------------------------------------------
// Fused Pooling, Activation, Scaling and Max Reduction Kernel
// Input: the linear output from the previous stage of shape [M x N].
// Operation per row:
//   1. Average Pooling: groups contiguous elements with pool_kernel_size. 
//      (If the group is incomplete at the end, it computes the average over available elements.)
//   2. GELU Activation (using the approximate formula: 0.5 * x * (1 + erf(x * 0.70710678))).
//   3. Scaling by scale_factor.
//   4. Maximum reduction over the pooled/activated values.
// Each block processes one row; multiple threads in a block cooperatively reduce the maximum.
//--------------------------------------------------------------------------
__global__ void FusedPoolActMaxKernel(const float* __restrict__ linear_output,
                                      float* __restrict__ output,
                                      int M, int N,
                                      int pool_kernel_size,
                                      int output_length,
                                      float scale_factor) {
    // One block per row
    int row = blockIdx.x;
    int tid = threadIdx.x;
    float local_max = -FLT_MAX;

    // Each thread processes multiple pooling bins using striding
    for (int bin = tid; bin < output_length; bin += blockDim.x) {
        int start = bin * pool_kernel_size;
        float sum = 0.0f;
        int count = 0;

#pragma unroll
        for (int j = 0; j < pool_kernel_size; j++) {
            int col = start + j;
            if (col < N) {
                sum += linear_output[row * N + col];
                count++;
            }
        }
        float avg = sum / count;  // Average pooling result
        // Apply GELU activation: 0.5 * avg * (1 + erf(avg * 0.70710678))
        float gelu = 0.5f * avg * (1.0f + erff(avg * 0.70710678f));
        // Scale the activated output
        gelu *= scale_factor;
        local_max = fmaxf(local_max, gelu);
    }

    // Reduction within block using shared memory
    extern __shared__ float sdata[];  // Dynamically allocated shared memory
    sdata[tid] = local_max;
    __syncthreads();

#pragma unroll
    // Parallel reduction (assumes blockDim.x is a power of 2)
    for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) {
            sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]);
        }
        __syncthreads();
    }

    // The first thread writes the maximum value for this row
    if (tid == 0) {
        output[row] = sdata[0];
    }
}

//--------------------------------------------------------------------------
// Forward function that chains the fused operations
// Steps:
// 1. Compute linear transformation: linear = x * (weight^T) + bias using a tiled matmul kernel.
// 2. Apply fused average pooling, GELU activation, scaling, and maximum reduction across pooled bins.
//--------------------------------------------------------------------------

torch::Tensor forward(
    torch::Tensor x,
    int pool_kernel_size,
    float scale_factor,
    torch::Tensor weight,
    torch::Tensor bias) {

    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(weight.is_cuda(), "weight must be a CUDA tensor");
    TORCH_CHECK(bias.is_cuda(), "bias must be a CUDA tensor");

    // Ensure tensors are contiguous
    x = x.contiguous();
    weight = weight.contiguous();
    bias = bias.contiguous();

    // Dimensions
    int M = x.size(0);        // Batch size (number of rows)
    int K = x.size(1);        // Input features
    int N = weight.size(0);   // Output features (number of rows in weight, since weight is transposed)

    auto options = torch::TensorOptions().dtype(x.dtype()).device(x.device());
    // Allocate tensor for the linear transformation results
    auto linear_output = torch::empty({M, N}, options);

    // Launch fused matrix multiplication + bias addition kernel
    dim3 blockDim(TILE_SIZE, TILE_SIZE);
    dim3 gridDim((N + TILE_SIZE - 1) / TILE_SIZE, (M + TILE_SIZE - 1) / TILE_SIZE);
    FusedMatMulBiasKernel<<<gridDim, blockDim>>>(
        x.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        linear_output.data_ptr<float>(),
        M, N, K);

    // Determine pooling output length
    int output_length = (N + pool_kernel_size - 1) / pool_kernel_size;

    // Allocate tensor for final output (one value per batch row)
    auto output = torch::empty({M}, options);

    // Launch fused pooling, activation, scaling, and max reduction kernel
    // One block per row, use 256 threads (or adjust based on output_length)
    int threads = 256;
    size_t sharedMemSize = threads * sizeof(float);
    FusedPoolActMaxKernel<<<M, threads, sharedMemSize>>>(
         linear_output.data_ptr<float>(),
         output.data_ptr<float>(),
         M, N, pool_kernel_size, output_length, scale_factor);

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Fused CUDA forward (MatMul+Bias, Pool, GELU, Scale, Max Reduction)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.370 inst/cycle 0.000 5
Executed Ipc Elapsed 0.156 inst/cycle 0.000 5
Issue Slots Busy 9.624 % 0.243 5
Issued Ipc Active 0.386 inst/cycle 0.001 5
SM Busy 9.624 % 0.243 5
Memory Throughput 35217635163.348 byte/second 81680544111972768.000 5
Mem Busy 8.250 % 0.020 5
Max Bandwidth 4.356 % 0.002 5
L1/TEX Hit Rate 74.420 % 0.000 5
L2 Hit Rate 91.836 % 0.047 5
Mem Pipes Busy 3.708 % 0.001 5
Warp Cycles Per Issued Instruction 19.034 cycle 0.068 5
Warp Cycles Per Executed Instruction 19.784 cycle 0.073 5
Avg. Active Threads Per Warp 31.850 0.000 5
Avg. Not Predicated Off Threads Per Warp 20.470 0.000 5
Max Active Clusters 0.000 cluster 0.000 5
Max Cluster Size 8.000 block 0.000 5
Overall GPU Occupancy 0.000 % 0.000 5
Cluster Occupancy 0.000 % 0.000 5
Block Limit SM 32.000 block 0.000 5
Block Limit Registers 8.000 block 0.000 5
Block Limit Shared Mem 16.000 block 0.000 5
Block Limit Warps 8.000 block 0.000 5
Theoretical Active Warps per SM 64.000 warp 0.000 5
Theoretical Occupancy 100.000 % 0.000 5
Achieved Occupancy 12.216 % 0.000 5
Achieved Active Warps Per SM 7.816 warp 0.000 5
Analysis Rules
Rule Description
WRN HighPipeUtilization All compute pipelines are under-utilized. Either this kernel is very small or it doesn't issue enough warps per scheduler. Check the Launch Statistics and Scheduler Statistics sections for further details.
INF CPIStall Check the Warp Stall Sampling (All Cycles) table for the top stall locations in your source based on sampling data. The Kernel Profiling Guide (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-reference) provides more details on each stall reason.
WRN ThreadDivergence Instructions are executed in warps, which are groups of 32 threads. Optimal instruction throughput is achieved if all 32 threads of a warp execute the same instruction. The chosen launch configuration, early thread completion, and divergent flow control can significantly lower the number of active threads in a warp per cycle. This kernel achieves an average of 31.8 threads being active per cycle. This is further reduced to 20.5 threads per warp due to predication. The compiler may use predication to avoid an actual branch. Instead, all instructions are scheduled, but a per-thread condition code or predicate controls which threads execute the instructions. Try to avoid different execution paths within a warp when possible. In addition, ensure your kernel makes use of Independent Thread Scheduling, which allows a warp to reconverge after a data-dependent conditional block by explicitly calling __syncwarp().
WRN Occupancy This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (12.2%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy.
Operation / Metric Value Unit
aten::to
CPU Time 933789.33 μs
Device Time 52.00 μs
Self CPU Time 65.44 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::_to_copy
CPU Time 933723.89 μs
Device Time 52.00 μs
Self CPU Time 140.41 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::empty_strided
CPU Time 933253.44 μs
Device Time 0.00 μs
Self CPU Time 192.27 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaDeviceGetStreamPriorityRange
CPU Time 921152.39 μs
Device Time 0.00 μs
Self CPU Time 921152.39 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaLaunchKernel
CPU Time 448699.35 μs
Device Time 30315.28 μs
Self CPU Time 448699.35 μs
Self Device Time 30315.28 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
FusedMatMulBiasKernel(float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 159551.35 μs
Self CPU Time 0.00 μs
Self Device Time 159551.35 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::zero_
CPU Time 67252.02 μs
Device Time 522503.62 μs
Self CPU Time 12263.06 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::fill_
CPU Time 54990.97 μs
Device Time 522503.62 μs
Self CPU Time 15884.87 μs
Self Device Time 522503.62 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<int>, at::detail::Array<char*, 1> >(int, at::native::FillFunctor<int>, at::detail::Array<char*, 1>)
CPU Time 0.00 μs
Device Time 522503.62 μs
Self CPU Time 0.00 μs
Self Device Time 522503.62 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
Status: Completed
45289 warnings generated when compiling for host.
Suppressed 45325 warnings (45278 in non-user code, 47 NOLINT).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:16:39 bugprone-easily-swappable-parameters
16 | __global__ void FusedMatMulBiasKernel(const float* __restrict__ A,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 | const float* __restrict__ B,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:16:65: note: the first parameter in the range is 'A'
16 | __global__ void FusedMatMulBiasKernel(const float* __restrict__ A,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:18:65: note: the last parameter in the range is 'bias'
18 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:24:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | int row = blockIdx.y * TILE_SIZE + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:25:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
25 | int col = blockIdx.x * TILE_SIZE + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:72:39: warning: 5 adjacent parameters of 'FusedPoolActMaxKernel' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
72 | int M, int N,
| ^~~~~~~~~~~~~
73 | int pool_kernel_size,
| ~~~~~~~~~~~~~~~~~~~~~
74 | int output_length,
| ~~~~~~~~~~~~~~~~~~
75 | float scale_factor) {
| ~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:72:43: note: the first parameter in the range is 'M'
72 | int M, int N,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:75:45: note: the last parameter in the range is 'scale_factor'
75 | float scale_factor) {
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:75:39: note: 'int' and 'float' may be implicitly converted
75 | float scale_factor) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:77:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:78:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
78 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:82:53: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
82 | for (int bin = tid; bin < output_length; bin += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:95:27: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
95 | float avg = sum / count; // Average pooling result
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:147:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
147 | int M = x.size(0); // Batch size (number of rows)
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:148:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
148 | int K = x.size(1); // Input features
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_98/b6_s3_unrolled_fused_pipeline_base/base/base.cu:149:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
149 | int N = weight.size(0); // Output features (number of rows in weight, since weight is transposed)
| ^