← Back to Leaderboard

The AI CUDA Engineer 👷

12_Gemm_Multiply_LeakyReLUgemm_tiled_grid_block_32_base

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


def module_fn(
    x: torch.Tensor,
    multiplier: float,
    negative_slope: float,
    weight: torch.Tensor,
    bias: torch.Tensor,
) -> torch.Tensor:
    """
    Applies linear transformation, multiplies by scalar, and applies LeakyReLU.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_features)
        multiplier (float): Scalar multiplier
        negative_slope (float): Negative slope for LeakyReLU
        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 = x * multiplier
    x = F.leaky_relu(x, negative_slope=negative_slope)
    return x


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__()
        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, multiplier, negative_slope, self.weight, self.bias)


batch_size = 128
in_features = 1024
out_features = 512
multiplier = 2.0
negative_slope = 0.1


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


def get_init_inputs():
    return [in_features, out_features, multiplier, negative_slope]
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 = 128
in_features = 1024
out_features = 512
multiplier = 2.0
negative_slope = 0.1

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

def get_init_inputs():
    return [in_features, out_features, multiplier, negative_slope]

Kernel Information

Related Kernels (Level 2, Task 12 • 12_Gemm_Multiply_LeakyReLU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 12_gemm_warp_primitives_base 0.03 1.30 2.32
🥈 12_gemm_ldg_optimization_base 0.04 1.18 2.12
🥈 12_gemm_warp_vec4_edit_1_base_edit_1 0.04 1.18 2.12
🥈 12_gemm_ldg_optimization_edit_1 0.04 1.18 2.12
5 12_gemm_warp_vec4_edit_1_base_base 0.04 1.04 1.86
6 gemm_tiled_grid_edit_1 0.05 0.83 1.49
7 12_gemm_constant_memory_edit_1 0.05 0.80 1.43
8 gemm_unrolled_base 0.05 0.77 1.38
8 gemm_unrolled_edit_1 0.05 0.77 1.38
8 12_gemm_constant_memory_base 0.05 0.77 1.38
11 gemm_tiled_grid_block_32_base 0.07 0.60 1.08
12 gemm_tiled_grid_base 0.07 0.59 1.06
12 gemm_tiled_shared_base 0.07 0.59 1.06
12 gemm_tiled_grid_block_32_edit_1 0.07 0.59 1.06
15 12_gemm_tiled_coalesced_edit_1 0.07 0.58 1.05
16 gemm_tiled_streamed_base 0.07 0.56 1.00
17 optimized_gemm_leakyrelu_base 0.07 0.55 0.99
17 atomic_optimization_gemm_edit_1 0.07 0.55 0.99
17 optimized_gemm_leakyrelu_edit_1 0.07 0.55 0.99
20 optimized_thread_block_indexing_gemm_base 0.08 0.51 0.91
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

#define BLOCK_SIZE 32

// Combined kernel using shared memory tiling and grid-stride loops
__global__ void gemm_tiled_grid_kernel(
    const float* __restrict__ x,       // Input: [batch_size x in_features]
    const float* __restrict__ weight,  // Weight: [out_features x in_features]
    const float* __restrict__ bias,    // Bias: [out_features]
    float* __restrict__ output,        // Output: [batch_size x out_features]
    const int batch_size,
    const int in_features,
    const int out_features,
    const float multiplier,
    const float negative_slope
) {
    // Each block computes a BLOCK_SIZE x BLOCK_SIZE tile of the output.
    // We'll use grid-stride loops to cover the full output if the grid is smaller than the problem size.
    const int tx = threadIdx.x;
    const int ty = threadIdx.y;

    // Loop over output tiles in the row (batch) and column (out_features) dimensions
    for (int row_base = blockIdx.x * BLOCK_SIZE; row_base < batch_size; row_base += gridDim.x * BLOCK_SIZE) {
        for (int col_base = blockIdx.y * BLOCK_SIZE; col_base < out_features; col_base += gridDim.y * BLOCK_SIZE) {
            float sum = 0.0f;
            int row = row_base + tx;
            int col = col_base + ty;

            // Compute the number of tiles over in_features dimension
            int numTiles = (in_features + BLOCK_SIZE - 1) / BLOCK_SIZE;

            // Declare shared memory tiles for x and weight - padded for bank conflicts
            __shared__ float s_x[BLOCK_SIZE][BLOCK_SIZE + 1];  // +1 padding to avoid bank conflicts
            __shared__ float s_w[BLOCK_SIZE][BLOCK_SIZE + 1];  // +1 padding to avoid bank conflicts

            // Loop over tiles in the in_features dimension
            #pragma unroll 4
            for (int t = 0; t < numTiles; t++) {
                int tile_idx = t * BLOCK_SIZE;

                // Load a tile from the input matrix x using __ldg for cache hint
                if (row < batch_size && (tile_idx + ty) < in_features) {
                    s_x[tx][ty] = __ldg(&x[row * in_features + tile_idx + ty]);
                } else {
                    s_x[tx][ty] = 0.0f;
                }

                // Load a tile from the weight matrix with a transpose for better memory access
                if (col < out_features && (tile_idx + tx) < in_features) {
                    // Transpose the tile while loading: store in s_w[ty][tx]
                    s_w[ty][tx] = __ldg(&weight[col * in_features + tile_idx + tx]);
                } else {
                    s_w[ty][tx] = 0.0f;
                }

                __syncthreads();

                // Compute partial dot product for the tile
                #pragma unroll
                for (int k = 0; k < BLOCK_SIZE; k++) {
                    sum += s_x[tx][k] * s_w[ty][k];
                }

                __syncthreads();
            } // End of tiling loop

            // Write back the result with bias addition, multiplier scaling, and LeakyReLU activation
            if (row < batch_size && col < out_features) {
                float result = (sum + bias[col]) * multiplier;
                result = (result > 0.0f) ? result : result * negative_slope;
                output[row * out_features + col] = result;
            }
        } // End of col_base loop
    } // End of row_base loop
}

// Host function that sets up kernel execution
torch::Tensor module_fn_forward(
    torch::Tensor x,
    float multiplier,
    float negative_slope,
    torch::Tensor weight,
    torch::Tensor bias
) {
    TORCH_CHECK(x.device().is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(weight.device().is_cuda(), "weight must be a CUDA tensor");
    TORCH_CHECK(bias.device().is_cuda(), "bias must be a CUDA tensor");

    const int batch_size = x.size(0);
    const int in_features = x.size(1);
    const int out_features = weight.size(0);

    TORCH_CHECK(weight.size(1) == in_features, "Weight in_features must match x in_features");
    TORCH_CHECK(bias.size(0) == out_features, "Bias size must match weight out_features");

    auto output = torch::zeros({batch_size, out_features}, x.options());

    // Choose block dimensions and grid dimensions; grid-stride loops help cover full matrix.
    dim3 block(BLOCK_SIZE, BLOCK_SIZE);
    dim3 grid(
        (batch_size + BLOCK_SIZE - 1) / BLOCK_SIZE,
        (out_features + BLOCK_SIZE - 1) / BLOCK_SIZE
    );

    gemm_tiled_grid_kernel<<<grid, block>>>(
        x.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        output.data_ptr<float>(),
        batch_size,
        in_features,
        out_features,
        multiplier,
        negative_slope
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &module_fn_forward, "Combined GEMM forward CUDA kernel with shared memory tiling and grid-stride loops");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.030 inst/cycle 0.000 5
Executed Ipc Elapsed 0.480 inst/cycle 0.000 5
Issue Slots Busy 25.710 % 0.001 5
Issued Ipc Active 1.030 inst/cycle 0.000 5
SM Busy 31.206 % 0.001 5
Memory Throughput 34079210973.944 byte/second 4676624091894300.000 5
Mem Busy 40.512 % 0.007 5
Max Bandwidth 29.726 % 0.004 5
L1/TEX Hit Rate 76.210 % 0.000 5
L2 Hit Rate 76.992 % 0.800 5
Mem Pipes Busy 27.524 % 0.003 5
Warp Cycles Per Issued Instruction 30.858 cycle 0.000 5
Warp Cycles Per Executed Instruction 30.886 cycle 0.000 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 31.930 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 2.000 block 0.000 5
Block Limit Shared Mem 3.000 block 0.000 5
Block Limit Warps 2.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 49.552 % 0.000 5
Achieved Active Warps Per SM 31.712 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 Occupancy This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (49.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 294224.63 μs
Device Time 153.44 μs
Self CPU Time 78.24 μ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::zeros
CPU Time 4203865.09 μs
Device Time 88464.61 μs
Self CPU Time 121539.23 μ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::zero_
CPU Time 6993373.78 μs
Device Time 4927082.62 μs
Self CPU Time 247113.86 μ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 6746265.34 μs
Device Time 4927082.62 μs
Self CPU Time 313327.07 μs
Self Device Time 4927081.21 μ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 6745133.76 μs
Device Time 214728.29 μs
Self CPU Time 6745133.76 μs
Self Device Time 214728.29 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
gemm_tiled_grid_kernel(float const*, float const*, float const*, float*, int, int, int, float, float)
CPU Time 0.00 μs
Device Time 3927749.37 μs
Self CPU Time 0.00 μs
Self Device Time 3927749.37 μ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 4839007.00 μs
Self CPU Time 0.00 μs
Self Device Time 4839007.00 μ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
45292 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/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:9:5 bugprone-easily-swappable-parameters
9 | const float* __restrict__ x, // Input: [batch_size x in_features]
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 | const float* __restrict__ weight, // Weight: [out_features x in_features]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11 | const float* __restrict__ bias, // Bias: [out_features]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:9:31: note: the first parameter in the range is 'x'
9 | const float* __restrict__ x, // Input: [batch_size x in_features]
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:11:31: note: the last parameter in the range is 'bias'
11 | const float* __restrict__ bias, // Bias: [out_features]
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:15:5: warning: 3 adjacent parameters of 'gemm_tiled_grid_kernel' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
15 | const int out_features,
| ^~~~~~~~~~~~~~~~~~~~~~~
16 | const float multiplier,
| ~~~~~~~~~~~~~~~~~~~~~~~
17 | const float negative_slope
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:15:15: note: the first parameter in the range is 'out_features'
15 | const int out_features,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:17:17: note: the last parameter in the range is 'negative_slope'
17 | const float negative_slope
| ^~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:16:5: note: 'const int' and 'const float' may be implicitly converted: 'const int' (as 'int') -> 'const float' (as 'float'), 'const float' (as 'float') -> 'const int' (as 'int')
16 | const float multiplier,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:21:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
21 | const int tx = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:22:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | const int ty = threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:25:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
25 | for (int row_base = blockIdx.x * BLOCK_SIZE; row_base < batch_size; row_base += gridDim.x * BLOCK_SIZE) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:25:85: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
25 | for (int row_base = blockIdx.x * BLOCK_SIZE; row_base < batch_size; row_base += gridDim.x * BLOCK_SIZE) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:26:29: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
26 | for (int col_base = blockIdx.y * BLOCK_SIZE; col_base < out_features; col_base += gridDim.y * BLOCK_SIZE) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:26:91: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
26 | for (int col_base = blockIdx.y * BLOCK_SIZE; col_base < out_features; col_base += gridDim.y * BLOCK_SIZE) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:81: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]
81 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:84: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]
84 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:85: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]
85 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:91:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
91 | const int batch_size = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:92:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
92 | const int in_features = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_12/b5_s1_gemm_tiled_grid_block_32/base/base.cu:93:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
93 | const int out_features = weight.size(0);
| ^