diff --git a/S1/gsd123_#147/hellinger_bhattacharyya_cuda.py b/S1/gsd123_#147/hellinger_bhattacharyya_cuda.py new file mode 100644 index 0000000..cbab95d --- /dev/null +++ b/S1/gsd123_#147/hellinger_bhattacharyya_cuda.py @@ -0,0 +1,98 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include +#include + +__inline__ __device__ float warp_reduce(float val) { + for (int offset = 16; offset > 0; offset /= 2) + val += __shfl_down_sync(0xffffffff, val, offset); + return val; +} + +__global__ void hellinger_bhattacharyya_kernel( + const float* __restrict__ x, + const float* __restrict__ target, + float* __restrict__ y, + int batch_size, + int width) +{ + int row = blockIdx.x; + int tid = threadIdx.x; + + if (row >= batch_size) return; + + const float* row_x = x + row * width; + + float sum_sq_diff = 0.0f; + + for (int i = tid; i < width; i += blockDim.x) { + float val_x = sqrtf(fabsf(row_x[i])); + float val_t = sqrtf(fabsf(target[i])); + float diff = val_x - val_t; + sum_sq_diff += diff * diff; + } + + sum_sq_diff = warp_reduce(sum_sq_diff); + + static __shared__ float shared_mem[32]; + int lane = tid % 32; + int wid = tid / 32; + + if (lane == 0) shared_mem[wid] = sum_sq_diff; + __syncthreads(); + + sum_sq_diff = (tid < blockDim.x / 32) ? shared_mem[lane] : 0.0f; + if (wid == 0) sum_sq_diff = warp_reduce(sum_sq_diff); + + if (tid == 0) { + float h = sqrtf(sum_sq_diff) * 0.70710678f; // 1/sqrt(2) + float h2 = h * h; + float val = 1.0f - h2; + y[row] = -logf(fabsf(val) + 1e-6f); + } +} + +torch::Tensor launch_hellinger_bhattacharyya(torch::Tensor x, torch::Tensor target) { + auto batch_size = x.size(0); + auto width = x.size(1); + auto y = torch::empty({batch_size}, x.options()); + + const int threads = 256; + const int blocks = batch_size; + + hellinger_bhattacharyya_kernel<<>>( + x.data_ptr(), + target.data_ptr(), + y.data_ptr(), + batch_size, + width + ); + return y; +} +""" + +cpp_source = """ +torch::Tensor launch_hellinger_bhattacharyya(torch::Tensor x, torch::Tensor target); +""" + +hellinger_bhattacharyya_module = load_inline( + name='hellinger_bhattacharyya_op', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['launch_hellinger_bhattacharyya'], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self, target): + super(ModelNew, self).__init__() + self.target = nn.Parameter(target) + self.op = hellinger_bhattacharyya_module + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.op.launch_hellinger_bhattacharyya(x.contiguous(), self.target.contiguous()) \ No newline at end of file diff --git a/S1/gsd123_#147/hellinger_bhattacharyya_torch.py b/S1/gsd123_#147/hellinger_bhattacharyya_torch.py new file mode 100644 index 0000000..0b3567e --- /dev/null +++ b/S1/gsd123_#147/hellinger_bhattacharyya_torch.py @@ -0,0 +1,25 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, target): + super(Model, self).__init__() + self.target = nn.Parameter(target) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + sqrt_x = torch.sqrt(torch.abs(x)) + sqrt_target = torch.sqrt(torch.abs(self.target)) + euclidean_dist = torch.sqrt(torch.sum((sqrt_x - sqrt_target) ** 2, dim=-1)) + hellinger_dist = euclidean_dist / 1.41421356 + return -torch.log(torch.abs(1.0 - hellinger_dist ** 2) + 1e-6) + +batch_size = 128 +input_dim = 1024 + +def get_inputs(): + x = torch.abs(torch.randn(batch_size, input_dim)) + return [x] + +def get_init_inputs(): + target = torch.abs(torch.randn(input_dim)) + return [target] \ No newline at end of file diff --git a/S1/gsd123_#147/prompt.txt b/S1/gsd123_#147/prompt.txt new file mode 100644 index 0000000..3445bc8 --- /dev/null +++ b/S1/gsd123_#147/prompt.txt @@ -0,0 +1,50 @@ +You write custom CUDA kernels to replace the pytorch operators in the given GeGLU 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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. +CUDA C++ kernel for Hellinger‑Bhattacharyya composite distance + +Element‑wise square‑root differences: (√|x[i]| – √|target[i]|)² + +Two‑level parallel reduction: warp‑level (__shfl_down_sync) + shared‑memory reduction + +Hellinger distance: √∑diff² × 1/√2 (scale factor 0.70710678) + +Bhattacharyya coefficient approximation: 1 – H² (distance‑to‑similarity conversion) + +Negative logarithm of the coefficient to obtain divergence, with epsilon for stability + +Grid‑stride loops for coalesced memory access across feature dimension + +Block‑per‑sample processing with 256 threads per block + +PyTorch inline C++/CUDA extension via load_inline + + + + +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 + +class Model(nn.Module): + def __init__(self, target): + super(Model, self).__init__() + self.target = nn.Parameter(target) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + sqrt_x = torch.sqrt(torch.abs(x)) + sqrt_target = torch.sqrt(torch.abs(self.target)) + euclidean_dist = torch.sqrt(torch.sum((sqrt_x - sqrt_target) ** 2, dim=-1)) + hellinger_dist = euclidean_dist / 1.41421356 + return -torch.log(torch.abs(1.0 - hellinger_dist ** 2) + 1e-6) + +batch_size = 128 +input_dim = 1024 + +def get_inputs(): + x = torch.abs(torch.randn(batch_size, input_dim)) + return [x] + +def get_init_inputs(): + target = torch.abs(torch.randn(input_dim)) + return [target] \ No newline at end of file diff --git a/S1/gsd123_#147/run_code.py b/S1/gsd123_#147/run_code.py new file mode 100644 index 0000000..86b133d --- /dev/null +++ b/S1/gsd123_#147/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from hellinger_bhattacharyya_torch import Model, get_inputs, get_init_inputs +from hellinger_bhattacharyya_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