← Back to Leaderboard

The AI CUDA Engineer 👷

45_Average_Pooling_2Dmodular_avg_pool2d_base_base

Level 1 • Task 45
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(
    x: torch.Tensor, kernel_size: int, stride: int, padding: int
) -> torch.Tensor:
    """
    Applies 2D Average Pooling using functional interface.

    Args:
        x (torch.Tensor): Input tensor
        kernel_size (int): Size of pooling window
        stride (int): Stride of pooling operation
        padding (int): Input padding

    Returns:
        torch.Tensor: Output tensor with 2D Average Pooling applied
    """
    return F.avg_pool2d(x, kernel_size=kernel_size, stride=stride, padding=padding)


class Model(nn.Module):
    """
    Simple model that performs 2D Average Pooling.
    """

    def __init__(self, kernel_size: int, stride: int, padding: int):
        """
        Initializes the Average Pooling layer.

        Args:
            kernel_size (int): Size of the pooling window
            stride (int): Stride of the pooling operation
            padding (int): Padding applied to input tensor
        """
        super(Model, self).__init__()
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding

    def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
        """
        Applies 2D Average Pooling to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, channels, height, width)
            fn: Function to apply pooling operation, defaults to module_fn

        Returns:
            torch.Tensor: Output tensor with Average Pooling applied
        """
        return fn(
            x,
            self.kernel_size,
            self.stride,
            self.padding,
        )


batch_size = 16
channels = 64
height = 256
width = 256
kernel_size = 3
stride = None  # Defaults to kernel_size
padding = 0


def get_inputs():
    x = torch.randn(batch_size, channels, height, width)
    return [x]


def get_init_inputs():
    return [kernel_size, stride if stride is not None else kernel_size, padding]
import torch
import torch.nn as nn


class Model(nn.Module):
    """
    Simple model that performs 2D Average Pooling.
    """

    def __init__(self, kernel_size: int, stride: int = None, padding: int = 0):
        """
        Initializes the Average Pooling layer.

        Args:
            kernel_size (int): Size of the pooling window.
            stride (int, optional): Stride of the pooling operation. Defaults to None (same as kernel_size).
            padding (int, optional): Padding applied to the input tensor. Defaults to 0.
        """
        super(Model, self).__init__()
        self.avg_pool = nn.AvgPool2d(
            kernel_size=kernel_size, stride=stride, padding=padding
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies 2D Average Pooling to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, channels, height, width).

        Returns:
            torch.Tensor: Output tensor with Average Pooling applied.
        """
        return self.avg_pool(x)


batch_size = 16
channels = 64
height = 256
width = 256
kernel_size = 3
stride = None  # Defaults to kernel_size
padding = 0


def get_inputs():
    x = torch.randn(batch_size, channels, height, width)
    return [x]


def get_init_inputs():
    return [kernel_size, stride if stride is not None else kernel_size, padding]

Kernel Information

Related Kernels (Level 1, Task 45 • 45_Average_Pooling_2D)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 unrolled_avg_pool2d_base 0.11 1.94 3.03
🥇 modular_avg_pool2d_base_base 0.11 1.94 3.03
🥇 grid_stride_manual_unroll_base 0.11 1.94 3.03
🥇 optimized_avg_pool2d_base 0.11 1.94 3.03
🥇 manual_unroll_avg_pool2d_base 0.11 1.94 3.03
🥇 efficient_avg_pool_base 0.11 1.94 3.03
🥇 constant_memory_avg_pool2d_base 0.11 1.94 3.03
🥇 even_workload_avg_pool2d_base 0.11 1.94 3.03
🥇 unrolled_optimized_avg_pool2d_base 0.11 1.94 3.03
10 warp_uniform_flow_base_base 0.11 1.83 2.87
10 optimized_avg_pool2d_base 0.11 1.83 2.87
10 grid_stride_avg_pool2d_base_base 0.11 1.83 2.87
10 warp_uniform_flow_base_edit_1 0.11 1.83 2.87
14 stride_optimized_avg_pool2d_base 0.12 1.82 2.84
14 warp_divergence_avg_pool2d_base 0.12 1.82 2.84
14 stride_loop_avg_pool2d_base 0.12 1.82 2.84
14 grid_unrolled_avg_pool2d_base 0.12 1.82 2.84
18 combined_avg_pool_base 0.12 1.80 2.82
18 spatial_block_optimized_base_base 0.12 1.80 2.82
18 spatial_block_optimized_base_edit_1 0.12 1.80 2.82
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

template <typename scalar_t>
__device__ __forceinline__ scalar_t compute_3x3_pool(
    const scalar_t* __restrict__ input,
    const int base_offset,
    const int W,
    const int in_x_start
) {
    const int row0 = base_offset;
    const int row1 = row0 + W;
    const int row2 = row1 + W;
    
    return input[row0 + in_x_start]     + input[row0 + in_x_start + 1]     + input[row0 + in_x_start + 2] +
           input[row1 + in_x_start]     + input[row1 + in_x_start + 1]     + input[row1 + in_x_start + 2] +
           input[row2 + in_x_start]     + input[row2 + in_x_start + 1]     + input[row2 + in_x_start + 2];
}

template <typename scalar_t>
__device__ __forceinline__ scalar_t compute_generic_pool(
    const scalar_t* __restrict__ input,
    const int base_offset,
    const int W,
    const int H,
    const int in_x_start,
    const int in_y_start,
    const int kernel_size
) {
    scalar_t sum = 0;
    #pragma unroll
    for (int ky = 0; ky < 7; ++ky) {  // Unroll up to common kernel sizes
        if (ky >= kernel_size) break;
        const int y = in_y_start + ky;
        if (y >= 0 && y < H) {
            const int row_offset = base_offset + y * W;
            #pragma unroll
            for (int kx = 0; kx < 7; ++kx) {
                if (kx >= kernel_size) break;
                const int x = in_x_start + kx;
                if (x >= 0 && x < W) {
                    sum += input[row_offset + x];
                }
            }
        }
    }
    return sum;
}

template <typename scalar_t>
__device__ __forceinline__ bool is_fully_inside(
    const int in_x_start,
    const int in_y_start,
    const int kernel_size,
    const int H,
    const int W
) {
    return (in_x_start >= 0) && (in_y_start >= 0) &&
           (in_x_start + kernel_size <= W) && (in_y_start + kernel_size <= H);
}

template <typename scalar_t>
__global__ void modular_avg_pool2d_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    const int N,
    const int C,
    const int H,
    const int W,
    const int outH,
    const int outW,
    const int kernel_size,
    const int stride,
    const int padding
) {
    const int tid = blockIdx.x * blockDim.x + threadIdx.x;
    const int total = N * C * outH * outW;
    
    if (tid >= total) return;

    // Calculate output position
    const int w_out = tid % outW;
    const int h_out = (tid / outW) % outH;
    const int c = (tid / (outW * outH)) % C;
    const int n = tid / (outW * outH * C);

    // Calculate input window position
    const int in_x_start = w_out * stride - padding;
    const int in_y_start = h_out * stride - padding;
    
    // Calculate base offset for current batch and channel
    const int base_offset = ((n * C + c) * H) * W;
    
    scalar_t sum;
    
    if (kernel_size == 3 && is_fully_inside<scalar_t>(in_x_start, in_y_start, 3, H, W)) {
        // Optimized path for 3x3 pooling
        sum = compute_3x3_pool<scalar_t>(
            input,
            base_offset + in_y_start * W,
            W,
            in_x_start
        );
    } else {
        // Generic path for other cases
        sum = compute_generic_pool<scalar_t>(
            input,
            base_offset,
            W, H,
            in_x_start,
            in_y_start,
            kernel_size
        );
    }
    
    output[tid] = sum / static_cast<scalar_t>(kernel_size * kernel_size);
}

torch::Tensor modular_avg_pool2d_forward(
    torch::Tensor x,
    int kernel_size,
    int stride,
    int padding
) {
    TORCH_CHECK(x.dim() == 4, "Input must be a 4D tensor");
    
    const int N = x.size(0);
    const int C = x.size(1);
    const int H = x.size(2);
    const int W = x.size(3);
    
    const int outH = (H + 2 * padding - kernel_size) / stride + 1;
    const int outW = (W + 2 * padding - kernel_size) / stride + 1;
    
    auto x_cont = x.contiguous();
    auto output = torch::empty({N, C, outH, outW}, x.options());
    
    const int total_elements = N * C * outH * outW;
    const int threads = 256;
    const int blocks = (total_elements + threads - 1) / threads;
    
    AT_DISPATCH_FLOATING_TYPES(x.scalar_type(), "modular_avg_pool2d_kernel", ([&] {
        modular_avg_pool2d_kernel<scalar_t><<<blocks, threads>>>(
            x_cont.data_ptr<scalar_t>(),
            output.data_ptr<scalar_t>(),
            N, C, H, W,
            outH, outW,
            kernel_size,
            stride,
            padding
        );
    }));
    
    cudaError_t err = cudaGetLastError();
    TORCH_CHECK(err == cudaSuccess, "CUDA Error: ", cudaGetErrorString(err));
    
    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &modular_avg_pool2d_forward, "Modular 2D Average Pooling forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 2.220 inst/cycle 0.001 5
Executed Ipc Elapsed 2.134 inst/cycle 0.000 5
Issue Slots Busy 55.570 % 0.423 5
Issued Ipc Active 2.224 inst/cycle 0.001 5
SM Busy 55.570 % 0.423 5
Memory Throughput 3019715749711.464 byte/second 457523578748511649792.000 5
Mem Busy 51.336 % 0.140 5
Max Bandwidth 90.114 % 0.410 5
L1/TEX Hit Rate 65.720 % 0.000 5
L2 Hit Rate 13.066 % 0.001 5
Mem Pipes Busy 18.406 % 0.021 5
Warp Cycles Per Issued Instruction 24.460 cycle 0.036 5
Warp Cycles Per Executed Instruction 24.470 cycle 0.036 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 27.710 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 85.300 % 0.003 5
Achieved Active Warps Per SM 54.592 warp 0.001 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (35.2%) 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 (85.3%) 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::to
CPU Time 577403.19 μs
Device Time 27440.91 μs
Self CPU Time 37.95 μ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::_to_copy
CPU Time 577365.24 μs
Device Time 27440.91 μs
Self CPU Time 90.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
cudaLaunchKernel
CPU Time 1151045.32 μs
Device Time 56495.31 μs
Self CPU Time 1151045.32 μs
Self Device Time 56495.31 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void modular_avg_pool2d_kernel<float>(float const*, float*, int, int, int, int, int, int, int, int, int)
CPU Time 0.00 μs
Device Time 774079.56 μs
Self CPU Time 0.00 μs
Self Device Time 774079.56 μ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 704416.61 μs
Device Time 578138.66 μs
Self CPU Time 12993.64 μ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 691424.67 μs
Device Time 578138.66 μs
Self CPU Time 15931.40 μs
Self Device Time 578138.66 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<int>, at::detail::Array<char*, 1> >(int, at::native::FillFunctor<int>, at::detail::Array<char*, 1>)
CPU Time 0.00 μs
Device Time 578138.66 μs
Self CPU Time 0.00 μs
Self Device Time 578138.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
45289 warnings generated when compiling for host.
Suppressed 45324 warnings (45277 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/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:8:5 bugprone-easily-swappable-parameters
8 | const int base_offset,
| ^~~~~~~~~~~~~~~~~~~~~~
9 | const int W,
| ~~~~~~~~~~~~
10 | const int in_x_start
| ~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:8:15: note: the first parameter in the range is 'base_offset'
8 | const int base_offset,
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:10:15: note: the last parameter in the range is 'in_x_start'
10 | const int in_x_start
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:25:5: warning: 5 adjacent parameters of 'compute_generic_pool' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
25 | const int W,
| ^~~~~~~~~~~~
26 | const int H,
| ~~~~~~~~~~~~
27 | const int in_x_start,
| ~~~~~~~~~~~~~~~~~~~~~
28 | const int in_y_start,
| ~~~~~~~~~~~~~~~~~~~~~
29 | const int kernel_size
| ~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:25:15: note: the first parameter in the range is 'W'
25 | const int W,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:29:15: note: the last parameter in the range is 'kernel_size'
29 | const int kernel_size
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:70:5: warning: 2 adjacent parameters of 'modular_avg_pool2d_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
70 | const int W,
| ^~~~~~~~~~~~
71 | const int outH,
| ~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:70:15: note: the first parameter in the range is 'W'
70 | const int W,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:71:15: note: the last parameter in the range is 'outH'
71 | const int outH,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:72:5: warning: 3 adjacent parameters of 'modular_avg_pool2d_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
72 | const int outW,
| ^~~~~~~~~~~~~~~
73 | const int kernel_size,
| ~~~~~~~~~~~~~~~~~~~~~~
74 | const int stride,
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:72:15: note: the first parameter in the range is 'outW'
72 | const int outW,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:74:15: note: the last parameter in the range is 'stride'
74 | const int stride,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:77:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | const int tid = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:128:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
128 | const int N = x.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:129:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
129 | const int C = x.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:130:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
130 | const int H = x.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:131:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
131 | const int W = x.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_45/b9_s3_modular_avg_pool2d_base/base/base.cu:143:5: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
143 | AT_DISPATCH_FLOATING_TYPES(x.scalar_type(), "modular_avg_pool2d_kernel", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:237:34: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES'
237 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:233:3: note: expanded from macro 'AT_DISPATCH_CASE_FLOATING_TYPES'
233 | AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:74:3: note: expanded from macro 'AT_DISPATCH_CASE'
74 | AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__)
| ^
note: (skipping 1 expansions in backtrace; use -fmacro-backtrace-limit=0 to see all)
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:58:7: note: expanded from macro 'AT_PRIVATE_CHECK_SELECTIVE_BUILD'
58 | AT_ERROR( \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:711:32: note: expanded from macro 'AT_ERROR'
711 | C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:536:9: note: expanded from macro 'TORCH_CHECK'
536 | __func__, \
| ^