finish TsallisDivergenceLoss #114

This commit is contained in:
uucoco 2025-12-10 19:44:37 +08:00
parent 10eed82956
commit e98d6055a2
4 changed files with 331 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 tsallis_divergence_kernel(
const float* __restrict__ p,
const float* __restrict__ q,
float* __restrict__ output,
int num_classes,
float q_param
) {
extern __shared__ float sdata[];
int tid = threadIdx.x;
int bid = blockIdx.x;
int row_offset = bid * num_classes;
float local_sum = 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];
local_sum += powf(p_val, q_param) * powf(q_val, 1.0f - q_param);
}
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) {
float sum_val = sdata[0];
output[bid] = (sum_val - 1.0f) / (q_param - 1.0f);
}
}
torch::Tensor tsallis_divergence_cuda(torch::Tensor p, torch::Tensor q, float q_param) {
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 = threads * sizeof(float);
tsallis_divergence_kernel<<<blocks, threads, shared_mem>>>(
p.data_ptr<float>(),
q.data_ptr<float>(),
output.data_ptr<float>(),
num_classes,
q_param
);
return output.mean();
}
"""
cpp_source = """
torch::Tensor tsallis_divergence_cuda(torch::Tensor p, torch::Tensor q, float q_param);
"""
tsallis_divergence_loss = load_inline(
name="tsallis_divergence_loss",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["tsallis_divergence_cuda"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, q=0.5):
super(ModelNew, self).__init__()
self.q = q
def forward(self, p, target):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(target, dim=1)
return tsallis_divergence_loss.tsallis_divergence_cuda(p_prob, q_prob, self.q)

View File

@ -0,0 +1,32 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, q=0.5):
super(Model, self).__init__()
self.q = q
def forward(self, p, target):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(target, dim=1)
sum_term = torch.sum((p_prob ** self.q) * (q_prob ** (1.0 - self.q)), dim=1)
loss = (sum_term - 1.0) / (self.q - 1.0)
return loss.mean()
batch_size = 32
num_classes = 1000
def get_inputs():
p = torch.randn(batch_size, num_classes, requires_grad=True)
target = torch.randn(batch_size, num_classes)
return [p, target]
def get_init_inputs():
return [0.5]

131
S1/uucoco_#114/prompt.txt Normal file
View File

@ -0,0 +1,131 @@
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 (tsallis_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
Block-Level Parallelism: One CUDA block per batch element
Grid-Stride Loops: Efficient memory access within each row
Mathematical Components
Tsallis Divergence: Non-extensive entropy-based divergence measure
Power Operations: powf(p, q) * powf(q_dist, 1-q) formulation
Linear Normalization: (sum - 1) / (q - 1) scaling
Statistical Distance: Measures difference between probability distributions
q-Parameter: Controls divergence properties (q ≠ 1)
Memory & Parallelism Patterns
Per-Batch Block Assignment: One CUDA block processes one batch element
Shared Memory Reduction: Tree reduction within thread blocks
Row-Wise Processing: Threads parallelize across class dimensions within rows
Batch Independence: Parallel processing across batch dimension
Optimization Techniques
Grid-Stride Loops: Threads process multiple elements within their assigned row
Shared Memory Efficiency: Single buffer for intermediate sums
Fused Computation: Complete Tsallis divergence calculation per batch element
Numerical Stability: Linear scaling after summation
Coalesced Memory Access: Sequential memory access patterns
Performance Features
Massive Parallelization: GPU acceleration for divergence computation
Memory Efficiency: Shared memory reuse for reduction operations
Scalable Design: Efficient for varying batch sizes and class counts
Minimal Synchronization: Single __syncthreads() call per reduction
Batch Mean Computation: Final averaging performed on CPU
Unique Implementation Aspects
q-Parameter Naming: Note: Uses q_param (not to confuse with input q tensor)
Linear Scaling: Tsallis divergence uses linear rather than logarithmic scaling
Power Product: Similar to Rényi but with different normalization
Per-Sample Output: Each batch element gets its own divergence value
Non-Extensive Statistics: Based on Tsallis entropy formulation
Comparison with Similar Divergences
vs Rényi: Uses linear (sum-1)/(q-1) instead of logarithmic log(sum)/(q-1)
vs Alpha Divergence: Similar power structure but different normalization
Parameter Range: Typically q > 0, q ≠ 1 for proper divergence definition
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, q=0.5):
super(Model, self).__init__()
self.q = q
def forward(self, p, target):
p_prob = F.softmax(p, dim=1)
q_prob = F.softmax(target, dim=1)
sum_term = torch.sum((p_prob ** self.q) * (q_prob ** (1.0 - self.q)), dim=1)
loss = (sum_term - 1.0) / (self.q - 1.0)
return loss.mean()
batch_size = 32
num_classes = 1000
def get_inputs():
p = torch.randn(batch_size, num_classes, requires_grad=True)
target = torch.randn(batch_size, num_classes)
return [p, target]
def get_init_inputs():
return [0.5]

View File

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