From 1c297de88d29ba4d439b71be7257edca2e486f50 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 18:38:14 +0800 Subject: [PATCH] finish ComboLoss #58 --- S1/uucoco_#58/ComboLoss_cuda.py | 170 +++++++++++++++++++++++++++++++ S1/uucoco_#58/ComboLoss_torch.py | 51 ++++++++++ S1/uucoco_#58/prompt.txt | 119 ++++++++++++++++++++++ S1/uucoco_#58/run_code.py | 77 ++++++++++++++ 4 files changed, 417 insertions(+) create mode 100644 S1/uucoco_#58/ComboLoss_cuda.py create mode 100644 S1/uucoco_#58/ComboLoss_torch.py create mode 100644 S1/uucoco_#58/prompt.txt create mode 100644 S1/uucoco_#58/run_code.py diff --git a/S1/uucoco_#58/ComboLoss_cuda.py b/S1/uucoco_#58/ComboLoss_cuda.py new file mode 100644 index 0000000..c3702cc --- /dev/null +++ b/S1/uucoco_#58/ComboLoss_cuda.py @@ -0,0 +1,170 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, alpha_combo=0.5, gamma_focal=2.0, smooth=1.0): + super().__init__() + self.alpha_combo = alpha_combo + self.gamma_focal = gamma_focal + self.smooth = smooth + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + torch::Tensor combo_loss_cuda(torch::Tensor logits, torch::Tensor targets, double gamma, double smooth, int batch_size); + """ + + cuda_source = """ + #include + #include + #include + + __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 combo_loss_kernel( + const double* __restrict__ logits, + const double* __restrict__ targets, + double* __restrict__ dice_inter, + double* __restrict__ dice_sum_inputs, + double* __restrict__ dice_sum_targets, + double* __restrict__ focal_out, + const int batch_size, + const int feature_dim, + const double gamma) + { + 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_sum_inputs[256]; + __shared__ double s_sum_targets[256]; + __shared__ double s_focal[256]; + + double local_inter = 0.0; + double local_sum_inputs = 0.0; + double local_sum_targets = 0.0; + double local_focal = 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_sum_inputs += p; + local_sum_targets += 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); + + double pt = exp(-bce); + double focal_weight = pow(1.0 - pt, gamma); + local_focal += focal_weight * bce; + } + + s_inter[tid] = local_inter; + s_sum_inputs[tid] = local_sum_inputs; + s_sum_targets[tid] = local_sum_targets; + s_focal[tid] = local_focal; + __syncthreads(); + + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if (tid < s) { + s_inter[tid] += s_inter[tid + s]; + s_sum_inputs[tid] += s_sum_inputs[tid + s]; + s_sum_targets[tid] += s_sum_targets[tid + s]; + s_focal[tid] += s_focal[tid + s]; + } + __syncthreads(); + } + + if (tid == 0) { + dice_inter[batch_idx] = s_inter[0]; + dice_sum_inputs[batch_idx] = s_sum_inputs[0]; + dice_sum_targets[batch_idx] = s_sum_targets[0]; + focal_out[batch_idx] = s_focal[0]; + } + } + + torch::Tensor combo_loss_cuda(torch::Tensor logits, torch::Tensor targets, double gamma, double smooth, int batch_size) { + auto Z_c = logits.contiguous(); + auto Y_c = targets.contiguous(); + + const int feature_dim = Z_c.size(1); + + auto dice_inter = torch::zeros({batch_size}, Z_c.options()); + auto dice_sum_inputs = torch::zeros({batch_size}, Z_c.options()); + auto dice_sum_targets = torch::zeros({batch_size}, Z_c.options()); + auto focal_out = torch::zeros({batch_size}, Z_c.options()); + + const int threads = 256; + const int blocks = batch_size; + + combo_loss_kernel<<>>( + Z_c.data_ptr(), + Y_c.data_ptr(), + dice_inter.data_ptr(), + dice_sum_inputs.data_ptr(), + dice_sum_targets.data_ptr(), + focal_out.data_ptr(), + batch_size, + feature_dim, + gamma + ); + + return torch::cat({dice_inter, dice_sum_inputs, dice_sum_targets, focal_out}, 0); + } + """ + + self.op = load_inline( + name="combo_loss_v5", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["combo_loss_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, logits, targets): + targets_f = targets.to(logits.dtype) + + batch_size = logits.size(0) + + comp_flat = self.op.combo_loss_cuda(logits, targets_f, self.gamma_focal, self.smooth, batch_size) + + dice_inter = comp_flat[:batch_size] + dice_sum_inputs = comp_flat[batch_size:2 * batch_size] + dice_sum_targets = comp_flat[2 * batch_size:3 * batch_size] + focal_out = comp_flat[3 * batch_size:] + + dice = (2.0 * dice_inter + self.smooth) / (dice_sum_inputs + dice_sum_targets + self.smooth) + dice_loss = 1.0 - dice.mean() + + focal_loss = focal_out.sum() / (batch_size * logits.size(1)) + + return self.alpha_combo * dice_loss + (1.0 - self.alpha_combo) * focal_loss \ No newline at end of file diff --git a/S1/uucoco_#58/ComboLoss_torch.py b/S1/uucoco_#58/ComboLoss_torch.py new file mode 100644 index 0000000..4ea9664 --- /dev/null +++ b/S1/uucoco_#58/ComboLoss_torch.py @@ -0,0 +1,51 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Model(nn.Module): + def __init__(self, alpha_combo=0.5, gamma_focal=2.0, smooth=1.0): + super().__init__() + self.alpha_combo = alpha_combo + self.gamma_focal = gamma_focal + self.smooth = smooth + + def _dice_loss(self, inputs, targets) -> torch.Tensor: + inputs = inputs.sigmoid() + inputs = inputs.flatten(1) + targets = targets.flatten(1) + + intersection = (inputs * targets).sum(dim=1) + dice = (2.0 * intersection + self.smooth) / (inputs.sum(dim=1) + targets.sum(dim=1) + self.smooth) + + return 1.0 - dice.mean() + + def _focal_loss(self, inputs, targets) -> torch.Tensor: + BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') + pt = torch.exp(-BCE_loss) + + focal_loss = ((1.0 - pt) ** self.gamma_focal) * BCE_loss + return focal_loss.mean() + + def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: + targets_f = targets.float() + + dice_loss = self._dice_loss(logits, targets_f) + + focal_loss = self._focal_loss(logits, targets_f) + + return self.alpha_combo * dice_loss + (1.0 - self.alpha_combo) * focal_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, 2.0, 1.0] \ No newline at end of file diff --git a/S1/uucoco_#58/prompt.txt b/S1/uucoco_#58/prompt.txt new file mode 100644 index 0000000..b3f7e46 --- /dev/null +++ b/S1/uucoco_#58/prompt.txt @@ -0,0 +1,119 @@ +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. + +This CUDA kernel implements a Combo Loss function combining Dice Loss and Focal Loss with advanced parallel reduction techniques: + +Key Optimizations: +Numerically Stable Sigmoid: Implements stable sigmoid for both positive and negative inputs using exp(-|x|) to avoid overflow. + +Stable Log-Sigmoid: Uses different formulas for positive/negative inputs to maintain numerical precision. + +Parallel Reduction with Shared Memory: Each thread block processes one batch sample, using shared memory reduction to sum across feature dimensions: + +Local accumulation in registers + +Store to shared memory arrays + +Tree reduction (for (int s = blockDim.x / 2; s > 0; s >>= 1)) + +Thread 0 writes final reduced values + +Computational Components (per batch sample): +Dice Loss Components: + +inter = Σ(p * y) (intersection) + +sum_inputs = Σ(p) + +sum_targets = Σ(y) + +Later computed as: dice = (2*inter + smooth) / (sum_inputs + sum_targets + smooth) + +Focal Loss Components: + +Computes BCE loss with focal weighting: focal_weight * bce + +pt = exp(-bce) (probability of correct classification) + +focal_weight = (1 - pt)^gamma + +Performance Characteristics: +Double Precision: Uses double for higher numerical accuracy + +Batch-Level Parallelism: Each block processes one batch element independently + +Feature-Level Parallel Reduction: Threads within block sum across feature dimensions + +Multiple Outputs: Computes 4 intermediate values per batch sample concurrently + +Final Loss Computation: +L = α * dice_loss + (1 - α) * focal_loss + +Where: + +dice_loss = 1 - mean(dice) (averaged across batch) + +focal_loss = sum(focal_out) / (batch_size * feature_dim) + +Advantages: +Avoids intermediate tensor creation between reductions + +Fuses multiple loss computations into single kernel + +Efficient shared memory utilization for reductions + + + +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_combo=0.5, gamma_focal=2.0, smooth=1.0): + super().__init__() + self.alpha_combo = alpha_combo + self.gamma_focal = gamma_focal + self.smooth = smooth + + def _dice_loss(self, inputs, targets) -> torch.Tensor: + inputs = inputs.sigmoid() + inputs = inputs.flatten(1) + targets = targets.flatten(1) + + intersection = (inputs * targets).sum(dim=1) + dice = (2.0 * intersection + self.smooth) / (inputs.sum(dim=1) + targets.sum(dim=1) + self.smooth) + + return 1.0 - dice.mean() + + def _focal_loss(self, inputs, targets) -> torch.Tensor: + BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') + pt = torch.exp(-BCE_loss) + + focal_loss = ((1.0 - pt) ** self.gamma_focal) * BCE_loss + return focal_loss.mean() + + def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: + targets_f = targets.float() + + dice_loss = self._dice_loss(logits, targets_f) + + focal_loss = self._focal_loss(logits, targets_f) + + return self.alpha_combo * dice_loss + (1.0 - self.alpha_combo) * focal_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, 2.0, 1.0] \ No newline at end of file diff --git a/S1/uucoco_#58/run_code.py b/S1/uucoco_#58/run_code.py new file mode 100644 index 0000000..0a04a89 --- /dev/null +++ b/S1/uucoco_#58/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from ComboLoss_torch import Model, get_inputs, get_init_inputs +from ComboLoss_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() \ No newline at end of file