← Back to Leaderboard

The AI CUDA Engineer 👷

43_Conv3d_Max_LogSumExp_ReLUblock_tuned_fused_kernel_base_base

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


def module_fn(
    x: torch.Tensor,
    stride: int,
    padding: int,
    conv_weight: torch.Tensor,
    conv_bias: torch.Tensor,
) -> torch.Tensor:
    """
    Applies 3D convolution, max pooling, log sum exp, and ReLU activation.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        stride (int): Stride of the convolution
        padding (int): Padding of the convolution
        conv_weight (torch.Tensor): Convolution weight tensor
        conv_bias (torch.Tensor): Convolution bias tensor

    Returns:
        torch.Tensor: Output tensor after applying convolution, max pooling, logsumexp and ReLU
    """
    x = F.conv3d(x, conv_weight, bias=conv_bias, stride=stride, padding=padding)
    x = F.max_pool3d(x, kernel_size=2, stride=2)
    x = torch.logsumexp(x, dim=1, keepdim=True)
    x = F.relu(x)
    return x


class Model(nn.Module):
    """
    Model that performs a 3D convolution, max pooling, log sum exp, and ReLU activation.
    """

    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super(Model, self).__init__()
        conv = nn.Conv3d(
            in_channels, out_channels, kernel_size, stride=stride, padding=padding
        )
        self.conv_weight = nn.Parameter(conv.weight)
        self.conv_bias = nn.Parameter(
            conv.bias
            + torch.randn(
                conv.bias.shape, device=conv.bias.device, dtype=conv.bias.dtype
            )
            * 0.02
        )

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


batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
stride = 1
padding = 1


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


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

class Model(nn.Module):
    """
    Model that performs a 3D convolution, max pooling, log sum exp, and ReLU activation.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)
        self.conv.bias = nn.Parameter(self.conv.bias + torch.randn(self.conv.bias.shape, device=self.conv.bias.device, dtype=self.conv.bias.dtype) * 0.02)
        self.max_pool = nn.MaxPool3d(kernel_size=2, stride=2)

    def forward(self, x):
        """
        Args:
            x: Input tensor of shape (batch_size, in_channels, depth, height, width)
        Returns:
            Output tensor of shape (batch_size, out_channels, depth', height', width')
        """
        x = self.conv(x)
        x = self.max_pool(x)
        x = torch.logsumexp(x, dim=1, keepdim=True)
        x = torch.relu(x)
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
stride = 1
padding = 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, stride, padding]

Kernel Information

Related Kernels (Level 2, Task 43 • 43_Conv3d_Max_LogSumExp_ReLU)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 strided_conv3d_max_logsumexp_relu_base 0.79 1.05 1.01
🥇 optimized_fused_kernel_base 0.79 1.05 1.01
🥇 fused_optimized_base 0.79 1.05 1.01
🥇 optimized_fused_3d_kernel_base 0.79 1.05 1.01
🥇 coalesced_memory_access_kernel_base 0.79 1.05 1.01
🥇 optimized_fused_3d_kernel_base 0.79 1.05 1.01
🥇 coalesced_memory_access_kernel_base 0.79 1.05 1.01
🥇 block_tuned_fused_kernel_base_base 0.79 1.05 1.01
🥇 unroll_fused_kernel_base_base 0.79 1.05 1.01
🥇 unroll_optimized_kernel_base_base 0.79 1.05 1.01
🥇 warp_uniform_kernel_base_base 0.79 1.05 1.01
🥇 minimal_sync_fused_kernel_base 0.79 1.05 1.01
13 optimized_thread_block_indexing_base 0.79 1.05 1.00
14 coalesced_fused_kernel_base 0.80 1.05 1.00
15 atomic_reduction_43_conv3d_base 0.81 1.03 0.99
16 fused_gridstride_logsumexp_relu_base 0.81 1.03 0.99
17 stride_loop_43_conv3d_base_base 0.81 1.03 0.99
18 43_Conv3d_Max_LogSumExp_ReLU 0.83 1.00 0.96
19 43_conv3d_max_logsumexp_relu_unrolled_optimized_base 0.83 1.00 0.95
19 43_conv3d_max_logsumexp_relu_tuned_blocksize_edit_1 0.83 1.00 0.95
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <cfloat>
#include <cmath>

__global__ void block_tuned_fused_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const int N, const int C, const int D, const int H, const int W) {
    
    // Calculate total elements and stride for thread processing
    const int total_elements = N * D * H * W;
    const int num_threads = blockDim.x * gridDim.x;
    const int thread_id = blockIdx.x * blockDim.x + threadIdx.x;
    const int spatial_stride = D * H * W;
    
    // Each thread processes multiple elements using stride loop
    for (int idx = thread_id; idx < total_elements; idx += num_threads) {
        // Decode indices more efficiently
        const int w = idx % W;
        int temp = idx / W;
        const int h = temp % H;
        temp /= H;
        const int d = temp % D;
        const int n = temp / D;

        // Calculate base index for current position
        const int base_idx = n * (C * spatial_stride) + d * (H * W) + h * W + w;

        // First pass: find maximum value across channels
        float max_val = -FLT_MAX;
        #pragma unroll 8
        for (int c = 0; c < C; ++c) {
            const int input_idx = base_idx + c * spatial_stride;
            max_val = fmaxf(max_val, input[input_idx]);
        }

        // Second pass: compute sum of exponentials
        float sum_exp = 0.0f;
        #pragma unroll 8
        for (int c = 0; c < C; ++c) {
            const int input_idx = base_idx + c * spatial_stride;
            sum_exp += expf(input[input_idx] - max_val);
        }

        // Compute final result with ReLU
        float result = max_val + logf(sum_exp);
        result = fmaxf(0.0f, result);
        
        // Write to output
        output[idx] = result;
    }
}

torch::Tensor forward(
    torch::Tensor x,
    int64_t stride,
    int64_t padding,
    torch::Tensor conv_weight,
    torch::Tensor conv_bias) {

    // Perform 3D convolution using PyTorch
    auto conv_result = torch::conv3d(x, conv_weight, conv_bias, 
                                   {stride, stride, stride}, 
                                   {padding, padding, padding});

    // Perform max pooling using PyTorch
    auto pool_result = torch::max_pool3d(conv_result, {2, 2, 2}, {2, 2, 2});

    // Get dimensions for the fused logsumexp and ReLU operations
    const int N = pool_result.size(0);
    const int C = pool_result.size(1);
    const int D = pool_result.size(2);
    const int H = pool_result.size(3);
    const int W = pool_result.size(4);

    // Create output tensor
    auto output = torch::empty({N, 1, D, H, W}, pool_result.options());

    // Use optimized block size of 128 threads
    const int block_size = 128;
    const int total_elements = N * D * H * W;
    
    // Calculate optimal number of blocks based on total elements and block size
    const int num_blocks = min(
        (total_elements + block_size - 1) / block_size,
        65535  // Maximum number of blocks
    );
    
    block_tuned_fused_kernel<<<num_blocks, block_size>>>(
        pool_result.data_ptr<float>(),
        output.data_ptr<float>(),
        N, C, D, H, W
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Block-size optimized fused kernel");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.614 inst/cycle 0.000 5
Executed Ipc Elapsed 1.196 inst/cycle 0.000 5
Issue Slots Busy 41.208 % 0.020 5
Issued Ipc Active 1.648 inst/cycle 0.000 5
SM Busy 41.208 % 0.020 5
Memory Throughput 1699886667948.028 byte/second 192144284813365084160.000 5
Mem Busy 30.628 % 0.076 5
Max Bandwidth 50.894 % 0.221 5
L1/TEX Hit Rate 46.804 % 0.000 5
L2 Hit Rate 12.262 % 0.004 5
Mem Pipes Busy 13.606 % 0.020 5
Warp Cycles Per Issued Instruction 29.656 cycle 0.031 5
Warp Cycles Per Executed Instruction 30.286 cycle 0.033 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 29.810 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 16.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 76.532 % 0.016 5
Achieved Active Warps Per SM 48.980 warp 0.007 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (24.6%) 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.
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 (76.4%) 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 4818348.86 μs
Device Time 4890399.92 μs
Self CPU Time 14106.63 μ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 4804242.23 μs
Device Time 4890399.92 μs
Self CPU Time 19381.42 μ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 4784860.81 μs
Device Time 4890399.92 μs
Self CPU Time 41676.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::cudnn_convolution
CPU Time 3856655.98 μs
Device Time 3974248.99 μs
Self CPU Time 188952.88 μs
Self Device Time 3974248.99 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaLaunchKernelExC
CPU Time 3630656.21 μs
Device Time 0.00 μs
Self CPU Time 3630656.21 μ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
sm80_xmma_fprop_implicit_gemm_f32f32_f32f32_f32_nchwkcrs_nchw_tilesize128x32x8_stage3_warpsize2x2x1_g1_ffma_aligna4_alignc4_execute_kernel__5x_cudnn
CPU Time 0.00 μs
Device Time 3974246.24 μs
Self CPU Time 0.00 μs
Self Device Time 3974246.24 μ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
45253 warnings and 1 error generated when compiling for host.
Error while processing /home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu.
Suppressed 45290 warnings (45243 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/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:11:5 bugprone-easily-swappable-parameters
11 | const int N, const int C, const int D, const int H, const int W) {
| ^~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:11:15: note: the first parameter in the range is 'N'
11 | const int N, const int C, const int D, const int H, const int W) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:11:28: note: the last parameter in the range is 'C'
11 | const int N, const int C, const int D, const int H, const int W) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:15:29: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
15 | const int num_threads = blockDim.x * gridDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:16:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
16 | const int thread_id = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:58: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]
58 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:61: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]
61 | torch::Tensor conv_weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:73:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
73 | const int N = pool_result.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:74:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
74 | const int C = pool_result.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:75:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
75 | const int D = pool_result.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:76:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
76 | const int H = pool_result.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:77:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | const int W = pool_result.size(4);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_2/task_43/b5_s3_block_tuned_fused_kernel_base/base/base.cu:87:28: error: no matching function for call to 'min' [clang-diagnostic-error]
87 | const int num_blocks = min(
| ^~~
/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)
| ^