← Back to Leaderboard

The AI CUDA Engineer 👷

78_ConvTranspose3d_Max_Max_Summodular_maxpool_kernel_base

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


def module_fn(
    x: torch.Tensor,
    stride: int,
    padding: int,
    conv_transpose: torch.Tensor,
    conv_transpose_bias: torch.Tensor,
) -> torch.Tensor:
    """
    Applies a 3D transposed convolution operation followed by two max pooling layers and a sum operation.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        stride (int): Stride of the transposed convolution
        padding (int): Padding of the transposed convolution
        conv_transpose (torch.Tensor): Transposed convolution weight tensor
        conv_transpose_bias (torch.Tensor): Bias tensor for transposed convolution

    Returns:
        torch.Tensor: Output tensor after applying transposed convolution, max pooling and sum reduction
    """
    x = F.conv_transpose3d(
        x, conv_transpose, bias=conv_transpose_bias, stride=stride, padding=padding
    )
    x = F.max_pool3d(x, kernel_size=2)
    x = F.max_pool3d(x, kernel_size=3)
    x = torch.sum(x, dim=1, keepdim=True)
    return x


class Model(nn.Module):
    """
    Model that performs a 3D transposed convolution, followed by two max pooling layers and a sum operation.
    """

    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super(Model, self).__init__()
        conv = nn.ConvTranspose3d(in_channels, out_channels, kernel_size)
        self.conv_transpose_parameter = nn.Parameter(conv.weight)
        self.conv_transpose_bias = nn.Parameter(conv.bias)

    def forward(self, x, stride, padding, fn=module_fn):
        return fn(
            x, stride, padding, self.conv_transpose_parameter, self.conv_transpose_bias
        )


batch_size = 16
in_channels = 8
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
stride = 2
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 transposed convolution, followed by two max pooling layers and a sum operation.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super(Model, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)
        self.max_pool1 = nn.MaxPool3d(kernel_size=2)
        self.max_pool2 = nn.MaxPool3d(kernel_size=3)

    def forward(self, x):
        x = self.conv_transpose(x)
        x = self.max_pool1(x)
        x = self.max_pool2(x)
        x = torch.sum(x, dim=1, keepdim=True) 
        return x

batch_size = 16
in_channels = 8
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
stride = 2
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 78 • 78_ConvTranspose3d_Max_Max_Sum)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 optimized_maxpool_kernel_base 0.58 1.05 1.21
🥇 adaptive_blocksize_maxpool_opt_base 0.58 1.05 1.21
🥉 minimized_divergence_maxpool_base_base 0.58 1.05 1.21
4 unrolled_78_convtranspose3d_optimized_base 0.59 1.03 1.19
4 modular_maxpool_kernel_base 0.59 1.03 1.19
6 fully_unrolled_maxpool_base_base 0.59 1.03 1.19
7 balanced_load_distribution_maxpool_base 0.59 1.03 1.19
8 manual_unroll_maxpool_base_base 0.59 1.03 1.19
9 coalesced_maxpool_shared_mem_base 0.60 1.02 1.18
10 unrolled_78_convtranspose3d_base 0.61 1.01 1.16
11 78_ConvTranspose3d_Max_Max_Sum 0.61 1.00 1.16
12 unroll_conv3d_max_sum_base 0.61 1.00 1.15
13 modular_conv3d_max_sum_edit_1 0.61 1.00 1.15
13 modular_conv3d_max_sum_base 0.61 1.00 1.15
13 shared_mem_reduction_max_sum_base 0.61 1.00 1.15
13 unroll_conv3d_max_sum_edit_1 0.61 1.00 1.15
17 optimized_stride_max_pool_base 0.61 1.00 1.15
17 shared_mem_reduction_max_sum_edit_1 0.61 1.00 1.15
19 constant_memory_optimization_base_edit_1 0.62 0.99 1.14
19 balanced_workload_distribution_base 0.62 0.99 1.14
#include <torch/extension.h>
#include <ATen/ATen.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cfloat>

// Device function: 2x2x2 max pooling on the input tensor
__device__ inline float pool2x2x2(const float* input, int n, int c,
                                    int start_d1, int start_h1, int start_w1,
                                    int D1, int H1, int W1, int C) {
    float max_val = -FLT_MAX;
    #pragma unroll
    for (int dd = 0; dd < 2; dd++) {
        int d1 = start_d1 + dd;
        if (d1 < D1) {
            #pragma unroll
            for (int hh = 0; hh < 2; hh++) {
                int h1 = start_h1 + hh;
                if (h1 < H1) {
                    #pragma unroll
                    for (int ww = 0; ww < 2; ww++) {
                        int w1 = start_w1 + ww;
                        if (w1 < W1) {
                            int idx = ((n * C + c) * D1 + d1) * H1 * W1 + h1 * W1 + w1;
                            max_val = max(max_val, input[idx]);
                        }
                    }
                }
            }
        }
    }
    return max_val;
}

// Device function: 3x3x3 pooling over the results of the 2x2x2 pooling
__device__ inline float pool3x3x3(const float* input, int n, int c,
                                    int start_d2, int start_h2, int start_w2,
                                    int D1, int H1, int W1, int C) {
    float max_val = -FLT_MAX;
    // The intermediate dimensions from 2x2x2 pooling are D2 = D1/2, H2 = H1/2, W2 = W1/2
    #pragma unroll
    for (int d_off = 0; d_off < 3; d_off++) {
        int d2 = start_d2 + d_off;
        if (d2 < (D1 / 2)) {
            #pragma unroll
            for (int h_off = 0; h_off < 3; h_off++) {
                int h2 = start_h2 + h_off;
                if (h2 < (H1 / 2)) {
                    #pragma unroll
                    for (int w_off = 0; w_off < 3; w_off++) {
                        int w2 = start_w2 + w_off;
                        if (w2 < (W1 / 2)) {
                            // Compute starting indices for the 2x2x2 pooling window
                            int start_d1 = d2 * 2;
                            int start_h1 = h2 * 2;
                            int start_w1 = w2 * 2;
                            float temp = pool2x2x2(input, n, c, start_d1, start_h1, start_w1, D1, H1, W1, C);
                            max_val = max(max_val, temp);
                        }
                    }
                }
            }
        }
    }
    return max_val;
}

// Main kernel: Each thread computes one element of the final pooled output
__global__ void modular_maxpool_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const int N, const int C,
    const int D1, const int H1, const int W1,
    const int D3, const int H3, const int W3) {

    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= N * C * D3 * H3 * W3) return;

    // Decode output index (n, c, d3, h3, w3)
    int w3 = idx % W3;
    int h3 = (idx / W3) % H3;
    int d3 = (idx / (W3 * H3)) % D3;
    int c  = (idx / (W3 * H3 * D3)) % C;
    int n  = idx / (W3 * H3 * D3 * C);

    // Calculate starting indices for the 3x3x3 pooling window on the intermediate tensor
    // The intermediate tensor dimensions are: D2 = D1/2, H2 = H1/2, W2 = W1/2.
    // The second maxpool has kernel size 3 and stride 3, so we compute:
    int start_d2 = d3 * 3;
    int start_h2 = h3 * 3;
    int start_w2 = w3 * 3;

    // Compute the final pooled value using the modular device function
    float val = pool3x3x3(input, n, c, start_d2, start_h2, start_w2, D1, H1, W1, C);
    output[idx] = val;
}

// The forward function applies a conv_transpose3d operation, then the modular max pooling.
// It sums over the channel dimension at the end.

torch::Tensor forward(
    torch::Tensor x,
    int64_t stride,
    int64_t padding,
    torch::Tensor conv_transpose,
    torch::Tensor conv_transpose_bias) {

    x = x.contiguous();
    conv_transpose = conv_transpose.contiguous();
    conv_transpose_bias = conv_transpose_bias.contiguous();

    TORCH_CHECK(x.is_cuda(), "Input x must be a CUDA tensor");
    TORCH_CHECK(conv_transpose.is_cuda(), "conv_transpose must be a CUDA tensor");
    TORCH_CHECK(conv_transpose_bias.is_cuda(), "conv_transpose_bias must be a CUDA tensor");

    // Apply the transposed convolution operation
    x = at::conv_transpose3d(
        x,
        conv_transpose,
        conv_transpose_bias,
        {stride, stride, stride},
        {padding, padding, padding}
    );

    // Get dimensions after conv_transpose: [N, C, D1, H1, W1]
    auto sizes = x.sizes();
    const int N = sizes[0];
    const int C = sizes[1];
    const int D1 = sizes[2];
    const int H1 = sizes[3];
    const int W1 = sizes[4];

    // The two-stage pooling reduces dimensions as follows:
    // First max pool (2x2x2): D2 = D1 / 2, H2 = H1 / 2, W2 = W1 / 2
    // Second max pool (3x3x3): D3 = D2 / 3 = D1 / 6, H3 = H1 / 6, W3 = W1 / 6
    const int D3 = D1 / 6;
    const int H3 = H1 / 6;
    const int W3 = W1 / 6;

    auto output = torch::empty({N, C, D3, H3, W3}, x.options());

    // Launch the kernel
    const int total_elements = N * C * D3 * H3 * W3;
    const int threads = 256;
    const int blocks = (total_elements + threads - 1) / threads;

    modular_maxpool_kernel<<<blocks, threads>>>(
        x.data_ptr<float>(),
        output.data_ptr<float>(),
        N, C, D1, H1, W1,
        D3, H3, W3
    );

    // Sum over channels (dim=1), keeping the dimension
    return output.sum(1, /*keepdim=*/true);
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Modular forward pass with device functions for max pooling");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.784 inst/cycle 0.000 5
Executed Ipc Elapsed 0.688 inst/cycle 0.000 5
Issue Slots Busy 19.592 % 0.004 5
Issued Ipc Active 0.784 inst/cycle 0.000 5
SM Busy 19.592 % 0.004 5
Memory Throughput 2123703289109.182 byte/second 434997002420839186432.000 5
Mem Busy 37.166 % 0.135 5
Max Bandwidth 63.374 % 0.395 5
L1/TEX Hit Rate 81.268 % 0.000 5
L2 Hit Rate 13.438 % 0.000 5
Mem Pipes Busy 7.360 % 0.006 5
Warp Cycles Per Issued Instruction 35.856 cycle 0.017 5
Warp Cycles Per Executed Instruction 35.894 cycle 0.017 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 28.340 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 43.976 % 0.000 5
Achieved Active Warps Per SM 28.146 warp 0.000 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 (44.0%) 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::conv_transpose3d
CPU Time 5429941.21 μs
Device Time 4898361.81 μs
Self CPU Time 19539.23 μ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 5410401.98 μs
Device Time 4898361.81 μs
Self CPU Time 25615.05 μ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 5384786.93 μs
Device Time 4898361.81 μs
Self CPU Time 56884.17 μ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_transpose
CPU Time 4793449.93 μs
Device Time 3865204.05 μs
Self CPU Time 277228.23 μs
Self Device Time 3865197.49 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaMemsetAsync
CPU Time 2172794.58 μs
Device Time 0.00 μs
Self CPU Time 2172794.58 μ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
sm90_xmma_dgrad_implicit_gemm_indexed_f32f32_tf32f32_f32_nhwckrsc_nhwc_tilesize256x64x32_warpgroupsize1x1x1_g1_strided_execute_kernel__5x_cudnn
CPU Time 0.00 μs
Device Time 2458013.66 μs
Self CPU Time 0.00 μs
Self Device Time 2458013.66 μ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
45287 warnings generated when compiling for host.
Suppressed 45325 warnings (45278 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_78/b9_s1_modular_maxpool_kernel/base/base.cu:8:62 bugprone-easily-swappable-parameters
8 | __device__ inline float pool2x2x2(const float* input, int n, int c,
| ^~~~~~
9 | int start_d1, int start_h1, int start_w1,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:8:66: note: the first parameter in the range is 'c'
8 | __device__ inline float pool2x2x2(const float* input, int n, int c,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:9:69: note: the last parameter in the range is 'start_w1'
9 | int start_d1, int start_h1, int start_w1,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:36:62: warning: 4 adjacent parameters of 'pool3x3x3' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
36 | __device__ inline float pool3x3x3(const float* input, int n, int c,
| ^~~~~~
37 | int start_d2, int start_h2, int start_w2,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:36:66: note: the first parameter in the range is 'c'
36 | __device__ inline float pool3x3x3(const float* input, int n, int c,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:37:69: note: the last parameter in the range is 'start_w2'
37 | int start_d2, int start_h2, int start_w2,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:73:33: warning: 2 adjacent parameters of 'modular_maxpool_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
73 | const int D1, const int H1, const int W1,
| ^~~~~~~~~~~~~
74 | const int D3, const int H3, const int W3) {
| ~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:73:43: note: the first parameter in the range is 'W1'
73 | const int D1, const int H1, const int W1,
| ^~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:74:15: note: the last parameter in the range is 'D3'
74 | const int D3, const int H3, const int W3) {
| ^~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:76:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
76 | int idx = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:127:19: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
127 | const int N = sizes[0];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:128:19: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
128 | const int C = sizes[1];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:129:20: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
129 | const int D1 = sizes[2];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:130:20: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
130 | const int H1 = sizes[3];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_78/b9_s1_modular_maxpool_kernel/base/base.cu:131:20: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
131 | const int W1 = sizes[4];
| ^