fixes Maxunpool2d #12

This commit is contained in:
ZZZJ 2025-12-09 16:09:48 +08:00
parent cc73715277
commit 8dc136c6dc
4 changed files with 308 additions and 0 deletions

View File

@ -0,0 +1,128 @@
# maxunpool2d_cuda.py
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from maxunpool2d_torch import BATCH_SIZE, CHANNELS, H_IN, W_IN, H_OUT, W_OUT, KERNEL_SIZE, STRIDE
BLOCK_SIZE = 512
VEC_SIZE = 4
class ModelNew(nn.Module):
def __init__(self, kernel_size, stride, output_size):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.output_size = output_size # (H_in, W_in) tuple
self.h_in = output_size[0] # H_in
self.w_in = output_size[1] # W_in
self.h_out = H_OUT # H_out (pooled size)
self.w_out = W_OUT # W_out (pooled size)
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_header = """
#include <torch/extension.h>
torch::Tensor maxunpool2d_forward_cuda(
torch::Tensor input_pooled, torch::Tensor indices, int H_in, int W_in
);
"""
cuda_source = f"""
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE {BLOCK_SIZE}
#define VEC_SIZE {VEC_SIZE}
__global__ void maxunpool2d_kernel(
const float* __restrict__ input_pooled,
const long* __restrict__ indices,
float* __restrict__ output_data,
int N, int C, int H_in, int W_in, int H_out, int W_out
) {{
const int N_C_H_out_W_out = N * C * H_out * W_out;
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int grid_stride = gridDim.x * blockDim.x;
const int C_H_in_W_in = C * H_in * W_in;
const int HW_in = H_in * W_in;
const int H_out_W_out = H_out * W_out;
// Vectorized Read pointers (reading pooled input)
const float4* __restrict__ pooled_vec = (const float4*)input_pooled;
const long4* __restrict__ indices_vec = (const long4*)indices;
// NOTE: Vectorizing the read of indices (long4) is complex due to 64-bit size.
// We optimize the loop structure and rely on the compiler for efficient scalar reads.
for (int idx = tid; idx < N_C_H_out_W_out; idx += grid_stride) {{
const int w_out = idx % W_out;
const int h_w_out = idx / W_out;
const int h_out = h_w_out % H_out;
const int n_c = h_w_out / H_out;
const int n_idx = n_c / C;
const int c_idx = n_c % C;
const float pooled_val = input_pooled[idx];
const long target_linear_index = indices[idx];
const int base_offset = (n_idx * C_H_in_W_in) + (c_idx * HW_in);
const int target_idx = base_offset + (int)target_linear_index;
output_data[target_idx] = pooled_val;
}}
}}
torch::Tensor maxunpool2d_forward_cuda(
torch::Tensor input_pooled, torch::Tensor indices, int H_in, int W_in
) {{
TORCH_CHECK(input_pooled.is_cuda() && indices.is_cuda(), "Inputs must be CUDA tensors");
const int N = input_pooled.size(0);
const int C = input_pooled.size(1);
const int H_out = input_pooled.size(2);
const int W_out = input_pooled.size(3);
auto output = torch::zeros({{N, C, H_in, W_in}}, input_pooled.options());
const int N_C_H_out_W_out = N * C * H_out * W_out;
dim3 block_dim(BLOCK_SIZE);
const int grid_size = (N_C_H_out_W_out + BLOCK_SIZE - 1) / BLOCK_SIZE;
dim3 grid_dim(grid_size);
maxunpool2d_kernel<<<grid_dim, block_dim>>>(
input_pooled.data_ptr<float>(),
indices.data_ptr<long>(), // indices long 类型
output.data_ptr<float>(),
N, C, H_in, W_in, H_out, W_out
);
return output;
}}
"""
self.unpool_op = load_inline(
name="maxunpool2d_op",
cpp_sources=cpp_header,
cuda_sources=cuda_source,
functions=["maxunpool2d_forward_cuda"],
verbose=False
)
def forward(self, input: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
return self.unpool_op.maxunpool2d_forward_cuda(
input.contiguous(),
indices.contiguous(),
self.h_in,
self.w_in
)

View File

@ -0,0 +1,49 @@
# maxunpool2d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
BATCH_SIZE = 16
CHANNELS = 128
H_IN, W_IN = 64, 64
KERNEL_SIZE = (3, 3)
STRIDE = (2, 2)
K_H, K_W = KERNEL_SIZE
S_H, S_W = STRIDE
H_OUT = math.floor((H_IN - K_H) / S_H) + 1
W_OUT = math.floor((W_IN - K_W) / S_W) + 1
class Model(nn.Module):
def __init__(self, kernel_size, stride, output_size):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.output_size = output_size
self.max_unpool = nn.MaxUnpool2d(kernel_size=kernel_size, stride=stride)
def forward(self, input: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
return self.max_unpool(input, indices, self.output_size)
def get_inputs():
x = torch.randn(BATCH_SIZE, CHANNELS, H_IN, W_IN, dtype=torch.float32)
input_pooled, indices = F.max_pool2d(
x,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
return_indices=True
)
return [input_pooled, indices]
def get_init_inputs():
return [KERNEL_SIZE, STRIDE, (H_IN, W_IN)]

57
S1/ZZZJ_#12/prompt.txt Normal file
View File

@ -0,0 +1,57 @@
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
# maxunpool2d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
BATCH_SIZE = 16
CHANNELS = 128
H_IN, W_IN = 64, 64
KERNEL_SIZE = (3, 3)
STRIDE = (2, 2)
K_H, K_W = KERNEL_SIZE
S_H, S_W = STRIDE
H_OUT = math.floor((H_IN - K_H) / S_H) + 1
W_OUT = math.floor((W_IN - K_W) / S_W) + 1
class Model(nn.Module):
def __init__(self, kernel_size, stride, output_size):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.output_size = output_size
self.max_unpool = nn.MaxUnpool2d(kernel_size=kernel_size, stride=stride)
def forward(self, input: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
return self.max_unpool(input, indices, self.output_size)
def get_inputs():
x = torch.randn(BATCH_SIZE, CHANNELS, H_IN, W_IN, dtype=torch.float32)
input_pooled, indices = F.max_pool2d(
x,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
return_indices=True
)
return [input_pooled, indices]
def get_init_inputs():
return [KERNEL_SIZE, STRIDE, (H_IN, W_IN)]
```

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

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