← Back to Leaderboard

The AI CUDA Engineer 👷

45_Gemm_Sigmoid_Sum_LogSumExpminimal_sync_fused_base_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>

__global__ void fused_linear_sigmoid_rowsum_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ row_sums,
    const int batch_size,
    const int input_size,
    const int hidden_size
) {
    int row = blockIdx.x;
    int tid = threadIdx.x;
    int warp_id = tid / 32;
    int lane_id = tid % 32;
    int warps_per_block = blockDim.x / 32;
    
    extern __shared__ float sdata[];
    
    if (row < batch_size) {
        float partial_sum = 0.0f;
        
        // Grid-stride loop over hidden dimension
        for (int col = tid; col < hidden_size; col += blockDim.x) {
            float dot = 0.0f;
            // Coalesced memory access pattern for input and weight
            for (int i = 0; i < input_size; i++) {
                dot += input[row * input_size + i] * weight[col * input_size + i];
            }
            dot += bias[col];
            partial_sum += 1.0f / (1.0f + expf(-dot));
        }

        // Warp-level reduction first
        #pragma unroll
        for (int offset = 16; offset > 0; offset /= 2) {
            partial_sum += __shfl_down_sync(0xffffffff, partial_sum, offset);
        }

        // Only first thread in each warp writes to shared memory
        if (lane_id == 0) {
            sdata[warp_id] = partial_sum;
        }
        
        // Single sync point to ensure shared memory is visible
        __syncthreads();

        // Final reduction across warps - only first warp
        if (warp_id == 0 && lane_id < warps_per_block) {
            float warp_sum = sdata[lane_id];
            
            // Warp-level reduction for final sum
            #pragma unroll
            for (int offset = warps_per_block/2; offset > 0; offset /= 2) {
                warp_sum += __shfl_down_sync(0xffffffff, warp_sum, offset);
            }

            if (lane_id == 0) {
                row_sums[row] = warp_sum;
            }
        }
    }
}

__global__ void optimized_logsumexp_kernel(
    const float* __restrict__ row_sums,
    float* __restrict__ final_output,
    const int batch_size
) {
    const int tid = threadIdx.x;
    const int lane_id = tid % 32;
    const int warp_id = tid / 32;
    
    // Step 1: Find maximum using warp-level operations
    float thread_max = -INFINITY;
    for (int i = tid; i < batch_size; i += blockDim.x) {
        thread_max = fmaxf(thread_max, row_sums[i]);
    }
    
    // Warp-level reduction for maximum
    #pragma unroll
    for (int offset = 16; offset > 0; offset /= 2) {
        float val = __shfl_down_sync(0xffffffff, thread_max, offset);
        thread_max = fmaxf(thread_max, val);
    }
    
    // Share max across warps using first element of shared memory
    __shared__ float s_max;
    if (lane_id == 0) {
        atomicMax((int*)&s_max, __float_as_int(thread_max));
    }
    __syncthreads();
    
    float global_max = s_max;
    
    // Step 2: Compute sum of exponentials
    float thread_sum = 0.0f;
    for (int i = tid; i < batch_size; i += blockDim.x) {
        thread_sum += expf(row_sums[i] - global_max);
    }
    
    // Warp-level reduction for sum
    #pragma unroll
    for (int offset = 16; offset > 0; offset /= 2) {
        thread_sum += __shfl_down_sync(0xffffffff, thread_sum, offset);
    }
    
    // Final reduction across warps
    __shared__ float s_sum;
    if (lane_id == 0) {
        atomicAdd(&s_sum, thread_sum);
    }
    __syncthreads();
    
    if (tid == 0) {
        final_output[0] = logf(s_sum) + global_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 row_sums = torch::empty({batch_size}, options);
    auto final_output = torch::empty({1}, options);

    const int blockSize = 256;
    const int warps_per_block = blockSize / 32;
    const size_t shared_mem_size = warps_per_block * sizeof(float);

    fused_linear_sigmoid_rowsum_kernel<<<batch_size, blockSize, shared_mem_size>>>(
        input.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        row_sums.data_ptr<float>(),
        batch_size,
        input_size,
        hidden_size
    );

    optimized_logsumexp_kernel<<<1, 256>>>(
        row_sums.data_ptr<float>(),
        final_output.data_ptr<float>(),
        batch_size
    );

    return final_output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Optimized forward pass");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.274 inst/cycle 0.000 5
Executed Ipc Elapsed 0.000 inst/cycle 0.000 5
Issue Slots Busy 7.326 % 0.057 5
Issued Ipc Active 0.294 inst/cycle 0.000 5
SM Busy 7.326 % 0.057 5
Memory Throughput 1250399880.650 byte/second 503462952730146.312 5
Mem Busy 9.168 % 0.021 5
Max Bandwidth 4.666 % 0.007 5
L1/TEX Hit Rate 48.480 % 0.000 5
L2 Hit Rate 101.838 % 0.027 5
Mem Pipes Busy 0.020 % 0.000 5
Warp Cycles Per Issued Instruction 27.330 cycle 2.197 5
Warp Cycles Per Executed Instruction 29.010 cycle 2.481 5
Avg. Active Threads Per Warp 22.530 0.000 5
Avg. Not Predicated Off Threads Per Warp 21.710 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 28.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.076 % 0.000 5
Achieved Active Warps Per SM 7.732 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.
WRN ThreadDivergence Instructions are executed in warps, which are groups of 32 threads. Optimal instruction throughput is achieved if all 32 threads of a warp execute the same instruction. The chosen launch configuration, early thread completion, and divergent flow control can significantly lower the number of active threads in a warp per cycle. This kernel achieves an average of 22.5 threads being active per cycle. This is further reduced to 21.7 threads per warp due to predication. The compiler may use predication to avoid an actual branch. Instead, all instructions are scheduled, but a per-thread condition code or predicate controls which threads execute the instructions. Try to avoid different execution paths within a warp when possible. In addition, ensure your kernel makes use of Independent Thread Scheduling, which allows a warp to reconverge after a data-dependent conditional block by explicitly calling __syncwarp().
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.1%) 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 218580.24 μs
Device Time 5.51 μs
Self CPU Time 49.12 μ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 218531.12 μs
Device Time 5.51 μs
Self CPU Time 101.81 μ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 218285.05 μs
Device Time 0.00 μs
Self CPU Time 111.73 μ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 217998.84 μs
Device Time 0.00 μs
Self CPU Time 217998.84 μ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 477081.88 μs
Device Time 34570.63 μs
Self CPU Time 477081.88 μs
Self Device Time 34570.63 μ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 17742.80 μs
Device Time 34492.70 μs
Self CPU Time 17742.80 μs
Self Device Time 34492.70 μ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 64263.37 μs
Device Time 619173.32 μs
Self CPU Time 13739.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::fill_
CPU Time 50526.25 μs
Device Time 619173.32 μs
Self CPU Time 17249.68 μs
Self Device Time 619173.32 μ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 619173.32 μs
Self CPU Time 0.00 μs
Self Device Time 619173.32 μ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 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/b5_s1_minimal_sync_fused_base/base/base.cu:8:5 bugprone-easily-swappable-parameters
8 | const float* __restrict__ weight,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:8:31: note: the first parameter in the range is 'weight'
8 | const float* __restrict__ weight,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:9:31: note: the last parameter in the range is 'bias'
9 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:11:5: warning: 3 adjacent parameters of 'fused_linear_sigmoid_rowsum_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
11 | const int batch_size,
| ^~~~~~~~~~~~~~~~~~~~~
12 | const int input_size,
| ~~~~~~~~~~~~~~~~~~~~~
13 | const int hidden_size
| ~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:11:15: note: the first parameter in the range is 'batch_size'
11 | const int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:13:15: note: the last parameter in the range is 'hidden_size'
13 | const int hidden_size
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:15:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
15 | int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:16:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
16 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:19:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
19 | int warps_per_block = blockDim.x / 32;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:27:55: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
27 | for (int col = tid; col < hidden_size; col += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:73:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
73 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:75:15: warning: Value stored to 'warp_id' during its initialization is never read [clang-analyzer-deadcode.DeadStores]
75 | const int warp_id = tid / 32;
| ^~~~~~~ ~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:75:15: note: Value stored to 'warp_id' during its initialization is never read
75 | const int warp_id = tid / 32;
| ^~~~~~~ ~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:79:44: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
79 | 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/b5_s1_minimal_sync_fused_base/base/base.cu:101:44: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
101 | 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/b5_s1_minimal_sync_fused_base/base/base.cu:124: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]
124 | torch::Tensor input,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:125: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]
125 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:126: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]
126 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:128:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
128 | const int batch_size = input.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:129:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
129 | const int input_size = input.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_45/b5_s1_minimal_sync_fused_base/base/base.cu:130:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
130 | const int hidden_size = weight.size(0);
| ^