finish GammmaDivergenceLoss #88

This commit is contained in:
uucoco 2025-12-10 19:09:28 +08:00
parent 10eed82956
commit 229b6b005c
4 changed files with 352 additions and 0 deletions

View File

@ -0,0 +1,113 @@
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 gamma_divergence_kernel(
const float* __restrict__ p,
const float* __restrict__ q,
float* __restrict__ output,
int num_classes,
float gamma
) {
extern __shared__ float sdata[];
int tid = threadIdx.x;
int bid = blockIdx.x;
int row_offset = bid * num_classes;
float* s_p = sdata;
float* s_pq = sdata + blockDim.x;
float* s_q = sdata + 2 * blockDim.x;
float local_p = 0.0f;
float local_pq = 0.0f;
float local_q = 0.0f;
for (int i = tid; i < num_classes; i += blockDim.x) {
float p_val = p[row_offset + i];
float q_val = q[row_offset + i];
float q_pow_g = powf(q_val, gamma);
local_p += powf(p_val, 1.0f + gamma);
local_pq += p_val * q_pow_g;
local_q += powf(q_val, 1.0f + gamma);
}
s_p[tid] = local_p;
s_pq[tid] = local_pq;
s_q[tid] = local_q;
__syncthreads();
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
s_p[tid] += s_p[tid + s];
s_pq[tid] += s_pq[tid + s];
s_q[tid] += s_q[tid + s];
}
__syncthreads();
}
if (tid == 0) {
float sum_p = s_p[0];
float sum_pq = s_pq[0];
float sum_q = s_q[0];
float term1 = logf(sum_p) / (gamma * (1.0f + gamma));
float term2 = logf(sum_pq) / gamma;
float term3 = logf(sum_q) / (1.0f + gamma);
output[bid] = term1 - term2 + term3;
}
}
torch::Tensor gamma_divergence_cuda(torch::Tensor p, torch::Tensor q, float gamma) {
int batch_size = p.size(0);
int num_classes = p.size(1);
auto output = at::empty({batch_size}, p.options());
int threads = 256;
int blocks = batch_size;
int shared_mem = 3 * threads * sizeof(float);
gamma_divergence_kernel<<<blocks, threads, shared_mem>>>(
p.data_ptr<float>(),
q.data_ptr<float>(),
output.data_ptr<float>(),
num_classes,
gamma
);
return output.mean();
}
"""
cpp_source = """
torch::Tensor gamma_divergence_cuda(torch::Tensor p, torch::Tensor q, float gamma);
"""
gamma_divergence_loss = load_inline(
name="gamma_divergence_loss",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["gamma_divergence_cuda"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, gamma=0.5):
super(ModelNew, self).__init__()
self.gamma = gamma
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
return gamma_divergence_loss.gamma_divergence_cuda(p_prob, q_prob, self.gamma)

View File

@ -0,0 +1,38 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, gamma=0.5):
super(Model, self).__init__()
self.gamma = gamma
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
sum_p_pow = torch.sum(p_prob.pow(1.0 + self.gamma), dim=1)
sum_pq_pow = torch.sum(p_prob * q_prob.pow(self.gamma), dim=1)
sum_q_pow = torch.sum(q_prob.pow(1.0 + self.gamma), dim=1)
term1 = torch.log(sum_p_pow) / (self.gamma * (1.0 + self.gamma))
term2 = torch.log(sum_pq_pow) / self.gamma
term3 = torch.log(sum_q_pow) / (1.0 + self.gamma)
loss = term1 - term2 + term3
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]

124
S1/uucoco_#88/prompt.txt Normal file
View File

@ -0,0 +1,124 @@
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 (gamma_divergence_kernel)
CUDA Math Functions: powf() for exponentiation, logf() for logarithms
Parallel Reduction: Tree-based reduction with multiple accumulators
Shared Memory: Using __shared__ with triple-buffer pattern (s_p, s_pq, s_q)
Block-Level Parallelism: One CUDA block per batch element
Thread-Level Parallelism: Parallel reduction across class dimensions
Mathematical Components
Gamma Divergence: Information-geometric divergence measure
Logarithmic Terms: Three logarithmic terms with different denominators
Power Computations: Multiple powf() calls with (1 + gamma) exponent
Normalization: Gamma parameter scaling in denominator terms
Statistical Distance: Measures difference between probability distributions
Memory & Parallelism Patterns
Triple Shared Memory Buffers: Separate buffers for p, pq, and q summations
Batch-Level Parallelism: Each batch element processed by separate CUDA block
Class-Level Parallelism: Threads parallelize across class dimensions
Hierarchical Reduction: Two-level parallel reduction within blocks
Optimization Techniques
Shared Memory Optimization: Efficient triple-buffer layout
Coalesced Memory Access: Sequential memory access patterns
Fused Computation: Complete divergence calculation per batch element
Logarithm Post-processing: Log operations after reduction (numerically stable)
Performance Features
Massive Parallelization: GPU acceleration for divergence computation
Numerical Stability: Log operations performed after summation
Memory Efficiency: Shared memory reuse across multiple reductions
Batch Independence: Parallel processing of batch elements
Host-Device Coordination: Final mean computation on CPU
Unique Implementation Aspects
Per-Batch Block Assignment: One CUDA block per batch element
Triple Reduction Pattern: Simultaneous reduction of three different sums
Logarithmic Normalization: Log operations in final divergence formula
Gamma Parameter Scaling: Parameter appears in all three denominator terms
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, gamma=0.5):
super(Model, self).__init__()
self.gamma = gamma
def forward(self, p, q):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(q, dim=1)
sum_p_pow = torch.sum(p_prob.pow(1.0 + self.gamma), dim=1)
sum_pq_pow = torch.sum(p_prob * q_prob.pow(self.gamma), dim=1)
sum_q_pow = torch.sum(q_prob.pow(1.0 + self.gamma), dim=1)
term1 = torch.log(sum_p_pow) / (self.gamma * (1.0 + self.gamma))
term2 = torch.log(sum_pq_pow) / self.gamma
term3 = torch.log(sum_q_pow) / (1.0 + self.gamma)
loss = term1 - term2 + term3
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_#88/run_code.py Normal file
View File

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