Merge pull request 'finish AdaptiveAvgPool3d Operator #4' (#517) from ZZZJ/GPUCodeForces:AdaptiveAvgPool3d into main

This commit is contained in:
wawahejun 2025-12-14 22:03:42 +08:00
commit 5c5eddbf66
4 changed files with 361 additions and 0 deletions

View File

@ -0,0 +1,211 @@
import torch
from torch.utils.cpp_extension import load_inline
adaptive_pool3d_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
// ---------------------------------------------------------
// Helper: Generic Index Calculation
// ---------------------------------------------------------
__device__ __forceinline__ int start_index(int out_idx, int out_len, int in_len) {
return (out_idx * in_len) / out_len;
}
__device__ __forceinline__ int end_index(int out_idx, int out_len, int in_len) {
long long tmp = (long long)(out_idx + 1) * in_len;
return (tmp + out_len - 1) / out_len;
}
// ---------------------------------------------------------
// Kernel 1: Fast Path (Integer Scaling)
// Assumes in_len % out_len == 0 for all dims
// ---------------------------------------------------------
__global__ void adaptive_avg_pool3d_fast_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int D_in, int H_in, int W_in,
int D_out, int H_out, int W_out,
int stride_d, int stride_h, int stride_w,
float inv_vol,
long in_stride_nc, // D_in * H_in * W_in
long out_stride_nc // D_out * H_out * W_out
) {
// Grid Mapping:
// Z: Batch * Channel
// Y: Output Depth (D_out)
// X: Output Spatial (H_out * W_out)
int nc = blockIdx.z;
int d_out = blockIdx.y;
int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x;
if (d_out >= D_out || spatial_idx >= H_out * W_out) return;
int h_out = spatial_idx / W_out;
int w_out = spatial_idx % W_out;
// Base Pointers
const float* vol_in = input + (long)nc * in_stride_nc;
float* vol_out = output + (long)nc * out_stride_nc;
// Fixed Window (No div/mod per loop)
int d_start = d_out * stride_d;
int h_start = h_out * stride_h;
int w_start = w_out * stride_w;
float sum = 0.0f;
// 3D Loop
#pragma unroll
for (int kz = 0; kz < stride_d; ++kz) {
int d_in = d_start + kz;
long d_offset = (long)d_in * H_in * W_in;
#pragma unroll
for (int ky = 0; ky < stride_h; ++ky) {
int h_in = h_start + ky;
long h_offset = (long)h_in * W_in;
#pragma unroll
for (int kx = 0; kx < stride_w; ++kx) {
int w_in = w_start + kx;
// Use __ldg for read-only cache
sum += __ldg(&vol_in[d_offset + h_offset + w_in]);
}
}
}
long out_idx = (long)d_out * (H_out * W_out) + spatial_idx;
vol_out[out_idx] = sum * inv_vol;
}
// ---------------------------------------------------------
// Kernel 2: Generic Path
// ---------------------------------------------------------
__global__ void adaptive_avg_pool3d_generic_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int D_in, int H_in, int W_in,
int D_out, int H_out, int W_out,
long in_stride_nc,
long out_stride_nc
) {
int nc = blockIdx.z;
int d_out = blockIdx.y;
int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x;
if (d_out >= D_out || spatial_idx >= H_out * W_out) return;
int h_out = spatial_idx / W_out;
int w_out = spatial_idx % W_out;
const float* vol_in = input + (long)nc * in_stride_nc;
float* vol_out = output + (long)nc * out_stride_nc;
// Calculate Windows
int d_start = start_index(d_out, D_out, D_in);
int d_end = end_index(d_out, D_out, D_in);
int d_len = d_end - d_start;
int h_start = start_index(h_out, H_out, H_in);
int h_end = end_index(h_out, H_out, H_in);
int h_len = h_end - h_start;
int w_start = start_index(w_out, W_out, W_in);
int w_end = end_index(w_out, W_out, W_in);
int w_len = w_end - w_start;
float sum = 0.0f;
for (int d = d_start; d < d_end; ++d) {
long d_offset = (long)d * H_in * W_in;
for (int h = h_start; h < h_end; ++h) {
long h_offset = (long)h * W_in;
for (int w = w_start; w < w_end; ++w) {
sum += __ldg(&vol_in[d_offset + h_offset + w]);
}
}
}
int vol_len = d_len * h_len * w_len;
long out_idx = (long)d_out * (H_out * W_out) + spatial_idx;
vol_out[out_idx] = (vol_len > 0) ? (sum / vol_len) : 0.0f;
}
torch::Tensor adaptive_avg_pool3d_cuda(torch::Tensor input, torch::Tensor output_size) {
int N = input.size(0);
int C = input.size(1);
int D_in = input.size(2);
int H_in = input.size(3);
int W_in = input.size(4);
auto size_cpu = output_size.cpu();
int* dims = size_cpu.data_ptr<int>();
int D_out = dims[0];
int H_out = dims[1];
int W_out = dims[2];
auto output = torch::empty({N, C, D_out, H_out, W_out}, input.options());
long in_stride_nc = (long)D_in * H_in * W_in;
long out_stride_nc = (long)D_out * H_out * W_out;
int nc = N * C;
// Check for Integer Scaling (Fast Path)
bool is_fast = (D_in % D_out == 0) && (H_in % H_out == 0) && (W_in % W_out == 0);
long total_spatial = H_out * W_out;
const int block = 256;
dim3 grid((total_spatial + block - 1) / block, D_out, nc);
if (is_fast) {
int stride_d = D_in / D_out;
int stride_h = H_in / H_out;
int stride_w = W_in / W_out;
float inv_vol = 1.0f / (float)(stride_d * stride_h * stride_w);
adaptive_avg_pool3d_fast_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
D_in, H_in, W_in,
D_out, H_out, W_out,
stride_d, stride_h, stride_w,
inv_vol,
in_stride_nc, out_stride_nc
);
} else {
adaptive_avg_pool3d_generic_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
D_in, H_in, W_in,
D_out, H_out, W_out,
in_stride_nc, out_stride_nc
);
}
return output;
}
"""
cpp_source = "torch::Tensor adaptive_avg_pool3d_cuda(torch::Tensor input, torch::Tensor output_size);"
adaptive_module = load_inline(
name="adaptive_avg_pool3d_extension",
cpp_sources=cpp_source,
cuda_sources=adaptive_pool3d_source,
functions=["adaptive_avg_pool3d_cuda"],
verbose=True,
with_cuda=True
)
class ModelNew(torch.nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
# 使用 Tensor 传递 size保持接口灵活
self.output_size = torch.tensor([32, 32, 32], dtype=torch.int32)
self.cuda_op = adaptive_module
def forward(self, x):
return self.cuda_op.adaptive_avg_pool3d_cuda(x.contiguous(), self.output_size)

View File

@ -0,0 +1,34 @@
import torch
import torch.nn as nn
torch.backends.cuda.matmul.allow_tf32 = False
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.output_size = (32, 32, 32)
self.pool = nn.AdaptiveAvgPool3d(self.output_size)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
x: [N, C, D_in, H_in, W_in]
Output: [N, C, D_out, H_out, W_out]
"""
return self.pool(x)
N = 8
C = 32
D_in = 64
H_in = 64
W_in = 64
def get_inputs():
x = torch.randint(0, 16, (N, C, D_in, H_in, W_in), device='cuda').float()
return [x]
def get_init_inputs():
return []

42
S1/ZZZJ_#4/prompt.txt Normal file
View File

@ -0,0 +1,42 @@
You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups.
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
python
# adaptive_pool3d_torch.py
import torch
import torch.nn as nn
torch.backends.cuda.matmul.allow_tf32 = False
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.output_size = (32, 32, 32)
self.pool = nn.AdaptiveAvgPool3d(self.output_size)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
x: [N, C, D_in, H_in, W_in]
Output: [N, C, D_out, H_out, W_out]
"""
return self.pool(x)
N = 8
C = 32
D_in = 64
H_in = 64
W_in = 64
def get_inputs():
x = torch.randint(0, 16, (N, C, D_in, H_in, W_in), device='cuda').float()
return [x]
def get_init_inputs():
return []```

74
S1/ZZZJ_#4/run_code.py Normal file
View File

@ -0,0 +1,74 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from adaptive_avg_pool3d_torch import Model,get_inputs,get_init_inputs
from adaptive_avg_pool3d_cuda import ModelNew
def run_benchmark():
# 检查 CUDA 是否可用
if not torch.cuda.is_available():
print("CUDA 不可用,请确保您有可用的 NVIDIA GPU 并已正确安装 PyTorch CUDA 版本。")
return
else:
device = torch.device("cuda")
# 初始化模型
init_inputs = get_init_inputs()
init_inputs = [
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in init_inputs
]
inputs = get_inputs()
inputs = [
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in inputs
]
torch_model = Model(*init_inputs).cuda()
cuda_model = ModelNew(*init_inputs).cuda()
torch_model.eval()
cuda_model.eval()
print("-------------------- 精度对齐验证 --------------------")
with torch.no_grad():
output_torch = torch_model( *inputs)
output_cuda = cuda_model(*inputs)
precision_flag = torch.allclose(output_torch, output_cuda,rtol=1e-03)
if precision_flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 100
# PyTorch 模型计时
torch.cuda.synchronize()
start_time = time.time()
for _ in range(num_iterations):
_ = torch_model(*inputs)
torch.cuda.synchronize()
torch_time = (time.time() - start_time) / num_iterations
# 自定义 CUDA 内核计时
torch.cuda.synchronize()
start_time = time.time()
for _ in range(num_iterations):
_ = cuda_model(*inputs)
torch.cuda.synchronize()
cuda_time = (time.time() - start_time) / num_iterations
print(f"PyTorch torch.relu 平均执行时间: {torch_time:.6f}")
print(f"自定义 CUDA 内核 平均执行时间: {cuda_time:.6f}")
speedup = 0
if cuda_time > 0:
speedup = torch_time / cuda_time
print(f"加速比 (Speedup): {speedup:.2f}x")
else:
print("CUDA 内核执行时间为0无法计算加速比。")
return precision_flag,speedup
if __name__ == "__main__":
precision_flag,speedup = run_benchmark()