← Back to Leaderboard

The AI CUDA Engineer 👷

99_Matmul_GELU_Softmaxfused_linear_gelu_softmax_optimized_base

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


def module_fn(
    x: torch.Tensor,
    weight: torch.Tensor,
    bias: torch.Tensor,
) -> torch.Tensor:
    """
    Applies linear transformation, GELU activation, and softmax.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_features)
        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 after applying linear, GELU and softmax,
            with shape (batch_size, out_features)
    """
    x = F.linear(x, weight, bias)
    x = F.gelu(x)
    x = F.softmax(x, dim=1)
    return x


class Model(nn.Module):
    """
    Simple model that performs a matrix multiplication, applies GELU, and then applies Softmax.
    """

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

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


batch_size = 128
in_features = 100
out_features = 10


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


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

class Model(nn.Module):
    """
    Simple model that performs a matrix multiplication, applies GELU, and then applies Softmax.
    """
    def __init__(self, in_features, out_features):
        super(Model, self).__init__()
        self.linear = nn.Linear(in_features, out_features)

    def forward(self, x):
        x = self.linear(x)
        x = torch.nn.functional.gelu(x)
        x = torch.nn.functional.softmax(x, dim=1)
        return x

batch_size = 128
in_features = 100
out_features = 10

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

def get_init_inputs():
    return [in_features, out_features]

Kernel Information

Related Kernels (Level 2, Task 99 • 99_Matmul_GELU_Softmax)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 fused_opt_base 0.01 2.78 2.26
🥇 warp_divergence_minimized_kernel_base 0.01 2.78 2.26
🥇 block_size_experiment_fused_kernel_base 0.01 2.78 2.26
🥇 optimized_fused_kernel_base 0.01 2.78 2.26
🥇 fused_shared_mem_kernel_base 0.01 2.78 2.26
🥇 balanced_workload_fused_kernel_base 0.01 2.78 2.26
7 reduced_sync_matmul_gelu_softmax_base 0.01 2.53 2.06
7 aligned_ldg_fused_kernel_base_base 0.01 2.53 2.06
7 warp_optimized_fused_kernel_base_base 0.01 2.53 2.06
7 fused_ldg_vec_kernel_base 0.01 2.53 2.06
7 unrolled_fused_matmul_gelu_softmax_base_base 0.01 2.53 2.06
7 fused_optim_base 0.01 2.53 2.06
7 fused_linear_gelu_softmax_optimized_base 0.01 2.53 2.06
7 warp_reduced_fused_kernel_base 0.01 2.53 2.06
7 fused_nodivergence_kernel_base 0.01 2.53 2.06
7 modular_device_functions_base 0.01 2.53 2.06
7 optimized_linear_gelu_softmax_base 0.01 2.53 2.06
7 optimized_linear_gelu_softmax_edit_1 0.01 2.53 2.06
7 optimized_linear_gelu_softmax_base 0.01 2.53 2.06
7 optimized_linear_gelu_softmax_edit_1 0.01 2.53 2.06
/*
Fused kernel that combines the linear transformation, GELU activation, and softmax normalization in one launch.
This optimized version fuses all steps into a single kernel, reducing global memory traffic and kernel launch overhead,
while using shared memory with tree-based reductions for computing the maximum and sum needed for stable softmax.
*/
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cfloat>
#include <cmath>

// GELU activation function as implemented in PyTorch
__device__ float gelu(float x) {
    const float sqrt_2_over_pi = 0.7978845608028654f;
    const float coef = 0.044715f;
    float cdf = 0.5f * (1.0f + tanhf(sqrt_2_over_pi * x * (1.0f + coef * x * x)));
    return x * cdf;
}

// Fused kernel: each block processes one row of the input
// Shared memory layout: first region for computed values (row_data), second region (scratch) for reductions
__global__ void fused_linear_gelu_softmax_optimized_kernel(
    const float* __restrict__ x,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int batch_size,
    int in_features,
    int out_features
) {
    extern __shared__ float shared_mem[];
    // Define two shared arrays: row_data holds computed values, scratch is used for reductions
    float* row_data = shared_mem;               // size: out_features
    float* scratch  = &shared_mem[out_features];  // size: out_features

    int row = blockIdx.x;      // each block handles one row
    int tid = threadIdx.x;     // each thread computes one output element
    int n = out_features;      // number of output features per row

    // 1. Compute linear transformation and apply GELU activation
    if (row < batch_size && tid < n) {
        float sum = 0.0f;
        for (int k = 0; k < in_features; k++) {
            sum += x[row * in_features + k] * weight[tid * in_features + k];
        }
        sum += bias[tid];
        row_data[tid] = gelu(sum);
    }
    __syncthreads();

    // 2. Compute maximum value in row_data for softmax numerical stability using tree reduction
    if (tid < n) {
        scratch[tid] = row_data[tid];
    }
    __syncthreads();

    // Use a tree-based reduction to compute the maximum. First, determine the next power of two factor.
    int s = 1;
    while (s < n) { s *= 2; }
    s /= 2;
    for (; s > 0; s /= 2) {
        if (tid < s && (tid + s) < n) {
            scratch[tid] = max(scratch[tid], scratch[tid + s]);
        }
        __syncthreads();
    }
    // Broadcast the computed maximum to all threads in the block
    float max_val = scratch[0];
    __syncthreads();

    // 3. Exponentiate each element after subtracting max_val
    if (tid < n) {
        float exp_val = expf(row_data[tid] - max_val);
        row_data[tid] = exp_val; // store back the exponentiated value
    }
    __syncthreads();

    // 4. Compute the sum of the exponentials for normalization
    if (tid < n) {
        scratch[tid] = row_data[tid];
    }
    __syncthreads();

    s = 1;
    while (s < n) { s *= 2; }
    s /= 2;
    for (; s > 0; s /= 2) {
        if (tid < s && (tid + s) < n) {
            scratch[tid] += scratch[tid + s];
        }
        __syncthreads();
    }
    float sum_exp = scratch[0];
    __syncthreads();

    // 5. Normalize each exponentiated value to obtain the softmax output
    if (tid < n) {
        output[row * n + tid] = row_data[tid] / sum_exp;
    }
}

// The forward function invoked from PyTorch
torch::Tensor forward(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias
) {
    const int batch_size = x.size(0);
    const int in_features = x.size(1);
    const int out_features = weight.size(0);

    auto options = torch::TensorOptions().dtype(x.dtype()).device(x.device());
    auto output = torch::empty({batch_size, out_features}, options);

    // Launch configuration: one block per row and 'out_features' threads per block.
    // Shared memory allocates two arrays of size 'out_features' each.
    int threads = out_features;
    int blocks = batch_size;
    int shared_mem_size = 2 * out_features * sizeof(float);

    fused_linear_gelu_softmax_optimized_kernel<<<blocks, threads, shared_mem_size>>>(
        x.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        output.data_ptr<float>(),
        batch_size,
        in_features,
        out_features
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Fused Linear + GELU + Softmax forward (optimized)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.060 inst/cycle 0.000 5
Executed Ipc Elapsed 0.040 inst/cycle 0.000 5
Issue Slots Busy 1.486 % 0.000 5
Issued Ipc Active 0.060 inst/cycle 0.000 5
SM Busy 1.486 % 0.000 5
Memory Throughput 6876958951.028 byte/second 3480571422307799.000 5
Mem Busy 4.080 % 0.001 5
Max Bandwidth 3.038 % 0.000 5
L1/TEX Hit Rate 87.140 % 0.000 5
L2 Hit Rate 99.540 % 0.216 5
Mem Pipes Busy 1.598 % 0.000 5
Warp Cycles Per Issued Instruction 16.850 cycle 0.148 5
Warp Cycles Per Executed Instruction 16.982 cycle 0.150 5
Avg. Active Threads Per Warp 9.850 0.000 5
Avg. Not Predicated Off Threads Per Warp 9.130 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 64.000 block 0.000 5
Block Limit Shared Mem 56.000 block 0.000 5
Block Limit Warps 64.000 block 0.000 5
Theoretical Active Warps per SM 32.000 warp 0.000 5
Theoretical Occupancy 50.000 % 0.000 5
Achieved Occupancy 1.560 % 0.000 5
Achieved Active Warps Per SM 1.000 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 9.9 threads being active per cycle. This is further reduced to 9.1 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 (50.0%) is limited by the number of blocks that can fit on the SM. The difference between calculated theoretical (50.0%) and measured achieved occupancy (1.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 378442.43 μs
Device Time 8.45 μs
Self CPU Time 53.03 μ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 378389.40 μs
Device Time 8.45 μs
Self CPU Time 104.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
aten::empty_strided
CPU Time 378130.59 μs
Device Time 0.00 μs
Self CPU Time 98.62 μ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 377258.62 μs
Device Time 0.00 μs
Self CPU Time 377258.62 μ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 551743.95 μs
Device Time 22278.40 μs
Self CPU Time 551743.95 μs
Self Device Time 22278.40 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
fused_linear_gelu_softmax_optimized_kernel(float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 71070.65 μs
Self CPU Time 0.00 μs
Self Device Time 71070.65 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaEventRecord
CPU Time 18436.25 μs
Device Time 44339.41 μs
Self CPU Time 18436.25 μs
Self Device Time 44339.41 μ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 68310.79 μs
Device Time 660814.46 μs
Self CPU Time 13860.59 μ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 54454.37 μs
Device Time 660814.46 μs
Self CPU Time 18763.57 μs
Self Device Time 660814.46 μ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 660814.46 μs
Self CPU Time 0.00 μs
Self Device Time 660814.46 μ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
45288 warnings generated when compiling for host.
Suppressed 45323 warnings (45276 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_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:24:5 bugprone-easily-swappable-parameters
24 | const float* __restrict__ weight,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
25 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:24:31: note: the first parameter in the range is 'weight'
24 | const float* __restrict__ weight,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:25:31: note: the last parameter in the range is 'bias'
25 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:27:5: warning: 3 adjacent parameters of 'fused_linear_gelu_softmax_optimized_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
27 | int batch_size,
| ^~~~~~~~~~~~~~~
28 | int in_features,
| ~~~~~~~~~~~~~~~~
29 | int out_features
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:27:9: note: the first parameter in the range is 'batch_size'
27 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:29:9: note: the last parameter in the range is 'out_features'
29 | int out_features
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:36:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
36 | int row = blockIdx.x; // each block handles one row
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:37:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
37 | int tid = threadIdx.x; // each thread computes one output element
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:104:19: 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]
104 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:105:19: 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]
105 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:106:19: 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]
106 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:108:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
108 | const int batch_size = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:109:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
109 | const int in_features = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:110:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
110 | const int out_features = weight.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:119:27: warning: performing an implicit widening conversion to type 'unsigned long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
119 | int shared_mem_size = 2 * out_features * sizeof(float);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:119:27: note: make conversion explicit to silence this warning
11 | int shared_mem_size = 2 * out_features * sizeof(float);
| ^~~~~~~~~~~~~~~~
| static_cast<unsigned long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:119:27: note: perform multiplication in a wider type
119 | int shared_mem_size = 2 * out_features * sizeof(float);
| ^
| static_cast<long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_99/b4_s3_fused_linear_gelu_softmax_optimized/base/base.cu:119:27: warning: narrowing conversion from 'unsigned long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
119 | int shared_mem_size = 2 * out_features * sizeof(float);
| ^