← Back to Leaderboard

The AI CUDA Engineer 👷

6_Conv3d_Softmax_MaxPool_MaxPoolbalanced_thread_block_distribution_edit_1

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>

// Kernel that performs both max pooling operations in a single pass with balanced workload distribution
__global__ void balanced_maxpool3d_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const int N, const int C, const int D, const int H, const int W
) {
    // Final output dimensions after both pooling operations
    const int D_out = D / 4;
    const int H_out = H / 4;
    const int W_out = W / 4;

    int nc_d = blockIdx.z;
    int d_out = nc_d % D_out;
    int nc = nc_d / D_out;
    int c = nc % C;
    int n = nc / C;

    int h_out = blockIdx.y * blockDim.y + threadIdx.y;
    int w_out = blockIdx.x * blockDim.x + threadIdx.x;

    if (w_out < W_out && h_out < H_out) {
        // Map to input coordinates
        int d_in_base = d_out * 4;
        int h_in_base = h_out * 4;
        int w_in_base = w_out * 4;

        float max_val = -FLT_MAX;
        
        // Single pass over 4x4x4 input region
        #pragma unroll
        for (int dz = 0; dz < 4; ++dz) {
            #pragma unroll
            for (int dy = 0; dy < 4; ++dy) {
                #pragma unroll
                for (int dx = 0; dx < 4; ++dx) {
                    int d_in = d_in_base + dz;
                    int h_in = h_in_base + dy;
                    int w_in = w_in_base + dx;
                    
                    int input_idx = n * (C * D * H * W) + 
                                  c * (D * H * W) + 
                                  d_in * (H * W) + 
                                  h_in * W + w_in;
                    
                    float val = input[input_idx];
                    max_val = max(max_val, val);
                }
            }
        }

        // Write final output
        int output_idx = n * (C * D_out * H_out * W_out) +
                        c * (D_out * H_out * W_out) +
                        d_out * (H_out * W_out) +
                        h_out * W_out +
                        w_out;
        output[output_idx] = max_val;
    }
}

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();

    // Use ATen ops for conv3d and softmax as they're highly optimized
    auto conv_output = at::conv3d(x, conv_weight, conv_bias, {1, 1, 1}, {0, 0, 0});
    auto softmax_output = at::softmax(conv_output, 1);

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

    // Final output dimensions
    int D_out = D / 4;
    int H_out = H / 4;
    int W_out = W / 4;

    auto output = at::empty({N, C, D_out, H_out, W_out}, softmax_output.options());

    // Launch kernel with balanced block size
    dim3 block(16, 16, 1);
    dim3 grid((W_out + block.x - 1) / block.x,
              (H_out + block.y - 1) / block.y,
              N * C * D_out);

    balanced_maxpool3d_kernel<<<grid, block>>>(
        softmax_output.data_ptr<float>(),
        output.data_ptr<float>(),
        N, C, D, H, W
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Balanced max pooling CUDA forward function");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.042 inst/cycle 0.000 5
Executed Ipc Elapsed 0.914 inst/cycle 0.000 5
Issue Slots Busy 26.160 % 0.006 5
Issued Ipc Active 1.046 inst/cycle 0.000 5
SM Busy 26.160 % 0.006 5
Memory Throughput 2375141774615.560 byte/second 772652346228749369344.000 5
Mem Busy 44.200 % 0.279 5
Max Bandwidth 70.916 % 0.682 5
L1/TEX Hit Rate 76.326 % 0.000 5
L2 Hit Rate 12.522 % 0.000 5
Mem Pipes Busy 22.158 % 0.071 5
Warp Cycles Per Issued Instruction 42.792 cycle 0.010 5
Warp Cycles Per Executed Instruction 42.964 cycle 0.010 5
Avg. Active Threads Per Warp 15.020 0.000 5
Avg. Not Predicated Off Threads Per Warp 14.580 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 69.734 % 0.003 5
Achieved Active Warps Per SM 44.632 warp 0.001 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 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 15.0 threads being active per cycle. This is further reduced to 14.6 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 (69.8%) 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 3770601.26 μs
Device Time 3827905.07 μs
Self CPU Time 10354.54 μ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 3760246.71 μs
Device Time 3827905.07 μs
Self CPU Time 15706.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 3744539.88 μs
Device Time 3827905.07 μs
Self CPU Time 30815.02 μ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 3229430.49 μs
Device Time 3322518.41 μs
Self CPU Time 149467.99 μs
Self Device Time 3322518.41 μ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 3050914.44 μs
Device Time 0.00 μs
Self CPU Time 3050914.44 μ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 3322516.91 μs
Self CPU Time 0.00 μs
Self Device Time 3322516.91 μ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/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:10:5 bugprone-easily-swappable-parameters
10 | const int N, const int C, const int D, const int H, const int W
| ^~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:10:15: note: the first parameter in the range is 'N'
10 | const int N, const int C, const int D, const int H, const int W
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:10:28: note: the last parameter in the range is 'C'
10 | const int N, const int C, const int D, const int H, const int W
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:17:16: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
17 | int nc_d = blockIdx.z;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:23:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
23 | int h_out = blockIdx.y * blockDim.y + threadIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:24:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | int w_out = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:80:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
80 | int N = softmax_output.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:81:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
81 | int C = softmax_output.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:82:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
82 | int D = softmax_output.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:83:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
83 | int H = softmax_output.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_2/task_6/b5_s0_balanced_thread_block_distribution/edit_1/edit_1.cu:84:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
84 | int W = softmax_output.size(4);
| ^