diff --git a/S1/ZZZJ_#12/maxunpool2d_cuda.py b/S1/ZZZJ_#12/maxunpool2d_cuda.py new file mode 100644 index 00000000..33c81ec6 --- /dev/null +++ b/S1/ZZZJ_#12/maxunpool2d_cuda.py @@ -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::Tensor maxunpool2d_forward_cuda( + torch::Tensor input_pooled, torch::Tensor indices, int H_in, int W_in + ); + """ + + cuda_source = f""" + #include + #include + + #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<<>>( + input_pooled.data_ptr(), + indices.data_ptr(), // indices 是 long 类型 + output.data_ptr(), + 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 + ) \ No newline at end of file diff --git a/S1/ZZZJ_#12/maxunpool2d_torch.py b/S1/ZZZJ_#12/maxunpool2d_torch.py new file mode 100644 index 00000000..5e210f27 --- /dev/null +++ b/S1/ZZZJ_#12/maxunpool2d_torch.py @@ -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)] \ No newline at end of file diff --git a/S1/ZZZJ_#12/prompt.txt b/S1/ZZZJ_#12/prompt.txt new file mode 100644 index 00000000..98216716 --- /dev/null +++ b/S1/ZZZJ_#12/prompt.txt @@ -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)] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#12/run_code.py b/S1/ZZZJ_#12/run_code.py new file mode 100644 index 00000000..398fb46b --- /dev/null +++ b/S1/ZZZJ_#12/run_code.py @@ -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() \ No newline at end of file