← Back to Leaderboard

The AI CUDA Engineer 👷

90_Conv3d_LeakyReLU_Sum_Clamp_GELUoptimized_strided_loop_base_base

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


def module_fn(
    x: torch.Tensor,
    conv_weight: torch.Tensor,
    conv_bias: torch.Tensor,
    sum_tensor: torch.Tensor,
) -> torch.Tensor:
    """
    Applies 3D convolution, LeakyReLU, tensor addition, clamping and GELU activation.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        conv_weight (torch.Tensor): 3D convolution weight tensor of shape
            (out_channels, in_channels, kernel_size, kernel_size, kernel_size)
        conv_bias (torch.Tensor): Bias tensor for 3D convolution of shape (out_channels)
        sum_tensor (torch.Tensor): Tensor to add of shape (out_channels, 1, 1, 1)

    Returns:
        torch.Tensor: Output tensor after applying convolution, LeakyReLU, addition,
            clamping and GELU activation
    """
    x = F.conv3d(x, conv_weight, bias=conv_bias)
    x = F.leaky_relu(x, negative_slope=0.2)
    x = x + sum_tensor
    x = torch.clamp(x, min=-1.0, max=1.0)
    x = F.gelu(x)
    return x


class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies LeakyReLU, sums with a tensor, clamps, and applies GELU activation.
    """

    def __init__(self, in_channels, out_channels, kernel_size, sum_tensor_shape):
        super(Model, self).__init__()
        conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.conv_weight = conv.weight
        self.conv_bias = conv.bias
        self.sum_tensor = nn.Parameter(torch.randn(sum_tensor_shape) * 0.02)

    def forward(self, x, fn=module_fn):
        return fn(x, self.conv_weight, self.conv_bias, self.sum_tensor)


batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
sum_tensor_shape = (out_channels, 1, 1, 1)


def get_inputs():
    return [torch.randn(batch_size, in_channels, depth, height, width)]


def get_init_inputs():
    return [in_channels, out_channels, kernel_size, sum_tensor_shape]
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies LeakyReLU, sums with a tensor, clamps, and applies GELU activation.
    """
    def __init__(self, in_channels, out_channels, kernel_size, sum_tensor_shape):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.sum_tensor = nn.Parameter(torch.randn(sum_tensor_shape)*0.02)

    def forward(self, x):
        x = self.conv(x)
        x = torch.nn.functional.leaky_relu(x, negative_slope=0.2)
        x = x + self.sum_tensor
        x = torch.clamp(x, min=-1.0, max=1.0)
        x = torch.nn.functional.gelu(x)
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
sum_tensor_shape = (out_channels, 1, 1, 1)

def get_inputs():
    return [torch.randn(batch_size, in_channels, depth, height, width)]

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, sum_tensor_shape]

Kernel Information

Related Kernels (Level 2, Task 90 • 90_Conv3d_LeakyReLU_Sum_Clamp_GELU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 aligned_vectorized_ldg_90_conv3d_edit_1 0.79 1.25 0.66
🥈 aligned_vectorized_ldg_90_conv3d_base 0.80 1.24 0.66
🥉 modular_device_functions_base 0.81 1.21 0.65
🥉 load_balanced_kernel_base_base 0.81 1.21 0.65
5 constant_memory_optimization_base 0.82 1.21 0.65
6 coalesced_mem_access_opt_base 0.82 1.20 0.64
7 atomic_minimal_usage_kernel_opt_base 0.83 1.20 0.64
7 atomic_minimal_usage_kernel_opt_edit_1 0.83 1.20 0.64
9 modular_device_functions_v2_base 0.83 1.20 0.64
10 balanced_workload_distribution_base 0.83 1.19 0.64
11 warp_primitives_based_kernel_edit_1 0.83 1.19 0.63
12 optimized_strided_loop_base_base 0.83 1.19 0.63
13 gridstride_const_base 0.84 1.18 0.63
13 block_size_256_kernel_base 0.84 1.18 0.63
15 warp_divergence_free_base 0.84 1.18 0.63
15 modular_device_functions_base 0.84 1.18 0.63
17 optimized_kernel_combination_base 0.84 1.18 0.63
18 multidim_indexed_kernel_base 0.84 1.18 0.63
18 const_mem_conv3d_leakyrelu_sumclamp_gelu_base 0.84 1.18 0.63
20 90_Conv3d_LeakyReLU_Sum_Clamp_GELU 0.84 1.17 0.63
#include <torch/extension.h>
#include <ATen/ATen.h>
#include <vector>
#include <cmath>

// Inline device functions for element-wise operations
__device__ inline float leaky_relu(float x, float alpha = 0.2f) {
    return (x > 0.0f) ? x : alpha * x;
}

__device__ inline float clamp_val(float x, float min_val = -1.0f, float max_val = 1.0f) {
    return fmaxf(fminf(x, max_val), min_val);
}

__device__ inline float gelu(float x) {
    float tanh_out = tanhf(0.7978845608f * (x + 0.044715f * x * x * x));
    return x * 0.5f * (1.0f + tanh_out);
}

// Optimized CUDA kernel with efficient stride loop pattern
__global__ void strided_kernel(
    const float* __restrict__ input,
    const float* __restrict__ sum_tensor,
    float* __restrict__ output,
    const int64_t num_elements,
    const int64_t width,
    const int64_t height,
    const int64_t depth,
    const int64_t channels,
    const int64_t spatial_size) {

    // Calculate base index and stride
    const int64_t tid = threadIdx.x;
    const int64_t bid = blockIdx.x;
    const int64_t block_size = blockDim.x;
    const int64_t grid_size = gridDim.x;
    
    // Calculate starting index for this thread
    int64_t idx = bid * block_size + tid;
    const int64_t stride = block_size * grid_size;
    
    // Process multiple elements per thread using stride loop
    while (idx < num_elements) {
        // Calculate spatial position
        const int64_t pos = idx % spatial_size;
        const int64_t w = pos % width;
        const int64_t h = (pos / width) % height;
        const int64_t d = (pos / (width * height)) % depth;
        
        // Calculate channel index
        const int64_t c = (idx / spatial_size) % channels;
        
        // Process element
        float x = input[idx];
        float y = leaky_relu(x);
        y += sum_tensor[c];
        y = clamp_val(y);
        y = gelu(y);
        output[idx] = y;
        
        // Move to next element with stride
        idx += stride;
    }
}

// Optimized kernel launcher
void strided_kernel_launcher(torch::Tensor &x, torch::Tensor &sum_tensor) {
    const int64_t batch_size = x.size(0);
    const int64_t channels = x.size(1);
    const int64_t depth = x.size(2);
    const int64_t height = x.size(3);
    const int64_t width = x.size(4);
    
    const int64_t spatial_size = width * height * depth;
    const int64_t num_elements = x.numel();

    // Optimize thread and block configuration
    const int threads_per_block = 256;
    const int64_t max_blocks = 65535;
    const int64_t needed_blocks = (num_elements + threads_per_block - 1) / threads_per_block;
    const int num_blocks = min(needed_blocks, max_blocks);

    strided_kernel<<<num_blocks, threads_per_block>>>(
        x.data_ptr<float>(),
        sum_tensor.data_ptr<float>(),
        x.data_ptr<float>(),
        num_elements,
        width,
        height,
        depth,
        channels,
        spatial_size
    );
}

// Forward function
torch::Tensor forward(
    torch::Tensor x,
    torch::Tensor conv_weight,
    torch::Tensor conv_bias,
    torch::Tensor sum_tensor) {

    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(conv_weight.is_cuda(), "conv_weight must be a CUDA tensor");
    TORCH_CHECK(conv_bias.is_cuda(), "conv_bias must be a CUDA tensor");
    TORCH_CHECK(sum_tensor.is_cuda(), "sum_tensor must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "x must be float32");

    // Perform 3D convolution
    auto x_conv = at::conv3d(x, conv_weight, conv_bias);

    // Ensure contiguous memory layout
    auto output = x_conv.contiguous();

    // Launch optimized kernel with stride loop pattern
    strided_kernel_launcher(output, sum_tensor);

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Optimized strided Conv3d LeakyReLU Sum Clamp GELU forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 3.252 inst/cycle 0.000 5
Executed Ipc Elapsed 3.208 inst/cycle 0.000 5
Issue Slots Busy 81.386 % 0.000 5
Issued Ipc Active 3.256 inst/cycle 0.000 5
SM Busy 81.386 % 0.000 5
Memory Throughput 1098224054260.694 byte/second 5392443141263693824.000 5
Mem Busy 18.628 % 0.002 5
Max Bandwidth 32.770 % 0.005 5
L1/TEX Hit Rate 55.454 % 0.000 5
L2 Hit Rate 50.388 % 0.005 5
Mem Pipes Busy 17.750 % 0.001 5
Warp Cycles Per Issued Instruction 17.438 cycle 0.000 5
Warp Cycles Per Executed Instruction 17.440 cycle 0.000 5
Avg. Active Threads Per Warp 29.650 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.950 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 89.096 % 0.006 5
Achieved Active Warps Per SM 57.020 warp 0.002 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (57.0%) based on active cycles, taking into account the rates of its different instructions. It executes integer and logic operations. It is well-utilized, but should not be a bottleneck.
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 (89.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::conv3d
CPU Time 718166.33 μs
Device Time 5279106.30 μs
Self CPU Time 13293.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
aten::convolution
CPU Time 704872.39 μs
Device Time 5279106.30 μs
Self CPU Time 19019.35 μ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::_convolution
CPU Time 685853.05 μs
Device Time 5279106.30 μs
Self CPU Time 37733.75 μ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::cudnn_convolution
CPU Time 564498.30 μs
Device Time 4576530.93 μs
Self CPU Time 179314.65 μs
Self Device Time 4576530.93 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
sm80_xmma_fprop_implicit_gemm_indexed_f32f32_f32f32_f32_nchwkcrs_nchw_tilesize32x32x8_stage3_warpsize1x2x1_g1_ffma_aligna4_alignc4_execute_kernel__5x_cudnn
CPU Time 0.00 μs
Device Time 4576528.31 μs
Self CPU Time 0.00 μs
Self Device Time 4576528.31 μ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 5393886.19 μs
Device Time 1635.86 μs
Self CPU Time 5393886.19 μs
Self Device Time 1635.86 μ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 1094476.56 μs
Device Time 595933.97 μs
Self CPU Time 17678.55 μ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 1076799.35 μs
Device Time 595933.97 μs
Self CPU Time 25220.25 μs
Self Device Time 595933.97 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
Status: Failed
45247 warnings and 1 error generated when compiling for host.
Error while processing /home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu.
Suppressed 45289 warnings (45242 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.
Found compiler error(s).
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:22:5 bugprone-easily-swappable-parameters
22 | const float* __restrict__ input,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
23 | const float* __restrict__ sum_tensor,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:22:31: note: the first parameter in the range is 'input'
22 | const float* __restrict__ input,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:23:31: note: the last parameter in the range is 'sum_tensor'
23 | const float* __restrict__ sum_tensor,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:25:5: warning: 2 adjacent parameters of 'strided_kernel' of similar type ('const int64_t') are easily swapped by mistake [bugprone-easily-swappable-parameters]
25 | const int64_t num_elements,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | const int64_t width,
| ~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:25:19: note: the first parameter in the range is 'num_elements'
25 | const int64_t num_elements,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:26:19: note: the last parameter in the range is 'width'
26 | const int64_t width,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:28:5: warning: 2 adjacent parameters of 'strided_kernel' of similar type ('const int64_t') are easily swapped by mistake [bugprone-easily-swappable-parameters]
28 | const int64_t depth,
| ^~~~~~~~~~~~~~~~~~~~
29 | const int64_t channels,
| ~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:28:19: note: the first parameter in the range is 'depth'
28 | const int64_t depth,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:29:19: note: the last parameter in the range is 'channels'
29 | const int64_t channels,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:81:28: error: no matching function for call to 'min' [clang-diagnostic-error]
81 | const int num_blocks = min(needed_blocks, max_blocks);
| ^~~
/home/common_modules/clang-tidy/20.0.0git/lib/clang/20/include/__clang_cuda_math.h:201:16: note: candidate function not viable: call to __device__ function from __host__ function
201 | __DEVICE__ int min(int __a, int __b) { return __nv_min(__a, __b); }
| ^
/usr/local/cuda/include/crt/math_functions.hpp:868:38: note: candidate function not viable: call to __device__ function from __host__ function
868 | __MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const unsigned int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:873:38: note: candidate function not viable: call to __device__ function from __host__ function
873 | __MATH_FUNCTIONS_DECL__ unsigned int min(const int a, const unsigned int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:878:38: note: candidate function not viable: call to __device__ function from __host__ function
878 | __MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:883:34: note: candidate function not viable: call to __device__ function from __host__ function
883 | __MATH_FUNCTIONS_DECL__ long int min(const long int a, const long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:902:43: note: candidate function not viable: call to __device__ function from __host__ function
902 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const unsigned long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:919:43: note: candidate function not viable: call to __device__ function from __host__ function
919 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const long int a, const unsigned long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:936:43: note: candidate function not viable: call to __device__ function from __host__ function
936 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:953:39: note: candidate function not viable: call to __device__ function from __host__ function
953 | __MATH_FUNCTIONS_DECL__ long long int min(const long long int a, const long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:958:48: note: candidate function not viable: call to __device__ function from __host__ function
958 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const unsigned long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:963:48: note: candidate function not viable: call to __device__ function from __host__ function
963 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const long long int a, const unsigned long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:968:48: note: candidate function not viable: call to __device__ function from __host__ function
968 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:973:31: note: candidate function not viable: call to __device__ function from __host__ function
973 | __MATH_FUNCTIONS_DECL__ float min(const float a, const float b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:978:32: note: candidate function not viable: call to __device__ function from __host__ function
978 | __MATH_FUNCTIONS_DECL__ double min(const double a, const double b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:983:32: note: candidate function not viable: call to __device__ function from __host__ function
983 | __MATH_FUNCTIONS_DECL__ double min(const float a, const double b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:988:32: note: candidate function not viable: call to __device__ function from __host__ function
988 | __MATH_FUNCTIONS_DECL__ double min(const double a, const float b)
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:98: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]
98 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_90/b9_s3_optimized_strided_loop_base/base/base.cu:99:19: warning: the parameter 'conv_weight' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
99 | torch::Tensor conv_weight,
| ^
| const &