finish CrossEntropyDiceLoss #59

This commit is contained in:
uucoco 2025-12-10 18:39:13 +08:00
parent 10eed82956
commit d44eb0f537
4 changed files with 351 additions and 0 deletions

View File

@ -0,0 +1,166 @@
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=1.0):
super().__init__()
self.alpha = alpha
self.smooth = smooth
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor ce_dice_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 ce_dice_loss_kernel(
const double* __restrict__ logits,
const double* __restrict__ targets,
double* __restrict__ intersection_out,
double* __restrict__ sum_probs_out,
double* __restrict__ sum_targets_out,
double* __restrict__ ce_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_probs[256];
__shared__ double s_targets[256];
__shared__ double s_ce[256];
double local_inter = 0.0;
double local_probs = 0.0;
double local_targets = 0.0;
double local_ce = 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_probs += p;
local_targets += y;
double log_p = log_sigmoid_d(z);
double log_1mp = log_sigmoid_d(-z);
double ce = -(y * log_p + (1.0 - y) * log_1mp);
local_ce += ce;
}
s_inter[tid] = local_inter;
s_probs[tid] = local_probs;
s_targets[tid] = local_targets;
s_ce[tid] = local_ce;
__syncthreads();
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
s_inter[tid] += s_inter[tid + s];
s_probs[tid] += s_probs[tid + s];
s_targets[tid] += s_targets[tid + s];
s_ce[tid] += s_ce[tid + s];
}
__syncthreads();
}
if (tid == 0) {
intersection_out[batch_idx] = s_inter[0];
sum_probs_out[batch_idx] = s_probs[0];
sum_targets_out[batch_idx] = s_targets[0];
ce_out[batch_idx] = s_ce[0];
}
}
torch::Tensor ce_dice_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 sum_probs_out = torch::zeros({batch_size}, Z_c.options());
auto sum_targets_out = torch::zeros({batch_size}, Z_c.options());
auto ce_out = torch::zeros({batch_size}, Z_c.options());
const int threads = 256;
const int blocks = batch_size;
ce_dice_loss_kernel<<<blocks, threads>>>(
Z_c.data_ptr<double>(),
Y_c.data_ptr<double>(),
intersection_out.data_ptr<double>(),
sum_probs_out.data_ptr<double>(),
sum_targets_out.data_ptr<double>(),
ce_out.data_ptr<double>(),
batch_size,
feature_dim
);
return torch::cat({intersection_out, sum_probs_out, sum_targets_out, ce_out}, 0);
}
"""
self.op = load_inline(
name="ce_dice_loss_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["ce_dice_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.ce_dice_loss_cuda(logits, targets_f, self.smooth, batch_size)
intersection = comp_flat[:batch_size]
sum_probs = comp_flat[batch_size:2 * batch_size]
sum_targets = comp_flat[2 * batch_size:3 * batch_size]
ce_sum = comp_flat[3 * batch_size:]
dice = (2.0 * intersection + self.smooth) / (sum_probs + sum_targets + self.smooth)
dice_loss = 1.0 - dice.mean()
ce_loss = ce_sum.sum() / (batch_size * feature_dim)
return self.alpha * dice_loss + (1.0 - self.alpha) * ce_loss

View File

@ -0,0 +1,39 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, alpha=0.5, smooth=1.0):
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_flat = targets_f.flatten(1)
intersection = (probs * targets_f_flat).sum(dim=1)
dice = (2.0 * intersection + self.smooth) / (probs.sum(dim=1) + targets_f_flat.sum(dim=1) + self.smooth)
dice_loss = 1.0 - dice.mean()
ce_loss = F.binary_cross_entropy_with_logits(logits, targets_f, reduction='mean')
return self.alpha * dice_loss + (1.0 - self.alpha) * ce_loss
batch_size = 128
feature_dim = 100
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, 1.0]

69
S1/uucoco_#59/prompt.txt Normal file
View File

@ -0,0 +1,69 @@
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.
CUDA kernel for CrossEntropy-Dice Loss with shared memory parallel reduction.
Optimizations:
Numerically stable sigmoid/log-sigmoid using exp(-|x|).
Parallel tree reduction in shared memory (4 concurrent reductions).
Batch-level parallelism (one block per sample).
Double precision for accuracy.
Kernel computes per batch:
intersection = Σ(p*y) for Dice
sum_probs = Σ(p)
sum_targets = Σ(y)
ce_sum = Σ(BCE loss)
Final loss:
L = α·(1-mean(Dice)) + (1-α)·mean(CE)
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=1.0):
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_flat = targets_f.flatten(1)
intersection = (probs * targets_f_flat).sum(dim=1)
dice = (2.0 * intersection + self.smooth) / (probs.sum(dim=1) + targets_f_flat.sum(dim=1) + self.smooth)
dice_loss = 1.0 - dice.mean()
ce_loss = F.binary_cross_entropy_with_logits(logits, targets_f, reduction='mean')
return self.alpha * dice_loss + (1.0 - self.alpha) * ce_loss
batch_size = 128
feature_dim = 100
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, 1.0]

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

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