6_Conv3d_Softmax_MaxPool_MaxPool
• efficient_double_pooling_edit_1
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]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cfloat>
__global__ void max_pool3d_coalesced_kernel(const float* __restrict__ input, float* __restrict__ output,
const int N, const int C, const int D, const int H, const int W) {
int D_out = D / 2;
int H_out = H / 2;
int W_out = W / 2;
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) {
int d_in = d_out * 2;
int h_in = h_out * 2;
int w_in = w_out * 2;
int input_base = n * (C * D * H * W) + c * (D * H * W) + d_in * (H * W) + h_in * W + w_in;
float max_val = -FLT_MAX;
#pragma unroll
for (int dz = 0; dz < 2; ++dz) {
#pragma unroll
for (int dy = 0; dy < 2; ++dy) {
#pragma unroll
for (int dx = 0; dx < 2; ++dx) {
int index = input_base + dz * (H * W) + dy * W + dx;
max_val = fmaxf(max_val, input[index]);
}
}
}
int output_index = 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_index] = max_val;
}
}
// Optimized forward function
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);
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);
int D_out = D / 2;
int H_out = H / 2;
int W_out = W / 2;
auto pool1 = at::empty({N, C, D_out, H_out, W_out}, softmax_output.options());
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);
const float* input_ptr = softmax_output.data_ptr<float>();
float* output_ptr = pool1.data_ptr<float>();
max_pool3d_coalesced_kernel<<<grid, block>>>(input_ptr, output_ptr, N, C, D, H, W);
int D1 = D_out;
int H1 = H_out;
int W1 = W_out;
int D_out2 = D1 / 2;
int H_out2 = H1 / 2;
int W_out2 = W1 / 2;
auto pool2 = at::empty({N, C, D_out2, H_out2, W_out2}, softmax_output.options());
dim3 grid2((W_out2 + block.x - 1) / block.x,
(H_out2 + block.y - 1) / block.y,
N * C * D_out2);
const float* input_ptr2 = pool1.data_ptr<float>();
float* output_ptr2 = pool2.data_ptr<float>();
max_pool3d_coalesced_kernel<<<grid2, block>>>(input_ptr2, output_ptr2, N, C, D1, H1, W1);
cudaDeviceSynchronize();
return pool2;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Optimized CUDA double max pooling with coalesced memory accesses");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 2.210 | inst/cycle | 0.064 | 5 |
Executed Ipc Elapsed | 1.836 | inst/cycle | 0.003 | 5 |
Issue Slots Busy | 55.530 | % | 43.160 | 5 |
Issued Ipc Active | 2.220 | inst/cycle | 0.068 | 5 |
SM Busy | 55.530 | % | 43.160 | 5 |
Memory Throughput | 2190986731079.556 | byte/second | 696491129240975317139456.000 | 5 |
Mem Busy | 41.852 | % | 150.103 | 5 |
Max Bandwidth | 65.434 | % | 618.913 | 5 |
L1/TEX Hit Rate | 58.726 | % | 2.442 | 5 |
L2 Hit Rate | 25.626 | % | 33.456 | 5 |
Mem Pipes Busy | 28.310 | % | 16.988 | 5 |
Warp Cycles Per Issued Instruction | 22.464 | cycle | 23.723 | 5 |
Warp Cycles Per Executed Instruction | 22.556 | cycle | 23.342 | 5 |
Avg. Active Threads Per Warp | 24.004 | 32.518 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 22.300 | 24.970 | 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 | 76.168 | % | 62.188 | 5 |
Achieved Active Warps Per SM | 48.748 | warp | 25.487 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (36.8%) 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 (82.6%) 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. |
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 17.0 threads being active per cycle. This is further reduced to 16.2 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(). |
Operation / Metric | Value | Unit |
---|---|---|
aten::to | ||
CPU Time | 243093.24 | μs |
Device Time | 2586.77 | μs |
Self CPU Time | 54.40 | μ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::conv3d | ||
CPU Time | 330175.87 | μs |
Device Time | 3831817.82 | μs |
Self CPU Time | 11376.10 | μ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 | 318799.76 | μs |
Device Time | 3831817.82 | μs |
Self CPU Time | 14220.46 | μ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 | 304579.31 | μs |
Device Time | 3831817.82 | μs |
Self CPU Time | 27675.68 | μ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 | 208856.66 | μs |
Device Time | 3326798.46 | μs |
Self CPU Time | 152461.76 | μs |
Self Device Time | 3326798.46 | μ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 | 3326796.99 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 3326796.99 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
cudaDeviceSynchronize | ||
CPU Time | 5481534.19 | μs |
Device Time | 63796.53 | μs |
Self CPU Time | 5481534.19 | μs |
Self Device Time | 63796.53 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
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.