fixes Maxunpool1d #11

This commit is contained in:
ZZZJ 2025-12-09 16:07:46 +08:00
parent cc73715277
commit 1bb1c04c4c
4 changed files with 280 additions and 0 deletions

View File

@ -0,0 +1,108 @@
# maxunpool1d_cuda.py
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from maxunpool1d_torch import BATCH_SIZE, CHANNELS, WIDTH_IN, WIDTH_OUT, KERNEL_SIZE, STRIDE
BLOCK_SIZE = 256
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_W = output_size[0]
self.width_out = WIDTH_OUT
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_header = """
#include <torch/extension.h>
torch::Tensor maxunpool1d_forward_cuda(
torch::Tensor input_pooled, torch::Tensor indices, int W_in, int W_out
);
"""
cuda_source = f"""
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE {BLOCK_SIZE}
#define VEC_SIZE {VEC_SIZE}
__global__ void maxunpool1d_kernel(
const float* __restrict__ input_pooled,
const long* __restrict__ indices,
float* __restrict__ output_data,
int W_in, int W_out, int N_C_W_out
) {{
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int grid_stride = gridDim.x * blockDim.x;
const int W_in_total = W_in;
for (int idx = tid; idx < N_C_W_out; idx += grid_stride) {{
const float pooled_val = input_pooled[idx];
const long target_w_in_index = indices[idx];
const int w_out = idx % W_out;
const int nc_idx = idx / W_out;
const int base_offset = nc_idx * W_in_total;
const int target_idx = base_offset + (int)target_w_in_index;
output_data[target_idx] = pooled_val;
}}
}}
torch::Tensor maxunpool1d_forward_cuda(
torch::Tensor input_pooled, torch::Tensor indices, int W_in, int W_out
) {{
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);
auto output = torch::zeros({{N, C, W_in}}, input_pooled.options());
const int N_C_W_out = N * C * W_out;
dim3 block_dim(BLOCK_SIZE);
const int grid_size = (N_C_W_out + BLOCK_SIZE - 1) / BLOCK_SIZE;
dim3 grid_dim(grid_size);
maxunpool1d_kernel<<<grid_dim, block_dim>>>(
input_pooled.data_ptr<float>(),
indices.data_ptr<long>(),
output.data_ptr<float>(),
W_in, W_out, N_C_W_out
);
return output;
}}
"""
self.unpool_op = load_inline(
name="maxunpool1d_op",
cpp_sources=cpp_header,
cuda_sources=cuda_source,
functions=["maxunpool1d_forward_cuda"],
verbose=False
)
def forward(self, input: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
return self.unpool_op.maxunpool1d_forward_cuda(
input.contiguous(),
indices.contiguous(),
self.output_size_W,
self.width_out
)

View File

@ -0,0 +1,45 @@
# maxunpool1d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
BATCH_SIZE = 32
CHANNELS = 64
WIDTH_IN = 256
KERNEL_SIZE = 3
STRIDE = 2
WIDTH_OUT = math.floor((WIDTH_IN - KERNEL_SIZE) / STRIDE) + 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.MaxUnpool1d(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, WIDTH_IN, dtype=torch.float32)
input_pooled, indices = F.max_pool1d(
x,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
return_indices=True
)
return [input_pooled, indices]
def get_init_inputs():
return [KERNEL_SIZE, STRIDE, (WIDTH_IN,)] # output_size 传递 (W_in,)

53
S1/ZZZJ_#11/prompt.txt Normal file
View File

@ -0,0 +1,53 @@
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
# maxunpool1d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
BATCH_SIZE = 32
CHANNELS = 64
WIDTH_IN = 256
KERNEL_SIZE = 3
STRIDE = 2
WIDTH_OUT = math.floor((WIDTH_IN - KERNEL_SIZE) / STRIDE) + 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.MaxUnpool1d(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, WIDTH_IN, dtype=torch.float32)
input_pooled, indices = F.max_pool1d(
x,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
return_indices=True
)
return [input_pooled, indices]
def get_init_inputs():
return [KERNEL_SIZE, STRIDE, (WIDTH_IN,)] # output_size 传递 (W_in,)
```

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

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