From a3f8abc65325cbc7c908fa07c333c54a01e987d1 Mon Sep 17 00:00:00 2001 From: uucoco Date: Thu, 13 Nov 2025 20:50:33 +0800 Subject: [PATCH] finish HellingerDistance #6 --- S1/uucoco_#6/HellingerDistance_cuda.py | 234 ++++++++++++++++++++++++ S1/uucoco_#6/HellingerDistance_torch.py | 45 +++++ S1/uucoco_#6/prompt.txt | 96 ++++++++++ S1/uucoco_#6/run_code.py | 78 ++++++++ 4 files changed, 453 insertions(+) create mode 100644 S1/uucoco_#6/HellingerDistance_cuda.py create mode 100644 S1/uucoco_#6/HellingerDistance_torch.py create mode 100644 S1/uucoco_#6/prompt.txt create mode 100644 S1/uucoco_#6/run_code.py diff --git a/S1/uucoco_#6/HellingerDistance_cuda.py b/S1/uucoco_#6/HellingerDistance_cuda.py new file mode 100644 index 0000000..8b6d66e --- /dev/null +++ b/S1/uucoco_#6/HellingerDistance_cuda.py @@ -0,0 +1,234 @@ +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-6 + +assert (C * H * W) % 4 == 0, "Instance size (C*H*W) must be a multiple of 4" + + +class ModelNew(nn.Module): + + def __init__(self): + super().__init__() + self.block_size = 512 + self.eps = EPS + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + #include + + void hellinger_sum_cuda( + torch::Tensor x, + torch::Tensor y, + torch::Tensor out, + float eps, + int N, + int D); + """ + + cuda_source = f""" + #include + #include + + #define BLOCK_SIZE {self.block_size} + #define WARP_SIZE 32 + #define ILP 4 // 每个线程处理 4 个 float4 (16个 float) + + // Warp 归约 + __inline__ __device__ float warp_reduce_sum(float val) {{ + #pragma unroll + for (int offset = 16; offset > 0; offset /= 2) {{ + val += __shfl_down_sync(0xffffffff, val, offset); + }} + return val; + }} + + + __global__ __launch_bounds__(BLOCK_SIZE) + void hellinger_split_kernel( + const float* __restrict__ x, + const float* __restrict__ y, + float* __restrict__ out, + float eps, + int D_vec_total // D / 4 + ) {{ + // 1. 任务映射: Grid(Split, Batch) + const int n_idx = blockIdx.y; // Batch Index + const int split_idx = blockIdx.x; // Split Index + const int num_splits = gridDim.x; + + // 2. 计算分块范围 + 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; + + // 3. 指针设置 + 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; + + // 4. 累加器 + float sum[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); + + hellinger_split_kernel<<>>( + x.data_ptr(), + y.data_ptr(), + out.data_ptr(), + eps, + D_vec + ); + }} + """ + + self.op = load_inline( + name='hellinger_cuda_opt_v1', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['hellinger_sum_cuda'], + extra_cuda_cflags=[ + '-O3', + '--use_fast_math', + '-Xptxas=-v' + ], + verbose=False + ) + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + if not x.is_contiguous(): x = x.contiguous() + if not y.is_contiguous(): y = y.contiguous() + + N, C, H, W = x.size() + D = C * H * W + + out = torch.zeros(N, device=x.device, dtype=torch.float32) + + self.op.hellinger_sum_cuda( + x, + y, + out, + self.eps, + N, + D + ) + + return torch.sqrt(out + self.eps) * 0.70710678 \ No newline at end of file diff --git a/S1/uucoco_#6/HellingerDistance_torch.py b/S1/uucoco_#6/HellingerDistance_torch.py new file mode 100644 index 0000000..15bae45 --- /dev/null +++ b/S1/uucoco_#6/HellingerDistance_torch.py @@ -0,0 +1,45 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +N, C, H, W = 32, 64, 56, 56 +EPS = 1e-6 + + +class HellingerDistance(nn.Module): + + def __init__(self, eps=1e-6): + super().__init__() + self.eps = eps + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + x = torch.relu(x) + y = torch.relu(y) + + sqrt_x = torch.sqrt(x + self.eps) + sqrt_y = torch.sqrt(y + self.eps) + + diff_sq = torch.square(sqrt_x - sqrt_y) + + sum_sq = torch.sum(diff_sq, dim=[1, 2, 3]) + + return torch.sqrt(sum_sq + self.eps) / 1.41421356 # 1/sqrt(2) + + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.op = HellingerDistance(EPS) + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return self.op(x, y) + + +def get_inputs(): + x = torch.rand(N, C, H, W, dtype=torch.float32) + y = torch.rand(N, C, H, W, dtype=torch.float32) + return [x, y] + + +def get_init_inputs(): + return [] diff --git a/S1/uucoco_#6/prompt.txt b/S1/uucoco_#6/prompt.txt new file mode 100644 index 0000000..e52b2c9 --- /dev/null +++ b/S1/uucoco_#6/prompt.txt @@ -0,0 +1,96 @@ +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. + +Technologies Used : + +PyTorch: Deep learning framework + +CUDA: GPU acceleration for parallel computing + +C++/CUDA C++: High-performance kernel programming + +Inline C++/CUDA Extension (torch.utils.cpp_extension.load_inline): Just-In-Time (JIT) compilation of custom operators + +Hellinger Distance: Statistical measure for similarity between probability distributions + +Vectorized Memory Access (float4): Uses 128-bit wide loads (4 floats) to improve memory bandwidth utilization + +Instruction-Level Parallelism (ILP): Processes multiple float4 elements per loop iteration to hide instruction latency + +Warp-Level Primitives: Uses __shfl_down_sync for efficient intra-warp reduction + +Two-Stage Parallel Reduction: Combines warp-level reduction with shared memory and block-level reduction + +Grid-Stride Loops with Boundary Checks: Handles data of arbitrary size safely + +Constant Memory/__ldg: Uses read-only data cache for improved memory access patterns + +Atomic Operations (atomicAdd): Safely accumulates results from multiple thread blocks + +Multi-Kernel Launch Configuration: Dynamically calculates grid dimensions based on GPU SM count and data size + +Fast Math Operations: Uses sqrtf with --use_fast_math compiler flag + +Memory Coalescing: Optimized memory access patterns through contiguous tensor layout + +Tensor Contiguity Enforcement: Ensures optimal memory layout in PyTorch wrapper + +Mathematical Optimization: Pre-computes scaling factor (0.70710678 = 1/√2) for final normalization + +Numerical Stability: Adds epsilon (eps) to prevent numerical underflow in square root operations + +Pointer Chasing Loop: Efficient main loop with ILP-unrolled memory access patterns + +Tail Processing: Handles remaining elements after main vectorized loop + +Semi-Synchronous Reduction: Reduces atomic operation overhead through warp-level aggregation + +Device Query API: Uses cudaGetDevice and cudaDeviceGetAttribute for optimal kernel configuration + + +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 +import torch.nn.functional as F + +N, C, H, W = 32, 64, 56, 56 +EPS = 1e-6 + + +class HellingerDistance(nn.Module): + + def __init__(self, eps=1e-6): + super().__init__() + self.eps = eps + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + x = torch.relu(x) + y = torch.relu(y) + + sqrt_x = torch.sqrt(x + self.eps) + sqrt_y = torch.sqrt(y + self.eps) + + diff_sq = torch.square(sqrt_x - sqrt_y) + + sum_sq = torch.sum(diff_sq, dim=[1, 2, 3]) + + return torch.sqrt(sum_sq + self.eps) / 1.41421356 # 1/sqrt(2) + + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.op = HellingerDistance(EPS) + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return self.op(x, y) + + +def get_inputs(): + x = torch.rand(N, C, H, W, dtype=torch.float32) + y = torch.rand(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/uucoco_#6/run_code.py b/S1/uucoco_#6/run_code.py new file mode 100644 index 0000000..0fc6b92 --- /dev/null +++ b/S1/uucoco_#6/run_code.py @@ -0,0 +1,78 @@ +import torch +import time +from HellingerDistance_torch import Model, get_inputs, get_init_inputs +from HellingerDistance_cuda import ModelNew + +def run_benchmark(): + if not torch.cuda.is_available(): + print("CUDA 不可用") + return + + device = torch.device("cuda") + + # 准备输入数据 + inputs = [x.cuda(device=device) for x in get_inputs()] + init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()] + + # 初始化模型 + torch_model = Model(*init_inputs).cuda() + cuda_model = ModelNew(*init_inputs).cuda() + + torch_model.eval() + cuda_model.eval() + + print("-------------------- 精度对齐验证 --------------------") + with torch.no_grad(): + # 预热GPU + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 正式测试 + output_torch = torch_model(*inputs) + output_cuda = cuda_model(*inputs) + + # 精度验证 + abs_diff = torch.abs(output_torch - output_cuda) + max_diff = torch.max(abs_diff).item() + mean_diff = torch.mean(abs_diff).item() + + if max_diff < 1e-4 and mean_diff < 1e-5: + print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}") + precision_flag = True + else: + print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}") + precision_flag = False + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 100 + + # 预热GPU + for _ in range(10): + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 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内置Swish平均执行时间: {torch_time:.6f}秒") + print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}秒") + speedup = torch_time / cuda_time if cuda_time > 0 else 0 + print(f"加速比 (Speedup): {speedup:.2f}x") + + return precision_flag, speedup + +if __name__ == "__main__": + precision_flag, speedup = run_benchmark() \ No newline at end of file