finish AngularLoss #57

This commit is contained in:
uucoco 2025-12-10 18:37:10 +08:00
parent 10eed82956
commit a40388fd02
4 changed files with 368 additions and 0 deletions

View File

@ -0,0 +1,154 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, alpha=0.5, smooth=1e-6):
super().__init__()
self.alpha = alpha
self.smooth = smooth
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor angular_loss_cuda(torch::Tensor logits, torch::Tensor targets, double smooth, int batch_size);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__device__ __forceinline__ double sigmoid_d(double x) {
if (x >= 0.0) {
double z = exp(-x);
return 1.0 / (1.0 + z);
} else {
double z = exp(x);
return z / (1.0 + z);
}
}
__device__ __forceinline__ double log_sigmoid_d(double x) {
if (x >= 0.0) {
return -log(1.0 + exp(-x));
} else {
return x - log(1.0 + exp(x));
}
}
__global__ void angular_loss_kernel(
const double* __restrict__ logits,
const double* __restrict__ targets,
double* __restrict__ intersection_out,
double* __restrict__ union_out,
double* __restrict__ bce_out,
const int batch_size,
const int feature_dim)
{
const int batch_idx = blockIdx.x;
const int tid = threadIdx.x;
const int stride = blockDim.x;
if (batch_idx >= batch_size) return;
__shared__ double s_inter[256];
__shared__ double s_union[256];
__shared__ double s_bce[256];
double local_inter = 0.0;
double local_union = 0.0;
double local_bce = 0.0;
const int offset = batch_idx * feature_dim;
for (int i = tid; i < feature_dim; i += stride) {
double z = logits[offset + i];
double y = targets[offset + i];
double p = sigmoid_d(z);
local_inter += p * y;
local_union += p + y;
double log_p = log_sigmoid_d(z);
double log_1mp = log_sigmoid_d(-z);
double bce = -(y * log_p + (1.0 - y) * log_1mp);
local_bce += bce;
}
s_inter[tid] = local_inter;
s_union[tid] = local_union;
s_bce[tid] = local_bce;
__syncthreads();
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
s_inter[tid] += s_inter[tid + s];
s_union[tid] += s_union[tid + s];
s_bce[tid] += s_bce[tid + s];
}
__syncthreads();
}
if (tid == 0) {
intersection_out[batch_idx] = s_inter[0];
union_out[batch_idx] = s_union[0];
bce_out[batch_idx] = s_bce[0];
}
}
torch::Tensor angular_loss_cuda(torch::Tensor logits, torch::Tensor targets, double smooth, int batch_size) {
auto Z_c = logits.contiguous();
auto Y_c = targets.contiguous();
const int feature_dim = Z_c.size(1);
auto intersection_out = torch::zeros({batch_size}, Z_c.options());
auto union_out = torch::zeros({batch_size}, Z_c.options());
auto bce_out = torch::zeros({batch_size}, Z_c.options());
const int threads = 256;
const int blocks = batch_size;
angular_loss_kernel<<<blocks, threads>>>(
Z_c.data_ptr<double>(),
Y_c.data_ptr<double>(),
intersection_out.data_ptr<double>(),
union_out.data_ptr<double>(),
bce_out.data_ptr<double>(),
batch_size,
feature_dim
);
return torch::cat({intersection_out, union_out, bce_out}, 0);
}
"""
self.op = load_inline(
name="angular_loss_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["angular_loss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, logits, targets):
targets_f = targets.to(logits.dtype)
batch_size = logits.size(0)
feature_dim = logits.size(1)
comp_flat = self.op.angular_loss_cuda(logits, targets_f, self.smooth, batch_size)
intersection = comp_flat[:batch_size]
union = comp_flat[batch_size:2 * batch_size]
bce_sum = comp_flat[2 * batch_size:]
angle = 1.0 - (2.0 * intersection + self.smooth) / (union + self.smooth)
angular_loss = (angle * (1.0 - angle)).mean()
bce_loss = bce_sum.sum() / (batch_size * feature_dim)
return self.alpha * angular_loss + (1.0 - self.alpha) * bce_loss

View File

@ -0,0 +1,41 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, alpha=0.5, smooth=1e-6):
super().__init__()
self.alpha = alpha
self.smooth = smooth
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
targets_f = targets.float()
probs = logits.sigmoid()
probs = probs.flatten(1)
targets_f = targets_f.flatten(1)
intersection = (probs * targets_f).sum(dim=1)
union = probs.sum(dim=1) + targets_f.sum(dim=1)
angle = 1.0 - (2.0 * intersection + self.smooth) / (union + self.smooth)
angular_loss = (angle * (1.0 - angle)).mean()
bce_loss = F.binary_cross_entropy_with_logits(logits, targets_f, reduction='mean')
return self.alpha * angular_loss + (1.0 - self.alpha) * bce_loss
batch_size = 512
feature_dim = 128
def get_inputs():
logits = torch.randn(batch_size, feature_dim, dtype=torch.float64)
targets = torch.randint(0, 2, (batch_size, feature_dim), dtype=torch.float64)
return [logits, targets]
def get_init_inputs():
return [0.5, 1e-6]

96
S1/uucoco_#57/prompt.txt Normal file
View File

@ -0,0 +1,96 @@
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.
This CUDA kernel implements an Angular Loss function with shared memory parallel reduction, similar to the Combo Loss but with different mathematical components:
Key Optimizations:
Numerically Stable Sigmoid & Log-Sigmoid: Same stable implementations as Combo Loss using exp(-|x|) to avoid overflow.
Parallel Reduction with Shared Memory: Each thread block processes one batch sample using tree reduction in shared memory:
Local accumulation in registers
Shared memory arrays for three values: inter, union, bce
Binary tree reduction (for (int s = blockDim.x / 2; s > 0; s >>= 1))
Thread 0 writes final reduced values
Computational Components (per batch sample):
Intersection: inter = Σ(p * y) where p = sigmoid(z)
Union: union = Σ(p + y) (sum of predictions and targets)
BCE Loss: bce = -[y*log(p) + (1-y)*log(1-p)] using stable log-sigmoid
Angular Loss Computation (in Python forward):
Angle Metric: angle = 1 - (2*inter + smooth) / (union + smooth)
Similar to Dice but with different normalization
Angular Loss: angular_loss = mean(angle * (1 - angle))
Quadratic penalty that peaks at angle=0.5
BCE Loss: bce_loss = sum(bce) / (batch_size * feature_dim)
Final Loss:
L = α * angular_loss + (1 - α) * bce_loss
Performance Characteristics:
Double Precision: Uses double for numerical accuracy in angle calculations
Batch-Level Parallelism: Each block processes one batch element
Feature-Level Reduction: Threads within block sum across feature dimensions
Three Concurrent Reductions: Computes intersection, union, and BCE simultaneously
Advantages:
Avoids intermediate tensor creation
Fuses multiple computations into single kernel
Efficient shared memory utilization
Numerically stable operations for extreme values
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, smooth=1e-6):
super().__init__()
self.alpha = alpha
self.smooth = smooth
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
targets_f = targets.float()
probs = logits.sigmoid()
probs = probs.flatten(1)
targets_f = targets_f.flatten(1)
intersection = (probs * targets_f).sum(dim=1)
union = probs.sum(dim=1) + targets_f.sum(dim=1)
angle = 1.0 - (2.0 * intersection + self.smooth) / (union + self.smooth)
angular_loss = (angle * (1.0 - angle)).mean()
bce_loss = F.binary_cross_entropy_with_logits(logits, targets_f, reduction='mean')
return self.alpha * angular_loss + (1.0 - self.alpha) * bce_loss
batch_size = 128
feature_dim = 64
def get_inputs():
logits = torch.randn(batch_size, feature_dim, dtype=torch.float64)
targets = torch.randint(0, 2, (batch_size, feature_dim), dtype=torch.float64)
return [logits, targets]
def get_init_inputs():
return [0.5, 1e-6]

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

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