From 73abfbc7bd41905e470ac6be9ce750fe9a022ef3 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 9 Dec 2025 15:52:43 +0800 Subject: [PATCH] fixes Maxpool3d #7 --- S1/ZZZJ_#7/maxpool3d_cuda.py | 187 ++++++++++++++++++++++++++++++++++ S1/ZZZJ_#7/maxpool3d_torch.py | 41 ++++++++ S1/ZZZJ_#7/prompt.txt | 49 +++++++++ S1/ZZZJ_#7/run_code.py | 74 ++++++++++++++ 4 files changed, 351 insertions(+) create mode 100644 S1/ZZZJ_#7/maxpool3d_cuda.py create mode 100644 S1/ZZZJ_#7/maxpool3d_torch.py create mode 100644 S1/ZZZJ_#7/prompt.txt create mode 100644 S1/ZZZJ_#7/run_code.py diff --git a/S1/ZZZJ_#7/maxpool3d_cuda.py b/S1/ZZZJ_#7/maxpool3d_cuda.py new file mode 100644 index 0000000..d94fb3a --- /dev/null +++ b/S1/ZZZJ_#7/maxpool3d_cuda.py @@ -0,0 +1,187 @@ +# maxpool3d_cuda.py +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline +import math + +from maxpool3d_torch import BATCH_SIZE, CHANNELS, D_IN, H_IN, W_IN, D_OUT, H_OUT, W_OUT, KERNEL_SIZE, STRIDE + + +K_D, K_H, K_W = KERNEL_SIZE +S_D, S_H, S_W = STRIDE + +BLOCK_SIZE = 256 +VEC_SIZE = 4 + +class ModelNew(nn.Module): + + def __init__(self, kernel_size, stride): + super().__init__() + self.k_d, self.k_h, self.k_w = kernel_size + self.s_d, self.s_h, self.s_w = stride + self.d_in = D_IN + self.h_in = H_IN + self.w_in = W_IN + self.d_out = D_OUT + self.h_out = H_OUT + self.w_out = W_OUT + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + + cpp_header = """ + #include + + torch::Tensor maxpool3d_forward_cuda( + torch::Tensor input, int D_in, int H_in, int W_in, int D_out, int H_out, int W_out, + int K_D, int K_H, int K_W, int S_D, int S_H, int S_W + ); + """ + + cuda_source = f""" + #include + #include + #include + #include // For -FLT_MAX + + #define BLOCK_SIZE {BLOCK_SIZE} + #define VEC_SIZE {VEC_SIZE} + + __global__ void maxpool3d_kernel( + const float* __restrict__ input_data, + float* __restrict__ output_data, + int N, int C, int D_in, int H_in, int W_in, int D_out, int H_out, int W_out, + int K_D, int K_H, int K_W, int S_D, int S_H, int S_W + ) {{ + + const int N_C_D_H_W_out = N * C * D_out * H_out * W_out; + const int tid = blockIdx.x * blockDim.x + threadIdx.x; + const int grid_stride = gridDim.x * blockDim.x; + + const int CDHW_in = C * D_in * H_in * W_in; + const int DHW_in = D_in * H_in * W_in; + const int HW_in = H_in * W_in; + + for (int idx = tid; idx < N_C_D_H_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 d_h_w_out = h_w_out / H_out; + + const int d_out = d_h_w_out % D_out; + const int n_c = d_h_w_out / D_out; + + const int n_idx = n_c / C; + const int c_idx = n_c % C; + + const int d_in_start = d_out * S_D; + const int h_in_start = h_out * S_H; + const int w_in_start = w_out * S_W; + + + float thread_max = -FLT_MAX; + + const int base_offset = (n_idx * CDHW_in) + (c_idx * DHW_in); + + + for (int k_d = 0; k_d < K_D; k_d++) {{ + for (int k_h = 0; k_h < K_H; k_h++) {{ + + + const int w_start_abs_offset = base_offset + ((d_in_start + k_d) * HW_in) + ((h_in_start + k_h) * W_in) + w_in_start; + + + int w_current = 0; + int w_len = K_W; + + while (w_current < w_len && ((w_in_start + w_current) % VEC_SIZE) != 0) {{ + thread_max = std::max(thread_max, input_data[w_start_abs_offset + w_current]); + w_current++; + }} + + const int w_vector_len = w_len - w_current; + const int num_vectors = w_vector_len / VEC_SIZE; + + if (num_vectors > 0) {{ + const float4* vec_ptr = (const float4*)(input_data + w_start_abs_offset + w_current); + + for (int v = 0; v < num_vectors; v++) {{ + float4 val4 = vec_ptr[v]; + thread_max = std::max(thread_max, val4.x); + thread_max = std::max(thread_max, val4.y); + thread_max = std::max(thread_max, val4.z); + thread_max = std::max(thread_max, val4.w); + }} + w_current += num_vectors * VEC_SIZE; + }} + + while (w_current < w_len) {{ + thread_max = std::max(thread_max, input_data[w_start_abs_offset + w_current]); + w_current++; + }} + + + }} + }} + + + output_data[idx] = thread_max; + }} + }} + + + torch::Tensor maxpool3d_forward_cuda( + torch::Tensor input, int D_in, int H_in, int W_in, int D_out, int H_out, int W_out, + int K_D, int K_H, int K_W, int S_D, int S_H, int S_W + ) {{ + TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor"); + input = input.contiguous(); + + const int N = input.size(0); + const int C = input.size(1); + + const int N_elements_out = N * C * D_out * H_out * W_out; + + auto output = torch::empty({{N, C, D_out, H_out, W_out}}, input.options()); + + dim3 block_dim(BLOCK_SIZE); + const int grid_size = (N_elements_out + BLOCK_SIZE - 1) / BLOCK_SIZE; + dim3 grid_dim(grid_size); + + maxpool3d_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + N, C, D_in, H_in, W_in, D_out, H_out, W_out, + K_D, K_H, K_W, S_D, S_H, S_W + ); + + return output; + }} + """ + + self.maxpool_op = load_inline( + name="maxpool3d_op", + cpp_sources=cpp_header, + cuda_sources=cuda_source, + functions=["maxpool3d_forward_cuda"], + verbose=False + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.maxpool_op.maxpool3d_forward_cuda( + x.contiguous(), + self.d_in, + self.h_in, + self.w_in, + self.d_out, + self.h_out, + self.w_out, + self.k_d, + self.k_h, + self.k_w, + self.s_d, + self.s_h, + self.s_w + ) \ No newline at end of file diff --git a/S1/ZZZJ_#7/maxpool3d_torch.py b/S1/ZZZJ_#7/maxpool3d_torch.py new file mode 100644 index 0000000..a816703 --- /dev/null +++ b/S1/ZZZJ_#7/maxpool3d_torch.py @@ -0,0 +1,41 @@ +# maxpool3d_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + +BATCH_SIZE = 4 +CHANNELS = 64 +D_IN, H_IN, W_IN = 32, 32, 32 +KERNEL_SIZE = (3, 3, 3) +STRIDE = (2, 2, 2) + +K_D, K_H, K_W = KERNEL_SIZE +S_D, S_H, S_W = STRIDE + + +D_OUT = math.floor((D_IN - K_D) / S_D) + 1 +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): + super().__init__() + self.max_pool = nn.MaxPool3d(kernel_size=kernel_size, stride=stride) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output= self.max_pool(x) + return output + + +def get_inputs(): + + x = torch.randn(BATCH_SIZE, CHANNELS, D_IN, H_IN, W_IN, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [KERNEL_SIZE, STRIDE] \ No newline at end of file diff --git a/S1/ZZZJ_#7/prompt.txt b/S1/ZZZJ_#7/prompt.txt new file mode 100644 index 0000000..497088a --- /dev/null +++ b/S1/ZZZJ_#7/prompt.txt @@ -0,0 +1,49 @@ +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 +# maxpool3d_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + +BATCH_SIZE = 4 +CHANNELS = 64 +D_IN, H_IN, W_IN = 32, 32, 32 +KERNEL_SIZE = (3, 3, 3) +STRIDE = (2, 2, 2) + +K_D, K_H, K_W = KERNEL_SIZE +S_D, S_H, S_W = STRIDE + + +D_OUT = math.floor((D_IN - K_D) / S_D) + 1 +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): + super().__init__() + self.max_pool = nn.MaxPool3d(kernel_size=kernel_size, stride=stride) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output= self.max_pool(x) + return output + + +def get_inputs(): + + x = torch.randn(BATCH_SIZE, CHANNELS, D_IN, H_IN, W_IN, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [KERNEL_SIZE, STRIDE] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#7/run_code.py b/S1/ZZZJ_#7/run_code.py new file mode 100644 index 0000000..f9f1cf8 --- /dev/null +++ b/S1/ZZZJ_#7/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from maxpool3d_torch import Model,get_inputs,get_init_inputs +from maxpool3d_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