← Back to Leaderboard

The AI CUDA Engineer 👷

6_Conv3d_Softmax_MaxPool_MaxPoolcoalesced_maxpool_base_base

Level 2 • Task 6
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,
) -> torch.Tensor:
    """Applies 3D convolution, softmax activation, and two max pooling operations.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        conv_weight (torch.Tensor): Convolution weight tensor of shape
            (out_channels, in_channels, kernel_size, kernel_size, kernel_size)
        conv_bias (torch.Tensor): Bias tensor for convolution of shape (out_channels)

    Returns:
        torch.Tensor: Output tensor after applying convolution, softmax and max pooling,
            with shape (batch_size, out_channels, depth', height', width') where:
            depth' = ((depth - kernel_size + 1) // 4)
            height' = ((height - kernel_size + 1) // 4)
            width' = ((width - kernel_size + 1) // 4)
            The //4 comes from two max pooling operations with kernel_size=2
    """
    x = F.conv3d(x, conv_weight, conv_bias, stride=1, padding=0)
    x = F.softmax(x, dim=1)
    x = F.max_pool3d(x, kernel_size=2)
    x = F.max_pool3d(x, kernel_size=2)
    return x


class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies Softmax, and performs two max pooling operations.
    """

    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(Model, self).__init__()
        conv = nn.Conv3d(in_channels, out_channels, kernel_size, padding=1)
        self.conv_weight = nn.Parameter(conv.weight)
        self.conv_bias = nn.Parameter(conv.bias)

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


batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
pool_kernel_size = 2


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


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

class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies Softmax, and performs two max pooling operations.
    """
    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.pool1 = nn.MaxPool3d(pool_kernel_size)
        self.pool2 = nn.MaxPool3d(pool_kernel_size)
        

    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') where depth', height', width' are the dimensions after pooling.
        """
        x = self.conv(x)
        x = torch.softmax(x, dim=1)
        x = self.pool1(x)
        x = self.pool2(x)
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
pool_kernel_size = 2

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

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

Kernel Information

Related Kernels (Level 2, Task 6 • 6_Conv3d_Softmax_MaxPool_MaxPool)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 strided_maxpool_base_base 0.95 1.13 0.90
🥈 stride_loop_maxpool_optimized_base 0.95 1.13 0.89
🥉 coalesced_maxpool_base_base 0.96 1.12 0.89
4 hybrid_maxpool3d_kernel_edit_1 0.96 1.11 0.88
5 hybrid_maxpool3d_kernel_base 0.96 1.11 0.88
5 balanced_thread_block_distribution_base 0.96 1.11 0.88
7 balanced_thread_block_distribution_edit_1 0.96 1.11 0.88
8 fused_max_pool3d_base 0.98 1.10 0.87
9 fused_maxpool_opt_base 0.99 1.08 0.86
10 coalesced_maxpool_edit_1 0.99 1.08 0.86
10 efficient_double_pooling_edit_1 0.99 1.08 0.86
10 efficient_double_pooling_base 0.99 1.08 0.86
13 coalesced_maxpool_base 1.00 1.07 0.85
14 blocksize_experiment_maxpool_base 1.00 1.07 0.85
15 divergence_free_maxpool_base_base 1.03 1.04 0.83
16 stride_loop_maxpool_base_base 1.03 1.04 0.83
16 optimized_shared_maxpool_base_base 1.03 1.04 0.83
18 strided_modular_maxpool_base 1.04 1.03 0.82
19 fused_double_maxpool_base 1.04 1.03 0.82
20 efficient_fused_pooling_base 1.04 1.03 0.82
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cfloat>

__global__ void coalesced_maxpool_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const int N, const int C, const int D, const int H, const int W,
    const int outD, const int outH, const int outW,
    const int items_per_block
) {
    // Reorganized memory layout for coalesced access
    const int stride_n = C * D * H * W;
    const int stride_c = D * H * W;
    const int stride_d = H * W;
    const int stride_h = W;
    
    // New thread mapping: prioritize width dimension for coalescing
    const int tid = threadIdx.x;
    const int local_w = tid % 4;          // Fastest dimension [0-3]
    const int local_h = (tid / 4) % 4;    // Medium dimension [0-3]
    const int local_d = tid / 16;         // Slowest dimension [0-3]

    const int total_elements = N * C * outD * outH * outW;
    const int block_start = blockIdx.x * items_per_block;

    // Process multiple elements per block
    #pragma unroll 4
    for (int item_idx = 0; item_idx < items_per_block; item_idx++) {
        const int global_idx = block_start + item_idx;
        if (global_idx >= total_elements) break;

        // Convert linear index to 5D output coordinates
        const int n = global_idx / (C * outD * outH * outW);
        int rem = global_idx % (C * outD * outH * outW);
        const int c = rem / (outD * outH * outW);
        rem %= outD * outH * outW;
        const int out_d = rem / (outH * outW);
        rem %= outH * outW;
        const int out_h = rem / outW;
        const int out_w = rem % outW;

        // Input window starting positions
        const int d_start = out_d * 4;
        const int h_start = out_h * 4;
        const int w_start = out_w * 4;

        // Global input coordinates with coalesced access pattern
        const int d = d_start + local_d;
        const int h = h_start + local_h;
        const int w = w_start + local_w;

        // Coalesced memory access with boundary checks
        float val = -FLT_MAX;
        if (d < D && h < H && w < W) {
            const int input_idx = n * stride_n + c * stride_c + d * stride_d + h * stride_h + w;
            val = __ldg(&input[input_idx]);
        }

        // Warp-level reduction with optimized shuffle pattern
        #pragma unroll
        for (int offset = 16; offset > 0; offset /= 2) {
            val = fmaxf(val, __shfl_down_sync(0xffffffff, val, offset));
        }

        // Efficient shared memory reduction
        __shared__ float smem[2];
        if (tid % 32 == 0) smem[tid/32] = val;
        __syncthreads();

        // Final reduction in first warp
        if (tid < 32) {
            float tmp = tid < 2 ? smem[tid] : -FLT_MAX;
            #pragma unroll
            for (int offset = 1; offset > 0; offset >>= 1) {
                tmp = fmaxf(tmp, __shfl_down_sync(0xffffffff, tmp, offset));
            }
            if (tid == 0) {
                output[global_idx] = tmp;
            }
        }
        __syncthreads();
    }
}

torch::Tensor forward(
    torch::Tensor x,
    torch::Tensor conv_weight,
    torch::Tensor conv_bias
) {
    x = x.contiguous();
    conv_weight = conv_weight.contiguous();
    conv_bias = conv_bias.contiguous();

    auto conv_output = at::conv3d(x, conv_weight, conv_bias, {1, 1, 1}, {0, 0, 0});
    auto softmax_output = at::softmax(conv_output, 1);

    const int N = softmax_output.size(0);
    const int C = softmax_output.size(1);
    const int D = softmax_output.size(2);
    const int H = softmax_output.size(3);
    const int W = softmax_output.size(4);

    const int outD = D / 4;
    const int outH = H / 4;
    const int outW = W / 4;

    auto output = torch::empty({N, C, outD, outH, outW}, softmax_output.options());

    const int items_per_block = 8;
    const int total_elements = N * C * outD * outH * outW;
    const int num_blocks = (total_elements + items_per_block - 1) / items_per_block;
    
    coalesced_maxpool_kernel<<<num_blocks, 64>>>(
        softmax_output.data_ptr<float>(),
        output.data_ptr<float>(),
        N, C, D, H, W,
        outD, outH, outW,
        items_per_block
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Coalesced memory access CUDA forward");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 2.950 inst/cycle 0.000 5
Executed Ipc Elapsed 2.880 inst/cycle 0.000 5
Issue Slots Busy 73.792 % 0.000 5
Issued Ipc Active 2.950 inst/cycle 0.000 5
SM Busy 74.502 % 0.000 5
Memory Throughput 644867685714.884 byte/second 842901734189980928.000 5
Mem Busy 33.402 % 0.002 5
Max Bandwidth 19.892 % 0.001 5
L1/TEX Hit Rate 48.512 % 0.000 5
L2 Hit Rate 46.376 % 0.004 5
Mem Pipes Busy 18.316 % 0.001 5
Warp Cycles Per Issued Instruction 15.432 cycle 0.000 5
Warp Cycles Per Executed Instruction 15.440 cycle 0.000 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.540 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 24.000 block 0.000 5
Block Limit Shared Mem 56.000 block 0.000 5
Block Limit Warps 32.000 block 0.000 5
Theoretical Active Warps per SM 48.000 warp 0.000 5
Theoretical Occupancy 75.000 % 0.000 5
Achieved Occupancy 71.184 % 0.000 5
Achieved Active Warps Per SM 45.560 warp 0.000 5
Analysis Rules
Rule Description
WRN HighPipeUtilization ALU is the highest-utilized pipeline (74.5%) based on active cycles, taking into account the rates of its different instructions. It executes integer and logic operations. The pipeline is well-utilized, but might become a bottleneck if more work is added. Based on the number of executed instructions, the highest utilized pipeline (74.5%) is ALU. It executes integer and logic operations. Comparing the two, the overall pipeline utilization appears to be caused by frequent, low-latency instructions. See the Kernel Profiling Guide (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-decoder) or hover over the pipeline name to understand the workloads handled by each pipeline. The Instruction Statistics section shows the mix of executed instructions in this kernel. Check the Warp State Statistics section for which reasons cause warps to stall.
WRN Occupancy This kernel's theoretical occupancy (75.0%) is limited by the number of required registers. 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 4715070.29 μs
Device Time 4771861.08 μs
Self CPU Time 12410.83 μ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 4702659.46 μs
Device Time 4771861.08 μs
Self CPU Time 18817.59 μ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 4683841.87 μs
Device Time 4771861.08 μs
Self CPU Time 37197.11 μ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 4029813.31 μs
Device Time 4137525.11 μs
Self CPU Time 170204.02 μs
Self Device Time 4137525.11 μ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 3822938.73 μs
Device Time 0.00 μs
Self CPU Time 3822938.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
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 4137522.61 μs
Self CPU Time 0.00 μs
Self Device Time 4137522.61 μ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
45285 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/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:9:57 bugprone-easily-swappable-parameters
9 | const int N, const int C, const int D, const int H, const int W,
| ^~~~~~~~~~~~
10 | const int outD, const int outH, const int outW,
| ~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:9:67: note: the first parameter in the range is 'W'
9 | const int N, const int C, const int D, const int H, const int W,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:10:15: note: the last parameter in the range is 'outD'
10 | const int outD, const int outH, const int outW,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:10:37: warning: 2 adjacent parameters of 'coalesced_maxpool_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
10 | const int outD, const int outH, const int outW,
| ^~~~~~~~~~~~~~~
11 | const int items_per_block
| ~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:10:47: note: the first parameter in the range is 'outW'
10 | const int outD, const int outH, const int outW,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:11:15: note: the last parameter in the range is 'items_per_block'
11 | const int items_per_block
| ^~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:20:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
20 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:26:29: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
26 | const int block_start = blockIdx.x * items_per_block;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:99:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
99 | const int N = softmax_output.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:100:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
100 | const int C = softmax_output.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:101:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
101 | const int D = softmax_output.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:102:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
102 | const int H = softmax_output.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_6/b9_s3_coalesced_maxpool_base/base/base.cu:103:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
103 | const int W = softmax_output.size(4);
| ^