← Back to Leaderboard

The AI CUDA Engineer 👷

31_ELUelu_hybrid_base

Level 1 • Task 31
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(x: torch.Tensor, alpha: float) -> torch.Tensor:
    """
    Applies ELU activation to the input tensor.

    Args:
        x (torch.Tensor): Input tensor of any shape.
        alpha (float): The alpha parameter for the ELU function.

    Returns:
        torch.Tensor: Output tensor with ELU applied, same shape as input.
    """
    return F.elu(x, alpha=alpha)


class Model(nn.Module):
    """
    Simple model that performs an ELU activation.
    """

    def __init__(self, alpha):
        """
        Initializes the ELU model.

        Args:
            alpha (float): The alpha parameter for the ELU function.
        """
        super(Model, self).__init__()
        self.alpha = alpha

    def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
        """
        Applies ELU activation to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of any shape.

        Returns:
            torch.Tensor: Output tensor with ELU applied, same shape as input.
        """
        return fn(x, self.alpha)


batch_size = 16
dim = 16384
alpha = 1.0


def get_inputs():
    x = torch.randn(batch_size, dim)
    return [x]


def get_init_inputs():
    return [alpha]
import torch
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    """
    Simple model that performs an ELU activation.
    """
    def __init__(self, alpha: float = 1.0):
        """
        Initializes the ELU model.

        Args:
            alpha (float, optional): The alpha parameter for the ELU function. Defaults to 1.0.
        """
        super(Model, self).__init__()
        self.alpha = alpha
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies ELU activation to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of any shape.

        Returns:
            torch.Tensor: Output tensor with ELU applied, same shape as input.
        """
        return F.elu(x, alpha=self.alpha)

batch_size = 16
dim = 16384

def get_inputs():
    x = torch.randn(batch_size, dim)
    return [x]

def get_init_inputs():
    return [1.0]  # Provide alpha value for initialization

Kernel Information

Related Kernels (Level 1, Task 31 • 31_ELU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 31_elu_shared_base 0.01 1.14 4.80
🥇 hybrid_elu_optimized_base 0.01 1.14 4.80
🥇 31_elu_vectorized_base 0.01 1.14 4.80
🥇 vec_shared_elu_base 0.01 1.14 4.80
🥇 31_elu_grid_stride_base_base 0.01 1.14 4.80
🥇 31_elu_vectorized_edit_1 0.01 1.14 4.80
🥇 elu_unroll_kernel_base 0.01 1.14 4.80
🥇 ldg_elu_128_base 0.01 1.14 4.80
9 31_ELU 0.01 0.97 4.12
9 31_elu_aligned_coalesced_base 0.01 0.97 4.12
9 hybrid_elu_base 0.01 0.97 4.12
9 31_elu_optimized_indexing_base 0.01 0.97 4.12
9 31_elu_reduced_divergence_base 0.01 0.97 4.12
9 elu_hybrid_base 0.01 0.97 4.12
9 31_elu_coalesced_base 0.01 0.97 4.12
9 31_elu_shared_mem_base 0.01 0.97 4.12
9 modular_elu_base 0.01 0.97 4.12
9 elu_vec4_shared_base 0.01 0.97 4.12
9 elu_tuned_blocksize_base 0.01 0.97 4.12
9 branchless_elu_vectorized_base 0.01 0.97 4.12
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>

// Macros to check tensor properties
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) \
    CHECK_CUDA(x);   \
    CHECK_CONTIGUOUS(x)

// Hybrid kernel: Use vectorized loads (float4) for the bulk of the data and
// shared memory to handle any tail (non-multiple-of-4) elements in a coalesced way.
__global__ void elu_kernel_hybrid(const float* __restrict__ x,
                                   float* __restrict__ out,
                                   float alpha,
                                   int n,   // total number of elements
                                   int n4)  // number of float4 elements in the bulk
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;

    // ----- Process main, vectorized part -----
    // Each thread works on 4 elements at a time using float4 if in bounds
    if (tid < n4) {
        const float4* x4 = reinterpret_cast<const float4*>(x);
        float4* out4 = reinterpret_cast<float4*>(out);
        float4 in_val = x4[tid];
        float4 res;
        res.x = (in_val.x > 0.f) ? in_val.x : alpha * (expf(in_val.x) - 1.f);
        res.y = (in_val.y > 0.f) ? in_val.y : alpha * (expf(in_val.y) - 1.f);
        res.z = (in_val.z > 0.f) ? in_val.z : alpha * (expf(in_val.z) - 1.f);
        res.w = (in_val.w > 0.f) ? in_val.w : alpha * (expf(in_val.w) - 1.f);
        out4[tid] = res;
    }

    // ----- Process tail elements -----
    // If n is not a multiple of 4, handle the remaining elements using shared memory
    int tail_start = n4 * 4;  // starting index for tail elements
    int total_threads = gridDim.x * blockDim.x;

    // Declare shared memory buffer. Each block allocates blockDim.x floats.
    extern __shared__ float tile[];

    // Use a grid-stride loop over the tail portion
    for (int i = tail_start + tid; i < n; i += total_threads) {
        int local_idx = threadIdx.x;  // each thread's slot in shared memory

        // Load scalar element from global memory into shared memory
        // (Even though for one element, using shared memory here mimics kernel1's approach
        // for coalesced memory accesses on a tile—even for tail elements.)
        tile[local_idx] = x[i];
        __syncthreads();

        // Perform the ELU activation
        float val = tile[local_idx];
        float result = (val > 0.f) ? val : alpha * (expf(val) - 1.f);
        __syncthreads();

        // Write the result back to global memory
        out[i] = result;
        __syncthreads();  // Ensure that shared memory is ready for next iteration
    }
}

// Interface function called from Python
torch::Tensor elu_cuda_hybrid(torch::Tensor x, float alpha) {
    CHECK_INPUT(x);

    auto out = torch::empty_like(x);
    int n = x.numel();

    // Calculate the number of complete float4 groups
    int n4 = n / 4;  // main vectorized part covers n4 * 4 elements

    // Determine tail count (n % 4)
    int tail_count = n - n4 * 4;

    // Decide grid size: we want to cover both the vectorized and tail parts
    // (n4 is typically >> tail_count, so using n4 works in most cases)
    int thread_needed = (n4 > tail_count ? n4 : tail_count);
    const int threads = 256;
    int blocks = (thread_needed + threads - 1) / threads;

    // Allocate shared memory per block for tail processing
    size_t sharedMemSize = threads * sizeof(float);

    elu_kernel_hybrid<<<blocks, threads, sharedMemSize>>>(
        x.data_ptr<float>(),
        out.data_ptr<float>(),
        alpha,
        n,
        n4
    );

    return out;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &elu_cuda_hybrid, "Hybrid ELU Activation with vectorized load and shared memory tail handling (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.320 inst/cycle 0.000 5
Executed Ipc Elapsed 0.128 inst/cycle 0.000 5
Issue Slots Busy 9.374 % 0.003 5
Issued Ipc Active 0.374 inst/cycle 0.000 5
SM Busy 9.374 % 0.003 5
Memory Throughput 283506633768.476 byte/second 16369674480749002752.000 5
Mem Busy 13.472 % 0.027 5
Max Bandwidth 12.374 % 0.029 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 67.066 % 0.097 5
Mem Pipes Busy 5.250 % 0.006 5
Warp Cycles Per Issued Instruction 36.476 cycle 0.422 5
Warp Cycles Per Executed Instruction 43.050 cycle 0.590 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 24.510 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 16.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 21.474 % 0.019 5
Achieved Active Warps Per SM 13.746 warp 0.008 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 (21.6%) 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 469607.63 μs
Device Time 40.19 μs
Self CPU Time 36.41 μ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 469571.22 μs
Device Time 40.19 μs
Self CPU Time 83.64 μ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 488896.46 μs
Device Time 0.00 μs
Self CPU Time 19773.43 μ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 468643.34 μs
Device Time 0.00 μs
Self CPU Time 468643.34 μ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 486043.07 μs
Device Time 22481.89 μs
Self CPU Time 486043.07 μs
Self Device Time 22481.89 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
elu_kernel_hybrid(float const*, float*, float, int, int)
CPU Time 0.00 μs
Device Time 24671.23 μs
Self CPU Time 0.00 μs
Self Device Time 24671.23 μ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 24200.21 μs
Device Time 43269.32 μs
Self CPU Time 24200.21 μs
Self Device Time 43269.32 μ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 64921.60 μs
Device Time 641573.22 μs
Self CPU Time 13164.48 μ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 51759.04 μs
Device Time 641573.22 μs
Self CPU Time 15656.53 μs
Self Device Time 641573.22 μ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 641573.22 μs
Self CPU Time 0.00 μs
Self Device Time 641573.22 μ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
45283 warnings generated when compiling for host.
Suppressed 45322 warnings (45275 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_1/task_31/b4_s2_elu_hybrid/base/base.cu:7:35 bugprone-macro-parentheses
7 | #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
| ^
| ()
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:8:41: warning: macro argument should be enclosed in parentheses [bugprone-macro-parentheses]
8 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
| ^
| ()
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:17:36: warning: 2 adjacent parameters of 'elu_kernel_hybrid' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
17 | float alpha,
| ^~~~~~~~~~~~
18 | int n, // total number of elements
| ~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:17:42: note: the first parameter in the range is 'alpha'
17 | float alpha,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:18:40: note: the last parameter in the range is 'n'
18 | int n, // total number of elements
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:18:36: note: 'float' and 'int' may be implicitly converted
18 | int n, // total number of elements
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:21:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
21 | int tid = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:40:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
40 | int total_threads = gridDim.x * blockDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:47:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
47 | int local_idx = threadIdx.x; // each thread's slot in shared memory
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:67:45: 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]
67 | torch::Tensor elu_cuda_hybrid(torch::Tensor x, float alpha) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_31/b4_s2_elu_hybrid/base/base.cu:71:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
71 | int n = x.numel();
| ^