finish ALphaDivergenceLoss #78

This commit is contained in:
uucoco 2025-12-10 18:58:50 +08:00
parent 10eed82956
commit 0c9ff965de
4 changed files with 302 additions and 0 deletions

View File

@ -0,0 +1,91 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void alpha_divergence_kernel(
const float* __restrict__ p,
const float* __restrict__ q,
float* __restrict__ output,
int n,
float alpha
) {
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];
local_sum += powf(p_val, alpha) * powf(q_val, 1.0f - alpha);
}
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 alpha_divergence_cuda(torch::Tensor p, torch::Tensor q, float alpha) {
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);
alpha_divergence_kernel<<<blocks, threads, shared_mem>>>(
p.data_ptr<float>(),
q.data_ptr<float>(),
output.data_ptr<float>(),
n,
alpha
);
float sum_val = output.item<float>();
float mean_sum = sum_val / batch_size;
float loss = (mean_sum - 1.0f) / (alpha * (alpha - 1.0f));
return torch::tensor(loss, p.options());
}
"""
cpp_source = """
torch::Tensor alpha_divergence_cuda(torch::Tensor p, torch::Tensor q, float alpha);
"""
alpha_divergence_loss = load_inline(
name="alpha_divergence_loss",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["alpha_divergence_cuda"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, alpha=0.5):
super(ModelNew, self).__init__()
self.alpha = alpha
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
return alpha_divergence_loss.alpha_divergence_cuda(p_prob, q_prob, self.alpha)

View File

@ -0,0 +1,33 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, alpha=0.5):
super(Model, self).__init__()
self.alpha = alpha
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
term = (p_prob ** self.alpha) * (q_prob ** (1 - self.alpha))
sum_term = torch.sum(term, dim=1)
loss = (sum_term - 1) / (self.alpha * (self.alpha - 1))
return loss.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 [0.5]

101
S1/uucoco_#78/prompt.txt Normal file
View File

@ -0,0 +1,101 @@
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
torch.tensor(): Tensor creation from Python scalar
CUDA/C++ Implementation Details
CUDA Kernels: Custom GPU kernel (alpha_divergence_kernel)
CUDA Math Functions: powf() for floating-point exponentiation
Parallel Reduction: Tree-based reduction using shared memory
Shared Memory: Using __shared__ for inter-thread communication
Atomic Operations: atomicAdd for thread-safe global updates
Grid-Stride Loops: Efficient memory access pattern
Mathematical Components
Alpha Divergence: Rényi/Alpha family of divergences between distributions
Exponential Operations: Power computations with powf()
Normalization: Scaling by (alpha * (alpha - 1.0f))
Statistical Distance: Measures difference between probability distributions
Optimization Techniques
Shared Memory Reduction: Parallel tree reduction within thread blocks
Grid-Stride Loops: Efficient handling of arbitrary tensor sizes
Fused Computation: Complete divergence calculation in single kernel
Batch Processing: Mean computation across batch dimension
Performance Features
Massive Parallelization: GPU acceleration for divergence computation
Memory Efficiency: Shared memory for intermediate reduction results
Numerical Stability: Proper handling of alpha parameter range
Host-Device Coordination: CPU post-processing of GPU results
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, alpha=0.5):
super(Model, self).__init__()
self.alpha = alpha
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
term = (p_prob ** self.alpha) * (q_prob ** (1 - self.alpha))
sum_term = torch.sum(term, dim=1)
loss = (sum_term - 1) / (self.alpha * (self.alpha - 1))
return loss.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 [0.5]

77
S1/uucoco_#78/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from AlphaDivergenceLoss_torch import Model, get_inputs, get_init_inputs
from AlphaDivergenceLoss_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()