← Back to Leaderboard

The AI CUDA Engineer 👷

68_Matmul_Min_Subtractstride_loop_optimization_base_base

Level 2 • Task 68
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,
    constant: torch.Tensor,
) -> torch.Tensor:
    """
    Performs matrix multiplication, applies minimum with constant, and subtracts constant.

    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)
        constant (torch.Tensor): Scalar constant tensor

    Returns:
        torch.Tensor: Output tensor of shape (batch_size, out_features)
    """
    x = F.linear(x, linear_weight, linear_bias)
    x = torch.min(x, constant)
    x = x - constant
    return x


class Model(nn.Module):
    """
    Simple model that performs a matrix multiplication, applies minimum, and subtracts a constant.
    """

    def __init__(self, in_features, out_features, constant):
        super(Model, self).__init__()
        gemm = nn.Linear(in_features, out_features)
        self.linear_weight = nn.Parameter(gemm.weight)
        self.linear_bias = nn.Parameter(gemm.bias)
        self.constant = nn.Parameter(torch.tensor(constant))

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


batch_size = 128
in_features = 10
out_features = 5
constant = 2.0


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


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

class Model(nn.Module):
    """
    Simple model that performs a matrix multiplication, applies minimum, and subtracts a constant.
    """
    def __init__(self, in_features, out_features, constant):
        super(Model, self).__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.constant = nn.Parameter(torch.tensor(constant))

    def forward(self, x):
        x = self.linear(x)
        x = torch.min(x, self.constant)
        x = x - self.constant
        return x

batch_size = 128
in_features = 10
out_features = 5
constant = 2.0

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

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

Kernel Information

Related Kernels (Level 2, Task 68 • 68_Matmul_Min_Subtract)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 optimized_shared_memory_sync_base 0.01 2.95 1.92
🥇 optimized_thread_block_indexing_base_base 0.01 2.95 1.92
🥇 modularized_device_functions_base_base 0.01 2.95 1.92
🥇 aligned_memory_access_ldg_base_base 0.01 2.95 1.92
🥇 stride_loop_optimization_thread_base_base 0.01 2.95 1.92
🥇 tiled_shared_memory_matmul_base_base 0.01 2.95 1.92
🥇 unrolled_loop_optimization_base 0.01 2.95 1.92
🥇 optimized_warp_coalesced_base 0.01 2.95 1.92
🥇 grid_2d_mapping_base 0.01 2.95 1.92
🥇 aligned_memory_access_base_edit_1 0.01 2.95 1.92
🥇 modular_device_functions_edit_1 0.01 2.95 1.92
🥇 aligned_memory_access_base_base 0.01 2.95 1.92
🥇 grid_2d_mapping_edit_1 0.01 2.95 1.92
🥇 efficient_thread_block_mapping_base 0.01 2.95 1.92
🥇 stride_loop_optimization_base_base 0.01 2.95 1.92
🥇 tiled_gemm_thread_mapping_base 0.01 2.95 1.92
17 modular_device_functions_base 0.01 2.62 1.71
17 aligned_ldg_vectorized_edit_1 0.01 2.62 1.71
17 aligned_ldg_vectorized_base 0.01 2.62 1.71
17 branchless_min_dot_edit_1 0.01 2.62 1.71
#include <torch/extension.h>

#include <cuda.h>
#include <cuda_runtime.h>

#define BLOCK_SIZE 16

__device__ float compute_dot_product(const float* x_row, const float* weight_row, int in_features) {
    float sum = 0.0f;
    for (int j = 0; j < in_features; j += BLOCK_SIZE) {
        #pragma unroll
        for (int k = 0; k < BLOCK_SIZE && j + k < in_features; ++k) {
            sum += x_row[j + k] * weight_row[j + k];
        }
    }
    return sum;
}

__device__ float apply_min_subtract(float computed, float bias, float constant) {
    float result = computed + bias;  // Add bias
    if (result > constant) {  // Min with constant
        result = constant;
    }
    result -= constant;  // Subtract constant
    return result;
}

__global__ void my_kernel(
    const float* x,
    const float* linear_weight,
    const float* linear_bias,
    const float* constant,
    float* y,
    int batch_size,
    int in_features,
    int out_features) {
    int batch_idx = blockIdx.x * blockDim.x + threadIdx.x;
    int out_idx = blockIdx.y * blockDim.y + threadIdx.y;

    if (batch_idx < batch_size && out_idx < out_features) {
        // Pointers to rows
        const float* x_row = x + batch_idx * in_features;
        const float* weight_row = linear_weight + out_idx * in_features;
        float bias = linear_bias[out_idx];
        float cst = *constant;

        // Compute dot product using device function
        float result = compute_dot_product(x_row, weight_row, in_features);

        // Apply min and subtract using another device function
        y[batch_idx * out_features + out_idx] = apply_min_subtract(result, bias, cst);
    }
}

torch::Tensor forward(
    torch::Tensor x,
    torch::Tensor linear_weight,
    torch::Tensor linear_bias,
    torch::Tensor constant) {
    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(linear_weight.is_cuda(), "linear_weight must be a CUDA tensor");
    TORCH_CHECK(linear_bias.is_cuda(), "linear_bias must be a CUDA tensor");
    TORCH_CHECK(constant.is_cuda(), "constant must be a CUDA tensor");

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

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

    const float* x_ptr = x.data_ptr<float>();
    const float* weight_ptr = linear_weight.data_ptr<float>();
    const float* bias_ptr = linear_bias.data_ptr<float>();
    const float* constant_ptr = constant.data_ptr<float>();
    float* y_ptr = y.data_ptr<float>();

    dim3 threads(BLOCK_SIZE, BLOCK_SIZE);
    dim3 blocks((batch_size + BLOCK_SIZE - 1) / BLOCK_SIZE, (out_features + BLOCK_SIZE - 1) / BLOCK_SIZE);

    my_kernel<<<blocks, threads>>>(
        x_ptr,
        weight_ptr,
        bias_ptr,
        constant_ptr,
        y_ptr,
        batch_size,
        in_features,
        out_features);

    return y;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "CUDA forward function");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.140 inst/cycle 0.000 5
Executed Ipc Elapsed 0.000 inst/cycle 0.000 5
Issue Slots Busy 4.086 % 0.052 5
Issued Ipc Active 0.164 inst/cycle 0.000 5
SM Busy 4.086 % 0.052 5
Memory Throughput 2563629088.182 byte/second 4382884586856406.500 5
Mem Busy 8.090 % 0.044 5
Max Bandwidth 4.192 % 0.012 5
L1/TEX Hit Rate 92.650 % 0.003 5
L2 Hit Rate 101.668 % 0.001 5
Mem Pipes Busy 0.122 % 0.000 5
Warp Cycles Per Issued Instruction 26.622 cycle 4.407 5
Warp Cycles Per Executed Instruction 30.986 cycle 5.977 5
Avg. Active Threads Per Warp 28.070 0.000 5
Avg. Not Predicated Off Threads Per Warp 25.630 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 10.000 block 0.000 5
Block Limit Shared Mem 32.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 6.968 % 0.092 5
Achieved Active Warps Per SM 4.460 warp 0.037 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 (6.7%) 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::zeros
CPU Time 5941254.90 μs
Device Time 218595.28 μs
Self CPU Time 144402.79 μ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 6251182.67 μs
Device Time 7855256.06 μs
Self CPU Time 327713.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::fill_
CPU Time 5923471.42 μs
Device Time 7855256.06 μs
Self CPU Time 385983.83 μs
Self Device Time 7855256.06 μ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 5878262.73 μs
Device Time 2935.37 μs
Self CPU Time 5878262.73 μs
Self Device Time 2935.37 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
my_kernel(float const*, float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 351602.35 μs
Self CPU Time 0.00 μs
Self Device Time 351602.35 μ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 211884.39 μs
Device Time 1266451.47 μs
Self CPU Time 211884.39 μs
Self Device Time 1266451.47 μ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 7637604.88 μs
Self CPU Time 0.00 μs
Self Device Time 7637604.88 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaEventElapsedTime
CPU Time 308324.31 μs
Device Time 0.00 μs
Self CPU Time 308324.31 μ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
Status: Completed
45291 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_68/b6_s1_stride_loop_optimization_base/base/base.cu:19:53 bugprone-easily-swappable-parameters
19 | __device__ float apply_min_subtract(float computed, float bias, float constant) {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:19:59: note: the first parameter in the range is 'bias'
19 | __device__ float apply_min_subtract(float computed, float bias, float constant) {
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:19:71: note: the last parameter in the range is 'constant'
19 | __device__ float apply_min_subtract(float computed, float bias, float constant) {
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:29:5: warning: 4 adjacent parameters of 'my_kernel' of similar type ('const float *') are easily swapped by mistake [bugprone-easily-swappable-parameters]
29 | const float* x,
| ^~~~~~~~~~~~~~~
30 | const float* linear_weight,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
31 | const float* linear_bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~
32 | const float* constant,
| ~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:29:18: note: the first parameter in the range is 'x'
29 | const float* x,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:32:18: note: the last parameter in the range is 'constant'
32 | const float* constant,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:34:5: warning: 2 adjacent parameters of 'my_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
34 | int batch_size,
| ^~~~~~~~~~~~~~~
35 | int in_features,
| ~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:34:9: note: the first parameter in the range is 'batch_size'
34 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:35:9: note: the last parameter in the range is 'in_features'
35 | int in_features,
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:37:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
37 | int batch_idx = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:38:19: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
38 | int out_idx = blockIdx.y * blockDim.y + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:42:30: warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ptrdiff_t' [bugprone-implicit-widening-of-multiplication-result]
42 | const float* x_row = x + batch_idx * in_features;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:42:34: note: make conversion explicit to silence this warning
5 | const float* x_row = x + batch_idx * in_features;
| ^~~~~~~~~~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>()
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:42:34: note: perform multiplication in a wider type
42 | const float* x_row = x + batch_idx * in_features;
| ^~~~~~~~~
| static_cast<ptrdiff_t>()
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:43:35: warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ptrdiff_t' [bugprone-implicit-widening-of-multiplication-result]
43 | const float* weight_row = linear_weight + out_idx * in_features;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:43:51: note: make conversion explicit to silence this warning
43 | const float* weight_row = linear_weight + out_idx * in_features;
| ^~~~~~~~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:43:51: note: perform multiplication in a wider type
43 | const float* weight_row = linear_weight + out_idx * in_features;
| ^~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:56: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]
56 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:57:19: warning: the parameter 'linear_weight' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
57 | torch::Tensor linear_weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:58:19: warning: the parameter 'linear_bias' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
58 | torch::Tensor linear_bias,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:59:19: warning: the parameter 'constant' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
59 | torch::Tensor constant) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:65:22: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
65 | int batch_size = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:66:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
66 | int in_features = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_68/b6_s1_stride_loop_optimization_base/base/base.cu:67:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
67 | int out_features = linear_weight.size(0);
| ^