← Back to Leaderboard

The AI CUDA Engineer 👷

29_Matmul_Mish_Mishmodular_strided_thread_parallel_base

Level 2 • Task 29
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 followed by two Mish activations.

    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 linear transformation and two Mish activations,
            with shape (batch_size, out_features)
    """
    x = F.linear(x, weight, bias)
    x = F.mish(x)
    x = F.mish(x)
    return x


class Model(nn.Module):
    """
    Simple model that performs a matrix multiplication, applies Mish, and applies Mish again.
    """

    def __init__(self, in_features, out_features):
        super(Model, self).__init__()
        linear = nn.Linear(in_features, out_features)
        self.weight = nn.Parameter(linear.weight)
        self.bias = nn.Parameter(linear.bias + torch.ones_like(linear.bias) * 0.02)

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


batch_size = 128
in_features = 10
out_features = 20


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 Mish, and applies Mish again.
    """
    def __init__(self, in_features, out_features):
        super(Model, self).__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.linear.bias = nn.Parameter(self.linear.bias + torch.ones_like(self.linear.bias) * 0.02)

    def forward(self, x):
        x = self.linear(x)
        x = torch.nn.functional.mish(x)
        x = torch.nn.functional.mish(x)
        return x

batch_size = 128
in_features = 10
out_features = 20

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 29 • 29_Matmul_Mish_Mish)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 29_Matmul_Mish_Mish 0.01 3.65 9.33
🥇 aligned_ldg_29_matmul_mish_mish_base 0.01 3.65 9.33
🥇 optimized_ldg_matmul_mish_base 0.01 3.65 9.33
🥇 stride_loop_optimized_matmul_mish_base 0.01 3.65 9.33
🥇 optimized_tiled_kernel_base 0.01 3.65 9.33
🥇 uniform_control_flow_optimized_matmul_mish_base 0.01 3.65 9.33
🥇 matmul_mish_coalesced_base 0.01 3.65 9.33
🥇 fast_mish_tiled_base 0.01 3.65 9.33
🥇 unrolled_tiled_matmul_mish_base 0.01 3.65 9.33
🥇 matmul_mish_unroll_edit_1 0.01 3.65 9.33
🥇 matmul_mish_aligned_ldg_base 0.01 3.65 9.33
🥇 matmul_mish_aligned_ldg_edit_1 0.01 3.65 9.33
🥇 matmul_mish_coalesced_edit_1 0.01 3.65 9.33
🥇 modular_matmul_mish_base 0.01 3.65 9.33
🥇 strided_thread_parallel_base 0.01 3.65 9.33
🥇 strided_thread_parallel_edit_1 0.01 3.65 9.33
🥇 modular_strided_thread_parallel_base 0.01 3.65 9.33
🥇 warp_reduce_dot_product_base_base 0.01 3.65 9.33
🥇 warp_reduction_dot_base 0.01 3.65 9.33
🥇 tuned_block_size_128_base 0.01 3.65 9.33
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>

// Modular device function for computing softplus
__device__ float device_softplus(float x) {
    float abs_x = fabsf(x);
    float z = expf(-abs_x);
    return fmaxf(x, 0.0f) + log1pf(z);
}

// Modular device function for Mish activation
__device__ float device_mish(float x) {
    float sp = device_softplus(x);
    return x * tanhf(sp);
}

// Modular device function to compute dot product between two vectors
__device__ float compute_dot(const float* a, const float* b, int size) {
    float sum = 0.0f;
    for (int k = 0; k < size; ++k) {
        sum += a[k] * b[k];
    }
    return sum;
}

// Kernel using modular device functions
__global__ void modular_forward_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
) {
    const int total_elements = batch_size * out_features;
    const int stride = blockDim.x * gridDim.x;
    
    for (int idx = blockIdx.x * blockDim.x + threadIdx.x; 
         idx < total_elements; 
         idx += stride) {
        const int i = idx / out_features;
        const int j = idx % out_features;

        float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
        sum += bias[j];

        float y = device_mish(sum);
        output[idx] = device_mish(y);
    }
}

torch::Tensor forward(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias
) {
    TORCH_CHECK(x.dim() == 2, "x must be 2D");
    TORCH_CHECK(weight.dim() == 2, "weight must be 2D");
    TORCH_CHECK(bias.dim() == 1, "bias must be 1D");

    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 shape mismatch");
    TORCH_CHECK(bias.size(0) == out_features, "bias shape mismatch");

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

    const int block_size = 256; // Ensure block size is a multiple of 32 for warp alignment
    const int grid_size = 512;  // Optimized for better SM occupancy

    modular_forward_kernel<<<grid_size, block_size, 0, at::cuda::getCurrentCUDAStream()>>>(
        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, "Modular Strided Linear double Mish forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.358 inst/cycle 0.000 5
Executed Ipc Elapsed 0.066 inst/cycle 0.000 5
Issue Slots Busy 13.714 % 0.129 5
Issued Ipc Active 0.548 inst/cycle 0.000 5
SM Busy 13.714 % 0.129 5
Memory Throughput 3339463123.686 byte/second 11051351572120746.000 5
Mem Busy 7.440 % 0.054 5
Max Bandwidth 3.880 % 0.013 5
L1/TEX Hit Rate 95.800 % 0.000 5
L2 Hit Rate 102.472 % 0.039 5
Mem Pipes Busy 2.814 % 0.008 5
Warp Cycles Per Issued Instruction 44.394 cycle 0.397 5
Warp Cycles Per Executed Instruction 67.734 cycle 0.923 5
Avg. Active Threads Per Warp 31.250 0.000 5
Avg. Not Predicated Off Threads Per Warp 30.520 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 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 39.670 % 0.090 5
Achieved Active Warps Per SM 25.388 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 (39.3%) 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 566804.25 μs
Device Time 2.82 μs
Self CPU Time 44.14 μ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 566760.10 μs
Device Time 2.82 μs
Self CPU Time 84.97 μ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 566576.27 μs
Device Time 0.00 μs
Self CPU Time 84.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
cudaDeviceGetStreamPriorityRange
CPU Time 566295.37 μs
Device Time 0.00 μs
Self CPU Time 566295.37 μ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 46397.66 μs
Device Time 566635.59 μs
Self CPU Time 16144.79 μs
Self Device Time 566635.59 μ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 427650.10 μs
Device Time 15098.83 μs
Self CPU Time 427650.10 μs
Self Device Time 15098.83 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
modular_forward_kernel(float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 21422.22 μs
Self CPU Time 0.00 μs
Self Device Time 21422.22 μ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 16060.90 μs
Device Time 29333.78 μs
Self CPU Time 16060.90 μs
Self Device Time 29333.78 μ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 59731.98 μs
Device Time 566635.59 μs
Self CPU Time 13354.16 μ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
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 566635.59 μs
Self CPU Time 0.00 μs
Self Device Time 566635.59 μ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
45303 warnings generated when compiling for host.
Suppressed 45338 warnings (45291 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/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:32:5 bugprone-easily-swappable-parameters
32 | const float* __restrict__ weight,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
33 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:32:31: note: the first parameter in the range is 'weight'
32 | const float* __restrict__ weight,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:33:31: note: the last parameter in the range is 'bias'
33 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:35:5: warning: 2 adjacent parameters of 'modular_forward_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
35 | int batch_size,
| ^~~~~~~~~~~~~~~
36 | int in_features,
| ~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:35:9: note: the first parameter in the range is 'batch_size'
35 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:36:9: note: the last parameter in the range is 'in_features'
36 | int in_features,
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:40:24: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
40 | const int stride = blockDim.x * gridDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:42:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
42 | for (int idx = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:34: 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]
48 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:36: note: make conversion explicit to silence this warning
6 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:36: note: perform multiplication in a wider type
48 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:55: 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]
48 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:62: note: make conversion explicit to silence this warning
48 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:48:62: note: perform multiplication in a wider type
48 | float sum = compute_dot(&x[i * in_features], &weight[j * in_features], in_features);
| ^
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:57: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]
57 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:58: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]
58 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:59: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]
59 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:65:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
65 | const int batch_size = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:66:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
66 | const int in_features = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_29/b4_s1_modular_strided_thread_parallel/base/base.cu:67:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
67 | const int out_features = weight.size(0);
| ^