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]
Operation Name | 45_Average_Pooling_2D |
Level ID | 1 |
Task ID | 45 |
Kernel Name | manual_unroll_avg_pool2d_base |
CUDA Speedup (Native) | 1.935x |
CUDA Speedup (Compile) | 3.025x |
CUDA Runtime | 0.108 ms |
PyTorch Runtime (Native) | 0.209 ms |
PyTorch Runtime (Compile) | 0.327 ms |
Correct | True |
Max Diff (vs. Reference) | 0.000000 |
Model | o3-mini-2025-01-31 |
Temperature | 1.00 |
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// This kernel manually unrolls the inner loops for the common 3x3 pooling case
// to reduce loop overhead. For other kernel sizes or boundary cases, it falls back
// to a generic loop with #pragma unroll hints.
template <typename scalar_t>
__global__ void manual_unroll_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
) {
// Map threads to output pixel positions using a 2D grid and use blockIdx.z for combined (n, c)
int out_x = blockIdx.x * blockDim.x + threadIdx.x;
int out_y = blockIdx.y * blockDim.y + threadIdx.y;
int nc = blockIdx.z;
int n = nc / C;
int c = nc % C;
if (out_x >= outW || out_y >= outH)
return;
// Compute starting point in the input tensor
int in_x_start = out_x * stride - padding;
int in_y_start = out_y * stride - padding;
scalar_t sum = scalar_t(0);
// Check if the pooling window is completely inside the input
bool fully_inside = (in_x_start >= 0) && (in_y_start >= 0) &&
((in_x_start + kernel_size) <= W) &&
((in_y_start + kernel_size) <= H);
// Compute the output index
int out_index = ((n * C + c) * outH + out_y) * outW + out_x;
// Fast path: if kernel_size is 3 and the window is fully inside, manually unroll loops
if (kernel_size == 3 && fully_inside) {
int base = (n * C + c) * H;
int ix = in_x_start;
int row0 = base + in_y_start;
int row1 = base + in_y_start + 1;
int row2 = base + in_y_start + 2;
sum = input[row0 * W + ix] + input[row0 * W + ix + 1] + input[row0 * W + ix + 2] +
input[row1 * W + ix] + input[row1 * W + ix + 1] + input[row1 * W + ix + 2] +
input[row2 * W + ix] + input[row2 * W + ix + 1] + input[row2 * W + ix + 2];
} else {
// Generic path with #pragma unroll hint for small kernel sizes
#pragma unroll
for (int ky = 0; ky < kernel_size; ky++) {
int y = in_y_start + ky;
#pragma unroll
for (int kx = 0; kx < kernel_size; kx++) {
int x = in_x_start + kx;
if (y >= 0 && y < H && x >= 0 && x < W) {
int index_in = ((n * C + c) * H + y) * W + x;
sum += input[index_in];
}
}
}
}
output[out_index] = sum / static_cast<scalar_t>(kernel_size * kernel_size);
}
// Forward function exposed to PyTorch
torch::Tensor manual_unroll_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 options = x.options();
auto output = torch::empty({N, C, outH, outW}, options);
// Use a 2D block for spatial dimensions and gridDim.z for the combined N*C dimension
dim3 threads(32, 8);
dim3 blocks(
(outW + threads.x - 1) / threads.x,
(outH + threads.y - 1) / threads.y,
N * C
);
AT_DISPATCH_FLOATING_TYPES(x.scalar_type(), "manual_unroll_avg_pool2d_kernel", ([&] {
manual_unroll_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", &manual_unroll_avg_pool2d_forward, "Manual Unroll 2D Average Pooling forward (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.874 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.842 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 21.922 | % | 0.013 | 5 |
Issued Ipc Active | 0.876 | inst/cycle | 0.000 | 5 |
SM Busy | 21.922 | % | 0.013 | 5 |
Memory Throughput | 3017520786118.460 | byte/second | 103011775809610088448.000 | 5 |
Mem Busy | 51.678 | % | 0.029 | 5 |
Max Bandwidth | 90.042 | % | 0.090 | 5 |
L1/TEX Hit Rate | 63.788 | % | 0.000 | 5 |
L2 Hit Rate | 12.772 | % | 0.002 | 5 |
Mem Pipes Busy | 20.900 | % | 0.007 | 5 |
Warp Cycles Per Issued Instruction | 59.542 | cycle | 0.083 | 5 |
Warp Cycles Per Executed Instruction | 59.710 | cycle | 0.085 | 5 |
Avg. Active Threads Per Warp | 29.090 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 28.650 | 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 | 82.332 | % | 0.021 | 5 |
Achieved Active Warps Per SM | 52.692 | warp | 0.009 | 5 |
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 (82.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::to | ||
CPU Time | 382901.93 | μs |
Device Time | 27217.13 | μs |
Self CPU Time | 35.30 | μ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 | 382866.63 | μs |
Device Time | 27217.13 | μs |
Self CPU Time | 97.16 | μ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 | 1183519.86 | μs |
Device Time | 57755.01 | μs |
Self CPU Time | 1183519.86 | μs |
Self Device Time | 57755.01 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
void manual_unroll_avg_pool2d_kernel<float>(float const*, float*, int, int, int, int, int, int, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 790469.58 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 790469.58 | μ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 | 722719.40 | μs |
Device Time | 591017.94 | μs |
Self CPU Time | 13138.36 | μ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 | 709582.55 | μs |
Device Time | 591017.94 | μs |
Self CPU Time | 16429.69 | μs |
Self Device Time | 591017.94 | μ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 | 591017.94 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 591017.94 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45290 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.