diff --git a/S1/41/PearsonCorrelation_cuda.py b/S1/41/PearsonCorrelation_cuda.py new file mode 100644 index 0000000..e8973a9 --- /dev/null +++ b/S1/41/PearsonCorrelation_cuda.py @@ -0,0 +1,286 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +N, C, H, W = 32, 64, 56, 56 +EPS = 1e-8 + +assert (C * H * W) % 4 == 0 + + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self.block_size = 512 + self.eps = EPS + self.register_buffer('temp_buffer', torch.zeros((N, 5), dtype=torch.float32)) + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + #include + + void pearson_sum_cuda( + torch::Tensor x, + torch::Tensor y, + torch::Tensor temp_buffer, + int N, + int D); + """ + + cuda_source = f""" + #include + #include + + #define BLOCK_SIZE {self.block_size} + #define WARP_SIZE 32 + #define ILP 4 + + __inline__ __device__ float warp_reduce_sum(float val) {{ + #pragma unroll + for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {{ + val += __shfl_down_sync(0xffffffff, val, offset); + }} + return val; + }} + + __global__ __launch_bounds__(BLOCK_SIZE) + void pearson_split_kernel( + const float* __restrict__ x, + const float* __restrict__ y, + float* __restrict__ temp_buffer, + int D_vec_total + ) {{ + const int n_idx = blockIdx.y; + const int split_idx = blockIdx.x; + const int num_splits = gridDim.x; + + const int chunk_size = (D_vec_total + num_splits - 1) / num_splits; + const int start_idx = split_idx * chunk_size; + const int end_idx = min(start_idx + chunk_size, D_vec_total); + + if (start_idx >= D_vec_total) return; + + const int64_t batch_offset = (int64_t)n_idx * D_vec_total * 4; + + const float4* curr_x = reinterpret_cast(x + batch_offset) + start_idx + threadIdx.x; + const float4* curr_y = reinterpret_cast(y + batch_offset) + start_idx + threadIdx.x; + const float4* end_ptr = reinterpret_cast(x + batch_offset) + end_idx; + + float sum_x[ILP]; + float sum_y[ILP]; + float sum_xx[ILP]; + float sum_yy[ILP]; + float sum_xy[ILP]; + + #pragma unroll + for (int k=0; k max_splits) splits = max_splits; + if (splits < 1) splits = 1; + if (splits > 512) splits = 512; + + dim3 blocks(splits, N); + dim3 threads(BLOCK_SIZE); + + pearson_split_kernel<<>>( + x.data_ptr(), + y.data_ptr(), + temp_buffer.data_ptr(), + D_vec + ); + }} + """ + + self.op = load_inline( + name='pearson_cuda_opt_v1', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['pearson_sum_cuda'], + extra_cuda_cflags=[ + '-O3', + '--use_fast_math', + '-Xptxas=-v' + ], + verbose=False + ) + + def forward(self, x, y): + if not x.is_contiguous(): x = x.contiguous() + if not y.is_contiguous(): y = y.contiguous() + + if not x.is_cuda: x = x.cuda() + if not y.is_cuda: y = y.cuda() + + N, C, H, W = x.size() + D = C * H * W + + self.temp_buffer.zero_() + + self.op.pearson_sum_cuda( + x, + y, + self.temp_buffer, + N, + D + ) + + sum_x = self.temp_buffer[:, 0] + sum_y = self.temp_buffer[:, 1] + sum_xx = self.temp_buffer[:, 2] + sum_yy = self.temp_buffer[:, 3] + sum_xy = self.temp_buffer[:, 4] + + mean_x = sum_x / D + mean_y = sum_y / D + + numerator = sum_xy - D * mean_x * mean_y + var_x = sum_xx - D * mean_x * mean_x + var_y = sum_yy - D * mean_y * mean_y + + return numerator / (torch.sqrt(var_x * var_y) + self.eps) \ No newline at end of file diff --git a/S1/41/PearsonCorrelation_torch.py b/S1/41/PearsonCorrelation_torch.py new file mode 100644 index 0000000..9bc0adf --- /dev/null +++ b/S1/41/PearsonCorrelation_torch.py @@ -0,0 +1,43 @@ +import torch +import torch.nn as nn + +N, C, H, W = 32, 64, 56, 56 +EPS = 1e-8 + +class PearsonCorrelation(nn.Module): + def __init__(self, eps=1e-8): + super().__init__() + self.eps = eps + + def forward(self, x, y): + x_flat = x.view(x.size(0), -1) + y_flat = y.view(y.size(0), -1) + + x_mean = x_flat.mean(dim=1, keepdim=True) + y_mean = y_flat.mean(dim=1, keepdim=True) + + x_centered = x_flat - x_mean + y_centered = y_flat - y_mean + + cov = (x_centered * y_centered).sum(dim=1) + x_var = (x_centered ** 2).sum(dim=1) + y_var = (y_centered ** 2).sum(dim=1) + + denom = torch.sqrt(x_var * y_var) + return cov / (denom + self.eps) + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.op = PearsonCorrelation(EPS) + + def forward(self, x, y): + return self.op(x, y) + +def get_inputs(): + x = torch.randn(N, C, H, W, dtype=torch.float32) + y = torch.randn(N, C, H, W, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/41/prompt.txt b/S1/41/prompt.txt new file mode 100644 index 0000000..9c5150f --- /dev/null +++ b/S1/41/prompt.txt @@ -0,0 +1,57 @@ +You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm 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 normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. + +This document presents a CUDA-accelerated PyTorch module for computing Pearson correlation coefficients between two input tensors in batches. The implementation features a highly optimized GPU kernel that leverages several advanced techniques for maximum performance. +Key technical features include: +Memory Access Optimization: Uses vectorized float4 loads to maximize memory bandwidth utilization and employs Instruction-Level Parallelism (ILP=4) to hide memory latency. +Hierarchical Reduction: Implements a two-stage reduction strategy with warp-level reduction using __shfl_down_syncfollowed by block-level reduction via shared memory. +Dynamic Kernel Configuration: Automatically determines optimal kernel configuration based on GPU specifications (SM count) and problem size, splitting work across multiple blocks to maximize occupancy. +Numerical Stability: Incorporates epsilon term to prevent division by zero when computing the final correlation coefficient. +The kernel computes five statistical moments (sum_x, sum_y, sum_xx, sum_yy, sum_xy) in a single pass, then calculates the Pearson correlation using the formula: +cov_xy / sqrt(var_x * var_y)where cov_xy = sum_xy - D*mean_x*mean_yand var_x = sum_xx - D*mean_x*mean_x. +The module handles 4D tensors (NCHW format) and is particularly efficient for large channel dimensions where the vectorized approach provides significant speedups over naive implementations. + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: +import torch +import torch.nn as nn + +N, C, H, W = 32, 64, 56, 56 +EPS = 1e-8 + +class PearsonCorrelation(nn.Module): + def __init__(self, eps=1e-8): + super().__init__() + self.eps = eps + + def forward(self, x, y): + x_flat = x.view(x.size(0), -1) + y_flat = y.view(y.size(0), -1) + + x_mean = x_flat.mean(dim=1, keepdim=True) + y_mean = y_flat.mean(dim=1, keepdim=True) + + x_centered = x_flat - x_mean + y_centered = y_flat - y_mean + + cov = (x_centered * y_centered).sum(dim=1) + x_var = (x_centered ** 2).sum(dim=1) + y_var = (y_centered ** 2).sum(dim=1) + + denom = torch.sqrt(x_var * y_var) + return cov / (denom + self.eps) + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.op = PearsonCorrelation(EPS) + + def forward(self, x, y): + return self.op(x, y) + +def get_inputs(): + x = torch.randn(N, C, H, W, dtype=torch.float32) + y = torch.randn(N, C, H, W, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/41/run_code.py b/S1/41/run_code.py new file mode 100644 index 0000000..7e73cfb --- /dev/null +++ b/S1/41/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from PearsonCorrelation_torch import Model, get_inputs, get_init_inputs +from PearsonCorrelation_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