From fe6263d33da37098fd6c239d37b18f18799e7573 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:08:37 +0800 Subject: [PATCH] finish FDivergenceLoss #87 --- S1/uucoco_#87/FDivergenceLoss_cuda.py | 88 +++++++++++++++++++++++++ S1/uucoco_#87/FDivergenceLoss_torch.py | 30 +++++++++ S1/uucoco_#87/prompt.txt | 90 ++++++++++++++++++++++++++ S1/uucoco_#87/run_code.py | 77 ++++++++++++++++++++++ 4 files changed, 285 insertions(+) create mode 100644 S1/uucoco_#87/FDivergenceLoss_cuda.py create mode 100644 S1/uucoco_#87/FDivergenceLoss_torch.py create mode 100644 S1/uucoco_#87/prompt.txt create mode 100644 S1/uucoco_#87/run_code.py diff --git a/S1/uucoco_#87/FDivergenceLoss_cuda.py b/S1/uucoco_#87/FDivergenceLoss_cuda.py new file mode 100644 index 0000000..d2f3b6c --- /dev/null +++ b/S1/uucoco_#87/FDivergenceLoss_cuda.py @@ -0,0 +1,88 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__global__ void f_divergence_kernel( + const float* __restrict__ p, + const float* __restrict__ q, + float* __restrict__ output, + int n, + float eps +) { + extern __shared__ float sdata[]; + int tid = threadIdx.x; + int idx = blockIdx.x * blockDim.x + threadIdx.x; + + float local_sum = 0.0f; + for (int i = idx; i < n; i += blockDim.x * gridDim.x) { + float p_val = p[i]; + float q_val = q[i]; + float diff = p_val - q_val; + local_sum += (diff * diff) / (q_val + eps); + } + + sdata[tid] = local_sum; + __syncthreads(); + + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if (tid < s) { + sdata[tid] += sdata[tid + s]; + } + __syncthreads(); + } + + if (tid == 0) { + atomicAdd(output, sdata[0]); + } +} + +torch::Tensor f_divergence_cuda(torch::Tensor p, torch::Tensor q, float eps) { + int batch_size = p.size(0); + int num_classes = p.size(1); + int n = batch_size * num_classes; + + auto output = at::zeros({1}, p.options()); + + int threads = 256; + int blocks = 128; + int shared_mem = threads * sizeof(float); + + f_divergence_kernel<<>>( + p.data_ptr(), + q.data_ptr(), + output.data_ptr(), + n, + eps + ); + + return output / batch_size; +} +""" + +cpp_source = """ +torch::Tensor f_divergence_cuda(torch::Tensor p, torch::Tensor q, float eps); +""" + +f_divergence_loss = load_inline( + name="f_divergence_loss", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["f_divergence_cuda"], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self, eps=1e-8): + super(ModelNew, self).__init__() + self.eps = eps + + def forward(self, p, q): + p_prob = F.softmax(p, dim=1) + q_prob = F.softmax(q, dim=1) + return f_divergence_loss.f_divergence_cuda(p_prob, q_prob, self.eps) \ No newline at end of file diff --git a/S1/uucoco_#87/FDivergenceLoss_torch.py b/S1/uucoco_#87/FDivergenceLoss_torch.py new file mode 100644 index 0000000..d6bf996 --- /dev/null +++ b/S1/uucoco_#87/FDivergenceLoss_torch.py @@ -0,0 +1,30 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Model(nn.Module): + def __init__(self, eps=1e-8): + super(Model, self).__init__() + self.eps = eps + + def forward(self, p, q): + p = F.softmax(p, dim=1) + q = F.softmax(q, dim=1) + + divergence = (p - q) ** 2 / (q + self.eps) + return torch.sum(divergence, dim=1).mean() + + +batch_size = 32 +num_classes = 1000 + + +def get_inputs(): + p = torch.randn(batch_size, num_classes, requires_grad=True) + q = torch.randn(batch_size, num_classes) + return [p, q] + + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/uucoco_#87/prompt.txt b/S1/uucoco_#87/prompt.txt new file mode 100644 index 0000000..09569df --- /dev/null +++ b/S1/uucoco_#87/prompt.txt @@ -0,0 +1,90 @@ +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. +Technologies Used in This Code +Core Libraries & Frameworks +PyTorch: Deep learning framework + +CUDA: NVIDIA's parallel computing platform for GPU acceleration + +C++: For high-performance kernel implementation + +PyTorch Specific Components +torch.nn.Module: Base class for neural network modules + +torch.nn.functional.F.softmax: Softmax activation function + +torch.utils.cpp_extension.load_inline: For inline compilation of CUDA/C++ extensions + +PyTorch Tensors: Multi-dimensional arrays with automatic differentiation + +CUDA/C++ Implementation Details +CUDA Kernels: Custom GPU kernel (f_divergence_kernel) + +Parallel Reduction: Tree-based reduction for sum computation + +Shared Memory: Using __shared__ memory for inter-thread communication + +Atomic Operations: atomicAdd for thread-safe global memory updates + +Strided Access Pattern: Grid-stride loop for efficient memory access + +Optimization Techniques +Shared Memory Reduction: Parallel reduction within thread blocks + +Grid-Stride Loops: Efficient handling of arbitrary array sizes + +Numerical Stability: Epsilon (eps) to prevent division by zero + +Memory Coalescing: Optimized memory access patterns + +Statistical/Machine Learning Components +F-Divergence: Statistical distance between two probability distributions + +Chi-square-like metric: Implementation resembling chi-square divergence + +Softmax Normalization: Converting logits to probability distributions + +Batch Processing: Averaging over batch dimension + +Performance Features +GPU Parallelization: Massively parallel computation across data elements + +Fused Operations: Single kernel for complete divergence computation + +Optimized Reduction: Efficient sum reduction using shared memory + + + + +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 + + +class Model(nn.Module): + def __init__(self, eps=1e-8): + super(Model, self).__init__() + self.eps = eps + + def forward(self, p, q): + p = F.softmax(p, dim=1) + q = F.softmax(q, dim=1) + + divergence = (p - q) ** 2 / (q + self.eps) + return torch.sum(divergence, dim=1).mean() + + +batch_size = 32 +num_classes = 1000 + + +def get_inputs(): + p = torch.randn(batch_size, num_classes, requires_grad=True) + q = torch.randn(batch_size, num_classes) + return [p, q] + + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/uucoco_#87/run_code.py b/S1/uucoco_#87/run_code.py new file mode 100644 index 0000000..276b454 --- /dev/null +++ b/S1/uucoco_#87/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from FDivergenceLoss_torch import Model, get_inputs, get_init_inputs +from FDivergenceLoss_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