← Back to Leaderboard

The AI CUDA Engineer 👷

9_Matmul_Subtract_Multiply_ReLUtiled_grid_stride_base

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


def module_fn(
    x: torch.Tensor,
    linear_weight: torch.Tensor,
    linear_bias: torch.Tensor,
    subtract_value: float,
    multiply_value: float,
) -> torch.Tensor:
    """
    Applies linear transformation, subtraction, multiplication and ReLU activation.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_features)
        linear_weight (torch.Tensor): Weight matrix of shape (out_features, in_features)
        linear_bias (torch.Tensor): Bias vector of shape (out_features)
        subtract_value (float): Value to subtract
        multiply_value (float): Value to multiply

    Returns:
        torch.Tensor: Output tensor after applying linear transformation, subtraction,
            multiplication and ReLU, with shape (batch_size, out_features)
    """
    x = F.linear(x, linear_weight, linear_bias)
    x = x - subtract_value
    x = x * multiply_value
    x = torch.relu(x)
    return x


class Model(nn.Module):
    """
    Model that performs a matrix multiplication, subtraction, multiplication, and ReLU activation.
    """

    def __init__(self, in_features, out_features, subtract_value, multiply_value):
        super(Model, self).__init__()
        self.linear_weight = nn.Parameter(torch.randn(out_features, in_features) * 0.02)
        self.linear_bias = nn.Parameter(torch.randn(out_features) * 0.02)
        self.subtract_value = subtract_value
        self.multiply_value = multiply_value

    def forward(self, x, fn=module_fn):
        return fn(
            x,
            self.linear_weight,
            self.linear_bias,
            self.subtract_value,
            self.multiply_value,
        )


batch_size = 128
in_features = 10
out_features = 5
subtract_value = 2.0
multiply_value = 1.5


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


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

class Model(nn.Module):
    """
    Model that performs a matrix multiplication, subtraction, multiplication, and ReLU activation.
    """
    def __init__(self, in_features, out_features, subtract_value, multiply_value):
        super(Model, self).__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.subtract_value = subtract_value
        self.multiply_value = multiply_value

    def forward(self, x):
        x = self.linear(x)
        x = x - self.subtract_value
        x = x * self.multiply_value
        x = torch.relu(x)
        return x

batch_size = 128
in_features = 10
out_features = 5
subtract_value = 2.0
multiply_value = 1.5

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

def get_init_inputs():
    return [in_features, out_features, subtract_value, multiply_value]

Kernel Information

Related Kernels (Level 2, Task 9 • 9_Matmul_Subtract_Multiply_ReLU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 unrolled_loop_kernel_base 0.01 4.05 2.63
🥇 9_Matmul_Subtract_Multiply_ReLU 0.01 4.05 2.63
🥇 9_matmul_subtract_multiply_relu_unroll_base 0.01 4.05 2.63
🥇 9_matmul_subtract_multiply_relu_unroll_base 0.01 4.05 2.63
🥇 modular_matmul_subtract_multiply_relu_base 0.01 4.05 2.63
🥇 efficient_indexing_tile_kernel_base 0.01 4.05 2.63
🥇 efficient_thread_block_mapping_base 0.01 4.05 2.63
🥇 warp_divergence_optimized_base 0.01 4.05 2.63
🥇 warp_level_fused_kernel_base 0.01 4.05 2.63
🥇 shared_mem_tiled_base 0.01 4.05 2.63
🥇 tiled_sharedmem_optimized_base 0.01 4.05 2.63
🥇 warp_level_reduction_kernel_base 0.01 4.05 2.63
🥇 strided_thread_blocks_base_base 0.01 4.05 2.63
🥇 optimized_block_size_base 0.01 4.05 2.63
🥇 double_buffered_tiled_kernel_base 0.01 4.05 2.63
🥇 coalesced_memory_matmul_base_base 0.01 4.05 2.63
🥇 tiled_matmul_shared_mem_base 0.01 4.05 2.63
🥇 optimized_tiled_2d_base 0.01 4.05 2.63
🥇 matmul_1d_thread_mapping_base 0.01 4.05 2.63
🥇 modularized_matmul_ops_base 0.01 4.05 2.63
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

// Inline ReLU function template
template <typename scalar_t>
__device__ inline scalar_t relu_func(scalar_t x) {
  return x > 0 ? x : 0;
}

template <>
__device__ inline double relu_func(double x) {
  return x > 0 ? x : 0;
}


// This kernel combines a tiled shared memory approach with grid-stride loops
// to cover large matrices while ensuring memory coalescing for both input and weight.
// The kernel fuses a GEMM with bias addition, a subtract, a multiplication, and a ReLU activation.

template <typename scalar_t>
__global__ void tiled_grid_stride_matmul_relu_kernel(
    const scalar_t* __restrict__ input,    // [batch_size x in_features]
    const scalar_t* __restrict__ weight,   // [out_features x in_features]
    const scalar_t* __restrict__ bias,     // [out_features]
    scalar_t* __restrict__ output,         // [batch_size x out_features]
    const int batch_size,
    const int in_features,
    const int out_features,
    const float subtract_val,
    const float multiply_val) {

  // Tile dimension (adjustable) 
  constexpr int TILE_DIM = 16;

  // Allocate shared memory for input and weight tiles
  __shared__ scalar_t shInput[TILE_DIM][TILE_DIM];
  __shared__ scalar_t shWeight[TILE_DIM][TILE_DIM];

  // Use grid-stride loops to cover the full output matrix
  for (int row_tile = blockIdx.y * TILE_DIM;
       row_tile < batch_size;
       row_tile += gridDim.y * TILE_DIM) {
    for (int col_tile = blockIdx.x * TILE_DIM;
         col_tile < out_features;
         col_tile += gridDim.x * TILE_DIM) {

      // Compute the output coordinate this thread is responsible for
      int row = row_tile + threadIdx.y;
      int col = col_tile + threadIdx.x;
      scalar_t acc = 0;

      // Number of tiles along the in_features (K) dimension
      int numTiles = (in_features + TILE_DIM - 1) / TILE_DIM;

      // Loop over tiles in the K dimension
      for (int t = 0; t < numTiles; t++) {
        int k_index = t * TILE_DIM + threadIdx.x;
        // Load input tile element (each thread loads one element)
        if (row < batch_size && k_index < in_features) {
          shInput[threadIdx.y][threadIdx.x] = input[row * in_features + k_index];
        } else {
          shInput[threadIdx.y][threadIdx.x] = 0;
        }

        int k_index_weight = t * TILE_DIM + threadIdx.y;
        // Load weight tile element using __ldg for read-only cache efficiency
        if (col < out_features && k_index_weight < in_features) {
          shWeight[threadIdx.y][threadIdx.x] = __ldg(&weight[col * in_features + k_index_weight]);
        } else {
          shWeight[threadIdx.y][threadIdx.x] = 0;
        }

        __syncthreads();

        // Compute partial dot-product for the current tile
        #pragma unroll
        for (int k = 0; k < TILE_DIM; k++) {
          acc += shInput[threadIdx.y][k] * shWeight[k][threadIdx.x];
        }

        __syncthreads();
      } // End of K-dimension tiling loop

      // After accumulation, if within bounds, apply bias, subtract, multiply, and ReLU
      if (row < batch_size && col < out_features) {
        scalar_t value = acc + bias[col];
        value = (value - subtract_val) * multiply_val;
        // Using the inline ReLU
        output[row * out_features + col] = relu_func(value);
      }
    } // end for col_tile
  } // end for row_tile
}

// Host-side forward function exposed to PyTorch

torch::Tensor forward(
    torch::Tensor input,
    torch::Tensor weight,
    torch::Tensor bias,
    float subtract_val,
    float multiply_val) {

  auto batch_size = input.size(0);
  auto in_features = input.size(1);
  auto out_features = weight.size(0);

  auto output = torch::empty({batch_size, out_features}, input.options());

  constexpr int TILE_DIM = 16;

  // Define 2D block and grid dimensions. Grid-stride loops ensure full coverage even if grid size is smaller than problem dimensions.
  dim3 threads(TILE_DIM, TILE_DIM);
  dim3 blocks((out_features + TILE_DIM - 1) / TILE_DIM, (batch_size + TILE_DIM - 1) / TILE_DIM);

  AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "tiled_grid_stride_matmul_relu_kernel", ([&] {
    tiled_grid_stride_matmul_relu_kernel<scalar_t><<<blocks, threads>>>(
        input.data_ptr<scalar_t>(),
        weight.data_ptr<scalar_t>(),
        bias.data_ptr<scalar_t>(),
        output.data_ptr<scalar_t>(),
        batch_size,
        in_features,
        out_features,
        subtract_val,
        multiply_val);
  }));

  return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("forward", &forward, "Tiled and grid-stride fused matmul with bias, subtract, multiply and ReLU (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.396 inst/cycle 0.000 5
Executed Ipc Elapsed 0.010 inst/cycle 0.000 5
Issue Slots Busy 10.428 % 0.165 5
Issued Ipc Active 0.416 inst/cycle 0.000 5
SM Busy 10.428 % 0.165 5
Memory Throughput 2658111442.924 byte/second 4077281705173301.500 5
Mem Busy 8.432 % 0.005 5
Max Bandwidth 4.322 % 0.001 5
L1/TEX Hit Rate 49.924 % 1.474 5
L2 Hit Rate 101.544 % 0.407 5
Mem Pipes Busy 0.272 % 0.000 5
Warp Cycles Per Issued Instruction 18.838 cycle 0.111 5
Warp Cycles Per Executed Instruction 19.980 cycle 0.124 5
Avg. Active Threads Per Warp 29.730 0.000 5
Avg. Not Predicated Off Threads Per Warp 28.020 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 21.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.416 % 0.000 5
Achieved Active Warps Per SM 7.948 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 (12.4%) 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 491766.11 μs
Device Time 5.50 μs
Self CPU Time 64.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::_to_copy
CPU Time 491701.52 μs
Device Time 5.50 μs
Self CPU Time 135.07 μ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 491403.46 μs
Device Time 0.00 μs
Self CPU Time 112.13 μ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 485862.15 μs
Device Time 0.00 μs
Self CPU Time 485862.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
cudaLaunchKernel
CPU Time 429663.13 μs
Device Time 18816.61 μs
Self CPU Time 429663.13 μs
Self Device Time 18816.61 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void tiled_grid_stride_matmul_relu_kernel<float>(float const*, float const*, float const*, float*, int, int, int, float, float)
CPU Time 0.00 μs
Device Time 25139.74 μs
Self CPU Time 0.00 μs
Self Device Time 25139.74 μ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 19446.77 μs
Device Time 37384.96 μs
Self CPU Time 19446.77 μs
Self Device Time 37384.96 μ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 59746.09 μs
Device Time 559775.67 μs
Self CPU Time 12999.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 46748.19 μs
Device Time 559775.67 μs
Self CPU Time 14077.47 μs
Self Device Time 559775.67 μ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 559775.67 μs
Self CPU Time 0.00 μs
Self Device Time 559775.67 μ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
45291 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/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:23:5 bugprone-easily-swappable-parameters
23 | const scalar_t* __restrict__ input, // [batch_size x in_features]
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 | const scalar_t* __restrict__ weight, // [out_features x in_features]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
25 | const scalar_t* __restrict__ bias, // [out_features]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:23:34: note: the first parameter in the range is 'input'
23 | const scalar_t* __restrict__ input, // [batch_size x in_features]
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:25:34: note: the last parameter in the range is 'bias'
25 | const scalar_t* __restrict__ bias, // [out_features]
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:29:5: warning: 2 adjacent parameters of 'tiled_grid_stride_matmul_relu_kernel' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
29 | const int out_features,
| ^~~~~~~~~~~~~~~~~~~~~~~
30 | const float subtract_val,
| ~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:29:15: note: the first parameter in the range is 'out_features'
29 | const int out_features,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:30:17: note: the last parameter in the range is 'subtract_val'
30 | const float subtract_val,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:30: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')
30 | const float subtract_val,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:41:23: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
41 | for (int row_tile = blockIdx.y * TILE_DIM;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:43:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
43 | row_tile += gridDim.y * TILE_DIM) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:44:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
44 | for (int col_tile = blockIdx.x * TILE_DIM;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:46:22: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
46 | col_tile += gridDim.x * TILE_DIM) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:49:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
49 | int row = row_tile + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:50:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
50 | int col = col_tile + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:58:23: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
58 | int k_index = t * TILE_DIM + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:66:30: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
66 | int k_index_weight = t * TILE_DIM + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_random/level_2/task_9/b8_s1_tiled_grid_stride/base/base.cu:117:3: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
117 | AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "tiled_grid_stride_matmul_relu_kernel", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:237:34: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES'
237 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:233:3: note: expanded from macro 'AT_DISPATCH_CASE_FLOATING_TYPES'
233 | AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:74:3: note: expanded from macro 'AT_DISPATCH_CASE'
74 | AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__)
| ^
note: (skipping 1 expansions in backtrace; use -fmacro-backtrace-limit=0 to see all)
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:58:7: note: expanded from macro 'AT_PRIVATE_CHECK_SELECTIVE_BUILD'
58 | AT_ERROR( \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:711:32: note: expanded from macro 'AT_ERROR'
711 | C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:536:9: note: expanded from macro 'TORCH_CHECK'
536 | __func__, \
| ^