← Back to Leaderboard

The AI CUDA Engineer 👷

45_Gemm_Sigmoid_Sum_LogSumExplogsumexp_warp_reduce_base

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


def module_fn(
    x: torch.Tensor,
    linear1_weight: torch.Tensor,
    linear1_bias: torch.Tensor,
) -> torch.Tensor:
    """
    Performs matrix multiplication, applies Sigmoid, sums result, and calculates LogSumExp.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, input_size)
        linear1_weight (torch.Tensor): Weight matrix for first linear layer of shape (hidden_size, input_size)
        linear1_bias (torch.Tensor): Bias vector for first linear layer of shape (hidden_size)

    Returns:
        torch.Tensor: Scalar output after applying linear layers, sigmoid, sum and logsumexp
    """
    x = F.linear(x, linear1_weight, linear1_bias)
    x = torch.sigmoid(x)
    x = torch.sum(x, dim=1)
    x = torch.logsumexp(x, dim=0)
    return x


class Model(nn.Module):
    """
    Model that performs a matrix multiplication (Gemm), applies Sigmoid, sums the result, and calculates the LogSumExp.
    """

    def __init__(self, input_size, hidden_size, output_size):
        super(Model, self).__init__()
        lin1 = nn.Linear(input_size, hidden_size)
        self.linear1_weight = nn.Parameter(lin1.weight)
        self.linear1_bias = nn.Parameter(
            lin1.bias
            + torch.randn(
                lin1.bias.shape, device=lin1.bias.device, dtype=lin1.bias.dtype
            )
            * 0.02
        )

    def forward(self, x, fn=module_fn):
        return fn(x, self.linear1_weight, self.linear1_bias)


batch_size = 128
input_size = 10
hidden_size = 20
output_size = 5


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


def get_init_inputs():
    return [input_size, hidden_size, output_size]
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Model that performs a matrix multiplication (Gemm), applies Sigmoid, sums the result, and calculates the LogSumExp.
    """
    def __init__(self, input_size, hidden_size, output_size):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(input_size, hidden_size)
        self.linear1.bias = nn.Parameter(self.linear1.bias + torch.randn(self.linear1.bias.shape, device=self.linear1.bias.device, dtype=self.linear1.bias.dtype) * 0.02)

    def forward(self, x):
        x = self.linear1(x)
        x = torch.sigmoid(x)
        x = torch.sum(x, dim=1)
        x = torch.logsumexp(x, dim=0)
        return x

batch_size = 128
input_size = 10
hidden_size = 20
output_size = 5

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

def get_init_inputs():
    return [input_size, hidden_size, output_size]

Kernel Information

Related Kernels (Level 2, Task 45 • 45_Gemm_Sigmoid_Sum_LogSumExp)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 fused_gemm_sigmoid_logsumexp_base 0.01 5.98 2.74
🥇 fused_gemm_sigmoid_logsumexp_edit_1 0.01 5.98 2.74
🥉 minimal_sync_shared_memory_base_base 0.01 5.31 2.44
🥉 variable_block_size_tuning_base_base 0.01 5.31 2.44
🥉 aligned_memory_access_base_base 0.01 5.31 2.44
🥉 optimized_thread_block_mapping_base_base 0.01 5.31 2.44
🥉 strided_loop_optimized_base_base 0.01 5.31 2.44
🥉 warp_fused_base 0.01 5.31 2.44
🥉 minimal_sync_fused_base_base 0.01 5.31 2.44
🥉 shared_memory_optimized_base_base 0.01 5.31 2.44
11 fused_linear_reduction_base 0.01 4.78 2.19
11 variable_block_size_base_base 0.01 4.78 2.19
11 warp_divergence_minimization_base 0.01 4.78 2.19
11 fused_gemm_reduction_atomic_opt_edit_1 0.01 4.78 2.19
11 optimized_sync_fusion_kernel_base 0.01 4.78 2.19
11 modular_fused_kernel_opt_base 0.01 4.78 2.19
11 block_size_experimentation_edit_1 0.01 4.78 2.19
11 block_size_experimentation_base 0.01 4.78 2.19
19 fused_gemm_reduction_atomic_opt_base 0.01 4.35 2.00
19 logsumexp_warp_reduce_base 0.01 4.35 2.00
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>

// CUDA kernel for matrix multiplication + bias
__global__ void linear_sigmoid_kernel(
    const float* input,
    const float* weight,
    const float* bias,
    float* output,
    const int batch_size,
    const int input_size,
    const int hidden_size
) {
    const int row = blockIdx.x * blockDim.x + threadIdx.x;
    const int col = blockIdx.y * blockDim.y + threadIdx.y;

    if (row < batch_size && col < hidden_size) {
        float sum = 0.0f;
        for (int i = 0; i < input_size; i++) {
            sum += input[row * input_size + i] * weight[col * input_size + i];
        }
        sum += bias[col];
        output[row * hidden_size + col] = 1.0f / (1.0f + expf(-sum));
    }
}

// CUDA kernel for sum reduction
__global__ void sum_reduction_kernel(
    const float* input,
    float* output,
    const int batch_size,
    const int hidden_size
) {
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    
    if (idx < batch_size) {
        float sum = 0.0f;
        for (int i = 0; i < hidden_size; i++) {
            sum += input[idx * hidden_size + i];
        }
        output[idx] = sum;
    }
}

// Optimized logsumexp with warp-level reduction
__global__ void logsumexp_warp_reduce_kernel(
    const float* input,
    float* output,
    const int batch_size
) {
    const int tid = threadIdx.x;
    const int warp_size = 32;
    
    // Each thread handles multiple elements
    float thread_max = -INFINITY;
    float thread_sum = 0.0f;
    
    for (int i = tid; i < batch_size; i += blockDim.x) {
        thread_max = fmaxf(thread_max, input[i]);
    }

    // Warp-level max reduction
    for (int offset = warp_size/2; offset > 0; offset /= 2) {
        float val = __shfl_down_sync(0xFFFFFFFF, thread_max, offset);
        thread_max = fmaxf(thread_max, val);
    }

    const float block_max = __shfl_sync(0xFFFFFFFF, thread_max, 0);

    // Compute sum of exps
    for (int i = tid; i < batch_size; i += blockDim.x) {
        thread_sum += expf(input[i] - block_max);
    }

    // Warp-level sum reduction
    for (int offset = warp_size/2; offset > 0; offset /= 2) {
        float val = __shfl_down_sync(0xFFFFFFFF, thread_sum, offset);
        thread_sum += val;
    }

    if (tid == 0) {
        output[0] = logf(thread_sum) + block_max;
    }
}

torch::Tensor forward(
    torch::Tensor input,
    torch::Tensor weight,
    torch::Tensor bias
) {
    const int batch_size = input.size(0);
    const int input_size = input.size(1);
    const int hidden_size = weight.size(0);

    auto options = torch::TensorOptions()
        .dtype(input.dtype())
        .device(input.device());

    auto linear_output = torch::empty({batch_size, hidden_size}, options);
    auto sum_output = torch::empty({batch_size}, options);
    auto final_output = torch::empty({1}, options);

    dim3 threadsPerBlock(32, 32);
    dim3 numBlocks(
        (batch_size + threadsPerBlock.x - 1) / threadsPerBlock.x,
        (hidden_size + threadsPerBlock.y - 1) / threadsPerBlock.y
    );

    linear_sigmoid_kernel<<<numBlocks, threadsPerBlock>>>(
        input.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        linear_output.data_ptr<float>(),
        batch_size,
        input_size,
        hidden_size
    );

    sum_reduction_kernel<<<(batch_size + 255) / 256, 256>>>(
        linear_output.data_ptr<float>(),
        sum_output.data_ptr<float>(),
        batch_size,
        hidden_size
    );

    const int threads = 256;
    logsumexp_warp_reduce_kernel<<<1, threads>>>(
        sum_output.data_ptr<float>(),
        final_output.data_ptr<float>(),
        batch_size
    );

    return final_output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Forward pass");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.194 inst/cycle 0.000 5
Executed Ipc Elapsed 0.000 inst/cycle 0.000 5
Issue Slots Busy 5.142 % 0.036 5
Issued Ipc Active 0.206 inst/cycle 0.000 5
SM Busy 5.142 % 0.036 5
Memory Throughput 1141071828.378 byte/second 441855840094804.875 5
Mem Busy 9.430 % 0.027 5
Max Bandwidth 4.814 % 0.007 5
L1/TEX Hit Rate 48.480 % 0.000 5
L2 Hit Rate 101.424 % 0.016 5
Mem Pipes Busy 0.014 % 0.000 5
Warp Cycles Per Issued Instruction 27.596 cycle 2.606 5
Warp Cycles Per Executed Instruction 29.430 cycle 2.965 5
Avg. Active Threads Per Warp 31.570 0.000 5
Avg. Not Predicated Off Threads Per Warp 30.150 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 16.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 9.152 % 0.017 5
Achieved Active Warps Per SM 5.858 warp 0.007 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 (9.0%) 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 552801.59 μs
Device Time 5.60 μs
Self CPU Time 46.67 μ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 552754.92 μs
Device Time 5.60 μs
Self CPU Time 94.27 μ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 552518.23 μs
Device Time 0.00 μs
Self CPU Time 110.94 μ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 552187.77 μs
Device Time 0.00 μs
Self CPU Time 552187.77 μ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 496033.42 μs
Device Time 47584.55 μs
Self CPU Time 496033.42 μs
Self Device Time 47584.55 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
linear_sigmoid_kernel(float const*, float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 32519.43 μs
Self CPU Time 0.00 μs
Self Device Time 32519.43 μ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 66081.43 μs
Device Time 645988.74 μs
Self CPU Time 13854.90 μ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 52228.11 μs
Device Time 645988.74 μs
Self CPU Time 16476.13 μs
Self Device Time 645988.74 μ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 646067.43 μs
Self CPU Time 0.00 μs
Self Device Time 646067.43 μ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 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/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:9:5 bugprone-easily-swappable-parameters
9 | const float* weight,
| ^~~~~~~~~~~~~~~~~~~~
10 | const float* bias,
| ~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:9:18: note: the first parameter in the range is 'weight'
9 | const float* weight,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:10:18: note: the last parameter in the range is 'bias'
10 | const float* bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:12:5: warning: 2 adjacent parameters of 'linear_sigmoid_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
12 | const int batch_size,
| ^~~~~~~~~~~~~~~~~~~~~
13 | const int input_size,
| ~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:12:15: note: the first parameter in the range is 'batch_size'
12 | const int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:13:15: note: the last parameter in the range is 'input_size'
13 | const int input_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:16:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
16 | const int row = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:17:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
17 | const int col = blockIdx.y * blockDim.y + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:33:5: warning: 2 adjacent parameters of 'sum_reduction_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
33 | const int batch_size,
| ^~~~~~~~~~~~~~~~~~~~~
34 | const int hidden_size
| ~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:33:15: note: the first parameter in the range is 'batch_size'
33 | const int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:34:15: note: the last parameter in the range is 'hidden_size'
34 | const int hidden_size
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:36:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
36 | const int idx = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:53:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
53 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:60:44: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
60 | for (int i = tid; i < batch_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:73:44: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
73 | for (int i = tid; i < batch_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:89:19: warning: the parameter 'input' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
89 | torch::Tensor input,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:90: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]
90 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:91: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]
91 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:93:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
93 | const int batch_size = input.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:94:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
94 | const int input_size = input.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b2_s1_logsumexp_warp_reduce/base/base.cu:95:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
95 | const int hidden_size = weight.size(0);
| ^