diff --git a/S1/ZZZJ_#115/gaussian_filter_3d_cuda.py b/S1/ZZZJ_#115/gaussian_filter_3d_cuda.py new file mode 100644 index 0000000..231cdd9 --- /dev/null +++ b/S1/ZZZJ_#115/gaussian_filter_3d_cuda.py @@ -0,0 +1,147 @@ +import torch +import math +from torch.utils.cpp_extension import load_inline + +gaussian_3d_source = """ +#include +#include + +__global__ void gaussian_3d_kernel( + const float* __restrict__ input, + const float* __restrict__ weight, // [K, K, K] flattened + float* __restrict__ output, + int D, int H, int W, + int kernel_size, + int padding, + long spatial_size, // H * W + long volume_size // D * H * W +) { + + + int nc_idx = blockIdx.z; + int d = blockIdx.y; + int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x; + + if (spatial_idx < spatial_size) { + // Decode spatial coords + int h = spatial_idx / W; + int w = spatial_idx % W; + + // Base pointers for this volume + const float* vol_in = input + nc_idx * volume_size; + float* vol_out = output + nc_idx * volume_size; + + float sum = 0.0f; + int k_center = kernel_size / 2; + + // 3D Convolution Loop + // Unroll logic for 3x3x3 (common case) + #pragma unroll + for (int kz = 0; kz < kernel_size; ++kz) { + int in_d = d + kz - padding; + + // Depth Boundary Check + if (in_d >= 0 && in_d < D) { + long d_offset = (long)in_d * spatial_size; + + #pragma unroll + for (int ky = 0; ky < kernel_size; ++ky) { + int in_h = h + ky - padding; + + // Height Boundary Check + if (in_h >= 0 && in_h < H) { + long h_offset = (long)in_h * W; + + #pragma unroll + for (int kx = 0; kx < kernel_size; ++kx) { + int in_w = w + kx - padding; + + // Width Boundary Check + if (in_w >= 0 && in_w < W) { + // Read Input (Use __ldg for Texture Cache optimization) + float val = __ldg(&vol_in[d_offset + h_offset + in_w]); + + // Read Weight + int w_idx = kz * (kernel_size * kernel_size) + ky * kernel_size + kx; + float w_val = weight[w_idx]; + + sum += val * w_val; + } + } + } + } + } + } + + // Write Output + long out_idx = (long)d * spatial_size + spatial_idx; + vol_out[out_idx] = sum; + } +} + +torch::Tensor gaussian_filter_3d_cuda(torch::Tensor input, torch::Tensor weight, int kernel_size) { + int N = input.size(0); + int C = input.size(1); + int D = input.size(2); + int H = input.size(3); + int W = input.size(4); + + // Output + auto output = torch::empty_like(input); + + long spatial_size = H * W; + long volume_size = D * spatial_size; + int nc = N * C; + int padding = kernel_size / 2; + + // Config + const int block = 256; + dim3 grid((spatial_size + block - 1) / block, D, nc); + + gaussian_3d_kernel<<>>( + input.data_ptr(), + weight.data_ptr(), + output.data_ptr(), + D, H, W, + kernel_size, + padding, + spatial_size, + volume_size + ); + + return output; +} +""" + +cpp_source = "torch::Tensor gaussian_filter_3d_cuda(torch::Tensor input, torch::Tensor weight, int kernel_size);" + +gaussian_3d_module = load_inline( + name="gaussian_filter_3d_extension", + cpp_sources=cpp_source, + cuda_sources=gaussian_3d_source, + functions=["gaussian_filter_3d_cuda"], + verbose=True, + with_cuda=True +) + +class ModelNew(torch.nn.Module): + def __init__(self): + super(ModelNew, self).__init__() + self.kernel_size = 3 + self.sigma = 1.0 + self.channels = 32 + + + k = self.kernel_size + coords = torch.arange(k).float() - k // 2 + grid_z, grid_y, grid_x = torch.meshgrid(coords, coords, coords, indexing='ij') + + dist_sq = grid_x**2 + grid_y**2 + grid_z**2 + gaussian_kernel = torch.exp(-dist_sq / (2.0 * self.sigma**2)) + gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel) + + self.weight_single = gaussian_kernel.cuda() + self.cuda_op = gaussian_3d_module + + def forward(self, x): + return self.cuda_op.gaussian_filter_3d_cuda(x.contiguous(), self.weight_single, self.kernel_size) \ No newline at end of file diff --git a/S1/ZZZJ_#115/gaussian_filter_3d_torch.py b/S1/ZZZJ_#115/gaussian_filter_3d_torch.py new file mode 100644 index 0000000..e706169 --- /dev/null +++ b/S1/ZZZJ_#115/gaussian_filter_3d_torch.py @@ -0,0 +1,48 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + +torch.backends.cuda.matmul.allow_tf32 = False + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + self.kernel_size = 3 + self.sigma = 1.0 + self.channels = 32 + + + k = self.kernel_size + + coords = torch.arange(k).float() - k // 2 + + grid_z, grid_y, grid_x = torch.meshgrid(coords, coords, coords, indexing='ij') + + dist_sq = grid_x**2 + grid_y**2 + grid_z**2 + gaussian_kernel = torch.exp(-dist_sq / (2.0 * self.sigma**2)) + gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel) + + + self.weight = gaussian_kernel.view(1, 1, k, k, k).repeat(self.channels, 1, 1, 1, 1).cuda() + self.padding = k // 2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + x: [N, C, D, H, W] + Output: [N, C, D, H, W] + """ + return F.conv3d(x, self.weight, padding=self.padding, groups=x.shape[1]) + +N = 4 +C = 32 +D = 64 +H = 128 +W = 128 + +def get_inputs(): + x = torch.randint(0, 10, (N, C, D, H, W), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#115/prompt.txt b/S1/ZZZJ_#115/prompt.txt new file mode 100644 index 0000000..f19a90c --- /dev/null +++ b/S1/ZZZJ_#115/prompt.txt @@ -0,0 +1,56 @@ +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 +import torch.nn.functional as F +import math + +torch.backends.cuda.matmul.allow_tf32 = False + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + self.kernel_size = 3 + self.sigma = 1.0 + self.channels = 32 + + + k = self.kernel_size + + coords = torch.arange(k).float() - k // 2 + + grid_z, grid_y, grid_x = torch.meshgrid(coords, coords, coords, indexing='ij') + + dist_sq = grid_x**2 + grid_y**2 + grid_z**2 + gaussian_kernel = torch.exp(-dist_sq / (2.0 * self.sigma**2)) + gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel) + + + self.weight = gaussian_kernel.view(1, 1, k, k, k).repeat(self.channels, 1, 1, 1, 1).cuda() + self.padding = k // 2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + x: [N, C, D, H, W] + Output: [N, C, D, H, W] + """ + return F.conv3d(x, self.weight, padding=self.padding, groups=x.shape[1]) + +N = 4 +C = 32 +D = 64 +H = 128 +W = 128 + +def get_inputs(): + x = torch.randint(0, 10, (N, C, D, H, W), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#115/run_code.py b/S1/ZZZJ_#115/run_code.py new file mode 100644 index 0000000..55f89f0 --- /dev/null +++ b/S1/ZZZJ_#115/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from gaussian_filter_3d_torch import Model,get_inputs,get_init_inputs +from gaussian_filter_3d_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