← Back to Leaderboard

The AI CUDA Engineer 👷

80_Gemm_Max_Subtract_GELUldg_memory_optimized_kernel_base

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


def module_fn(
    x: torch.Tensor,
    max_dim: int,
    weight: torch.Tensor,
    bias: torch.Tensor,
) -> torch.Tensor:
    """
    Performs a GEMM, followed by a max operation, subtraction, and GELU activation.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_features)
        max_dim (int): Dimension to perform max operation over
        weight (torch.Tensor): Weight matrix of shape (out_features, in_features)
        bias (torch.Tensor): Bias vector of shape (out_features)

    Returns:
        torch.Tensor: Output tensor of shape (batch_size, out_features)
    """
    x = F.linear(x, weight, bias)
    x = torch.max(x, dim=max_dim, keepdim=True).values
    x = x - x.mean(dim=1, keepdim=True)
    x = F.gelu(x)
    return x


class Model(nn.Module):
    """
    Model that performs a GEMM, followed by a max operation, subtraction, and GELU activation.
    """

    def __init__(self, in_features, out_features, max_dim):
        super(Model, self).__init__()
        gemm = nn.Linear(in_features, out_features)
        self.weight = nn.Parameter(gemm.weight)
        self.bias = nn.Parameter(gemm.bias)

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


batch_size = 128
in_features = 512
out_features = 1024
max_dim = 1


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


def get_init_inputs():
    return [in_features, out_features, max_dim]
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Model that performs a GEMM, followed by a max operation, subtraction, and GELU activation.
    """
    def __init__(self, in_features, out_features, max_dim):
        super(Model, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.max_dim = max_dim

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

        Returns:
            Output tensor of shape (batch_size, out_features)
        """
        x = self.gemm(x)
        x = torch.max(x, dim=self.max_dim, keepdim=True).values
        x = x - x.mean(dim=1, keepdim=True)
        x = torch.nn.functional.gelu(x)
        return x

batch_size = 128
in_features = 512
out_features = 1024
max_dim = 1

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

def get_init_inputs():
    return [in_features, out_features, max_dim]

Kernel Information

Related Kernels (Level 2, Task 80 • 80_Gemm_Max_Subtract_GELU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 warp_optimized_gemm_max_gelu_base 0.03 1.70 1.81
🥇 warp_optimized_shared_memory_edit_1 0.03 1.70 1.81
🥇 warp_aligned_gemm_base_edit_1 0.03 1.70 1.81
🥇 warp_optimized_shared_memory_base 0.03 1.70 1.81
🥇 warp_balanced_gemm_optimization_base 0.03 1.70 1.81
6 warp_aligned_gemm_base_base 0.03 1.58 1.67
7 warp_aligned_gemm_const_bias_base 0.03 1.47 1.56
8 warp_aligned_gemm_const_bias_edit_1 0.03 1.25 1.33
8 ldg_memory_optimized_kernel_base 0.03 1.25 1.33
10 indexing_optimized_fused_kernel_base 0.04 1.22 1.29
10 workload_balanced_kernel_base_base 0.04 1.22 1.29
10 shared_memory_reduction_warp_optimization_base_base 0.04 1.22 1.29
10 efficient_thread_mapping_kernel_base 0.04 1.22 1.29
14 block_tuned_fused_kernel_base_base 0.04 1.18 1.26
14 minimal_sync_optimized_kernel_base_base 0.04 1.18 1.26
16 warp_balanced_gemm_optimization_edit_1 0.04 1.15 1.22
17 warp_optimized_reduction_base_base 0.04 1.09 1.16
18 evenly_distributed_base 0.04 1.06 1.13
18 fused_gemm_max_reduce_gelu_base 0.04 1.06 1.13
20 fused_stride_loops_base 0.04 1.04 1.10
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
#include <float.h>

#define GEMM_BLOCK_DIM 32
#define REDUCE_BLOCK_SIZE 512

__device__ inline float gelu(float x) {
    return 0.5f * x * (1.0f + erf(x * 0.70710678118654752440f));
}

__global__ void optimized_gemm_kernel(const float* __restrict__ x,
                                      const float* __restrict__ weight,
                                      const float* __restrict__ bias,
                                      float* __restrict__ y,
                                      int batch, int in_features, int out_features) {
    __shared__ float tile_x[GEMM_BLOCK_DIM][GEMM_BLOCK_DIM];
    __shared__ float tile_w[GEMM_BLOCK_DIM][GEMM_BLOCK_DIM];

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

    #pragma unroll 4
    for (int t = 0; t < (in_features + GEMM_BLOCK_DIM - 1) / GEMM_BLOCK_DIM; t++) {
        int idx = t * GEMM_BLOCK_DIM + threadIdx.x;
        int idy = t * GEMM_BLOCK_DIM + threadIdx.y;

        tile_x[threadIdx.y][threadIdx.x] = (row < batch && idx < in_features) ?
            __ldg(&x[row * in_features + idx]) : 0.0f;
        tile_w[threadIdx.y][threadIdx.x] = (col < out_features && idy < in_features) ?
            __ldg(&weight[col * in_features + idy]) : 0.0f;
        __syncthreads();

        #pragma unroll
        for (int k = 0; k < GEMM_BLOCK_DIM; k++) {
            sum += tile_x[threadIdx.y][k] * tile_w[k][threadIdx.x];
        }
        __syncthreads();
    }

    if (row < batch && col < out_features) {
        y[row * out_features + col] = sum + bias[col];
    }
}

__global__ void fused_max_reduce_mean_gelu_kernel(float* data,
                                                   int batch,
                                                   int out_features,
                                                   int max_dim) {
    extern __shared__ float sdata[];
    const int tid = threadIdx.x;
    float max_val = -FLT_MAX;

    if (max_dim == 0) {
        const int col = blockIdx.x;
        
        #pragma unroll 2
        for (int i = tid; i < batch; i += REDUCE_BLOCK_SIZE) {
            max_val = fmaxf(max_val, __ldg(&data[i * out_features + col]));
        }
    } else {
        const int row = blockIdx.x;
        
        #pragma unroll 2
        for (int j = tid; j < out_features; j += REDUCE_BLOCK_SIZE) {
            max_val = fmaxf(max_val, __ldg(&data[row * out_features + j]));
        }
    }

    sdata[tid] = max_val;
    __syncthreads();

    if (REDUCE_BLOCK_SIZE >= 512) { if (tid < 256) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + 256]); } __syncthreads(); }
    if (REDUCE_BLOCK_SIZE >= 256) { if (tid < 128) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + 128]); } __syncthreads(); }
    if (REDUCE_BLOCK_SIZE >= 128) { if (tid <  64) { sdata[tid] = fmaxf(sdata[tid], sdata[tid +  64]); } __syncthreads(); }
    
    if (tid < 32) {
        volatile float* smem = sdata;
        if (REDUCE_BLOCK_SIZE >= 64) smem[tid] = fmaxf(smem[tid], smem[tid + 32]);
        smem[tid] = fmaxf(smem[tid], smem[tid + 16]);
        smem[tid] = fmaxf(smem[tid], smem[tid + 8]);
        smem[tid] = fmaxf(smem[tid], smem[tid + 4]);
        smem[tid] = fmaxf(smem[tid], smem[tid + 2]);
        smem[tid] = fmaxf(smem[tid], smem[tid + 1]);
    }

    if (tid == 0) {
        const float max_result = sdata[0];
        const float mean = max_result / (max_dim == 0 ? batch : out_features);
        sdata[0] = max_result;
        sdata[1] = mean;
    }
    __syncthreads();

    const float max_result = sdata[0];
    const float mean = sdata[1];

    if (max_dim == 0) {
        const int col = blockIdx.x;
        #pragma unroll 2
        for (int i = tid; i < batch; i += REDUCE_BLOCK_SIZE) {
            const int idx = i * out_features + col;
            data[idx] = gelu(data[idx] - mean);
        }
    } else {
        const int row = blockIdx.x;
        #pragma unroll 2
        for (int j = tid; j < out_features; j += REDUCE_BLOCK_SIZE) {
            const int idx = row * out_features + j;
            data[idx] = gelu(data[idx] - mean);
        }
    }
}

torch::Tensor forward(torch::Tensor x, int max_dim, torch::Tensor weight, torch::Tensor bias) {
    const int batch = x.size(0);
    const int in_features = x.size(1);
    const int out_features = weight.size(0);

    auto y = torch::empty({batch, out_features}, x.options());

    dim3 blockDimGEMM(GEMM_BLOCK_DIM, GEMM_BLOCK_DIM);
    dim3 gridDimGEMM((out_features + GEMM_BLOCK_DIM - 1) / GEMM_BLOCK_DIM,
                     (batch + GEMM_BLOCK_DIM - 1) / GEMM_BLOCK_DIM);
    
    optimized_gemm_kernel<<<gridDimGEMM, blockDimGEMM>>>(
        x.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        y.data_ptr<float>(),
        batch, in_features, out_features
    );

    auto max_out = torch::empty({max_dim == 0 ? 1 : batch, max_dim == 0 ? out_features : 1}, y.options());

    const int gridDim = max_dim == 0 ? out_features : batch;
    const int sharedMem = REDUCE_BLOCK_SIZE * sizeof(float);

    fused_max_reduce_mean_gelu_kernel<<<gridDim, REDUCE_BLOCK_SIZE, sharedMem>>>(
        max_out.data_ptr<float>(),
        batch,
        out_features,
        max_dim
    );

    return max_out;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Memory optimized GEMM and fused reduction");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.978 inst/cycle 0.000 5
Executed Ipc Elapsed 0.414 inst/cycle 0.000 5
Issue Slots Busy 25.176 % 0.029 5
Issued Ipc Active 1.008 inst/cycle 0.000 5
SM Busy 25.176 % 0.029 5
Memory Throughput 130066580830.922 byte/second 10518993340926861312.000 5
Mem Busy 10.274 % 0.065 5
Max Bandwidth 7.696 % 0.034 5
L1/TEX Hit Rate 66.670 % 0.000 5
L2 Hit Rate 75.338 % 0.174 5
Mem Pipes Busy 7.658 % 0.037 5
Warp Cycles Per Issued Instruction 15.528 cycle 0.012 5
Warp Cycles Per Executed Instruction 15.980 cycle 0.013 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.350 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 5.000 block 0.000 5
Block Limit Shared Mem 10.000 block 0.000 5
Block Limit Warps 4.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 24.618 % 0.000 5
Achieved Active Warps Per SM 15.758 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.
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 (24.6%) 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 657452.84 μs
Device Time 225.02 μs
Self CPU Time 55.65 μ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 657397.19 μs
Device Time 225.02 μs
Self CPU Time 120.15 μ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 656726.81 μs
Device Time 0.00 μs
Self CPU Time 123.70 μ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 653630.71 μs
Device Time 0.00 μs
Self CPU Time 653630.71 μ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 570220.47 μs
Device Time 35387.55 μs
Self CPU Time 570220.47 μs
Self Device Time 35387.55 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
optimized_gemm_kernel(float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 209889.90 μs
Self CPU Time 0.00 μs
Self Device Time 209889.90 μ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 76523.20 μs
Device Time 607447.92 μs
Self CPU Time 11487.29 μ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 65037.69 μs
Device Time 607447.92 μs
Self CPU Time 15921.08 μs
Self Device Time 607447.92 μ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 607525.52 μs
Self CPU Time 0.00 μs
Self Device Time 607525.52 μ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
45295 warnings generated when compiling for host.
Suppressed 45324 warnings (45277 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_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:14:39 bugprone-easily-swappable-parameters
14 | __global__ void optimized_gemm_kernel(const float* __restrict__ x,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 | const float* __restrict__ weight,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:14:65: note: the first parameter in the range is 'x'
14 | __global__ void optimized_gemm_kernel(const float* __restrict__ x,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:16:65: note: the last parameter in the range is 'bias'
16 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:22:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | int row = blockIdx.y * GEMM_BLOCK_DIM + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:23:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
23 | int col = blockIdx.x * GEMM_BLOCK_DIM + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:28:19: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | int idx = t * GEMM_BLOCK_DIM + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:29:19: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | int idy = t * GEMM_BLOCK_DIM + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:54:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
54 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:58:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
58 | const int col = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:65:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
65 | const int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:92:41: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
92 | const float mean = max_result / (max_dim == 0 ? batch : out_features);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:98:17: warning: Value stored to 'max_result' during its initialization is never read [clang-analyzer-deadcode.DeadStores]
98 | const float max_result = sdata[0];
| ^~~~~~~~~~ ~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:98:17: note: Value stored to 'max_result' during its initialization is never read
98 | const float max_result = sdata[0];
| ^~~~~~~~~~ ~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:102:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
102 | const int col = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:109:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
109 | const int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:118:37: warning: the parameter 'x' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
118 | torch::Tensor forward(torch::Tensor x, int max_dim, torch::Tensor weight, torch::Tensor bias) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:118:67: warning: the parameter 'weight' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
118 | torch::Tensor forward(torch::Tensor x, int max_dim, torch::Tensor weight, torch::Tensor bias) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:118:89: warning: the parameter 'bias' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
118 | torch::Tensor forward(torch::Tensor x, int max_dim, torch::Tensor weight, torch::Tensor bias) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:119:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
119 | const int batch = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:120:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
120 | const int in_features = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_80/b9_s1_ldg_memory_optimized_kernel/base/base.cu:121:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
121 | const int out_features = weight.size(0);
| ^