Compare commits

...

1 Commits

Author SHA1 Message Date
ZZZJ f2e6deb1b8 fixes LPPool3d #150 2025-12-09 21:34:52 +08:00
4 changed files with 325 additions and 0 deletions

View File

@ -0,0 +1,175 @@
import torch
from torch.utils.cpp_extension import load_inline
lp_pool3d_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cmath>
__global__ void lp_pool3d_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 kernel_size, int stride,
float p, float inv_p,
long in_stride_nc, // D_in * H_in * W_in
long out_stride_nc // D_out * H_out * W_out
) {
int nc = blockIdx.z;
int d_out = blockIdx.y;
int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x;
if (spatial_idx >= H_out * W_out) return;
// Decode Spatial Coords
int h_out = spatial_idx / W_out;
int w_out = spatial_idx % W_out;
// Base Pointers for this (n, c) volume
const float* vol_in = input + (long)nc * in_stride_nc;
float* vol_out = output + (long)nc * out_stride_nc;
int d_start = d_out * stride;
int h_start = h_out * stride;
int w_start = w_out * stride;
float sum_pow = 0.0f;
// 3D Sliding Window Loop
// Compiler will optimize this loop structure
for (int kd = 0; kd < kernel_size; ++kd) {
int d_in = d_start + kd;
if (d_in >= 0 && d_in < D_in) {
long d_offset = (long)d_in * H_in * W_in;
for (int kh = 0; kh < kernel_size; ++kh) {
int h_in = h_start + kh;
if (h_in >= 0 && h_in < H_in) {
long h_offset = (long)h_in * W_in;
for (int kw = 0; kw < kernel_size; ++kw) {
int w_in = w_start + kw;
if (w_in >= 0 && w_in < W_in) {
// Read Input (Texture Cache)
float val = __ldg(&vol_in[d_offset + h_offset + w_in]);
// Optimization for p=2 (L2 Norm)
if (p == 2.0f) {
sum_pow += val * val;
} else if (p == 1.0f) {
sum_pow += fabsf(val);
} else {
sum_pow += powf(fabsf(val), p);
}
}
}
}
}
}
}
// Final Power
float res;
if (p == 2.0f) {
res = sqrtf(sum_pow);
} else if (p == 1.0f) {
res = sum_pow;
} else {
res = powf(sum_pow, inv_p);
}
// Write Output
long out_idx = (long)d_out * (H_out * W_out) + spatial_idx;
vol_out[out_idx] = res;
}
torch::Tensor lp_pool3d_cuda(torch::Tensor input, float p, int kernel_size, int stride, bool ceil_mode) {
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);
// Calculate Output Shape
// Floor mode (default)
int D_out = (D_in - kernel_size) / stride + 1;
int H_out = (H_in - kernel_size) / stride + 1;
int W_out = (W_in - kernel_size) / stride + 1;
if (ceil_mode) {
D_out = (D_in - kernel_size + stride - 1) / stride + 1;
H_out = (H_in - kernel_size + stride - 1) / stride + 1;
W_out = (W_in - kernel_size + stride - 1) / stride + 1;
// Basic padding correction logic would go here if needed
}
if (D_out < 1) D_out = 1;
if (H_out < 1) H_out = 1;
if (W_out < 1) W_out = 1;
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;
float inv_p = 1.0f / p;
long spatial_out = H_out * W_out;
// Config
const int block = 256;
dim3 grid(
(spatial_out + block - 1) / block,
D_out,
nc
);
lp_pool3d_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
D_in, H_in, W_in,
D_out, H_out, W_out,
kernel_size, stride,
p, inv_p,
in_stride_nc, out_stride_nc
);
return output;
}
"""
cpp_source = "torch::Tensor lp_pool3d_cuda(torch::Tensor input, float p, int kernel_size, int stride, bool ceil_mode);"
lp_pool3d_module = load_inline(
name="lp_pool3d_extension",
cpp_sources=cpp_source,
cuda_sources=lp_pool3d_source,
functions=["lp_pool3d_cuda"],
verbose=True,
with_cuda=True
)
class ModelNew(torch.nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.norm_type = 2.0
self.kernel_size = 3
self.stride = 2
self.ceil_mode = False
self.cuda_op = lp_pool3d_module
def forward(self, x):
return self.cuda_op.lp_pool3d_cuda(
x.contiguous(),
self.norm_type,
self.kernel_size,
self.stride,
self.ceil_mode
)

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.norm_type = 2.0
self.kernel_size = 3
self.stride = 2
self.ceil_mode = False
self.lp_pool = nn.LPPool3d(
norm_type=self.norm_type,
kernel_size=self.kernel_size,
stride=self.stride,
ceil_mode=self.ceil_mode
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lp_pool(x)
N = 4
C = 32
D = 32
H = 64
W = 64
def get_inputs():
x = torch.randint(-5, 5, (N, C, D, H, W), device='cuda').float()
return [x]
def get_init_inputs():
return []

42
S1/ZZZJ_#150/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
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.norm_type = 2.0
self.kernel_size = 3
self.stride = 2
self.ceil_mode = False
self.lp_pool = nn.LPPool3d(
norm_type=self.norm_type,
kernel_size=self.kernel_size,
stride=self.stride,
ceil_mode=self.ceil_mode
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lp_pool(x)
N = 4
C = 32
D = 32
H = 64
W = 64
def get_inputs():
x = torch.randint(-5, 5, (N, C, D, H, W), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

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

@ -0,0 +1,74 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from lp_pool3d_torch import Model,get_inputs,get_init_inputs
from lp_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()