From 1dcc7921bcdc5ffc07252819af8367348b0ce0be Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:25:44 +0800 Subject: [PATCH] finish ModeSeekingLoss #99 --- S1/uucoco_#99/ModeSeekingLoss_cuda.py | 115 +++++++++++++++++++++++++ S1/uucoco_#99/ModeSeekingLoss_torch.py | 32 +++++++ S1/uucoco_#99/prompt.txt | 53 ++++++++++++ S1/uucoco_#99/run_code.py | 77 +++++++++++++++++ 4 files changed, 277 insertions(+) create mode 100644 S1/uucoco_#99/ModeSeekingLoss_cuda.py create mode 100644 S1/uucoco_#99/ModeSeekingLoss_torch.py create mode 100644 S1/uucoco_#99/prompt.txt create mode 100644 S1/uucoco_#99/run_code.py diff --git a/S1/uucoco_#99/ModeSeekingLoss_cuda.py b/S1/uucoco_#99/ModeSeekingLoss_cuda.py new file mode 100644 index 0000000..5c461b1 --- /dev/null +++ b/S1/uucoco_#99/ModeSeekingLoss_cuda.py @@ -0,0 +1,115 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, eps=1e-5): + super().__init__() + self.eps = eps + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + torch::Tensor modeseekingloss_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor z1, torch::Tensor z2, float eps); + """ + + cuda_source = """ + #include + #include + + __global__ void reduce_l1_diff_kernel( + const float* __restrict__ a, + const float* __restrict__ b, + float* __restrict__ out, + const int dim) + { + extern __shared__ float sdata[]; + int tid = threadIdx.x; + int bid = blockIdx.x; + + float sum = 0.0f; + for (int i = tid; i < dim; i += blockDim.x) { + float diff = a[bid * dim + i] - b[bid * dim + i]; + sum += fabsf(diff); + } + + sdata[tid] = sum; + __syncthreads(); + + for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) { + if (tid < s) { + sdata[tid] += sdata[tid + s]; + } + __syncthreads(); + } + + if (tid == 0) { + out[bid] = sdata[0] / (float)dim; + } + } + + __global__ void compute_ratio_kernel( + const float* __restrict__ img_diff, + const float* __restrict__ z_diff, + float* __restrict__ output, + const int n, + const float eps) + { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) { + output[i] = z_diff[i] / (img_diff[i] + eps); + } + } + + torch::Tensor modeseekingloss_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor z1, torch::Tensor z2, float eps) { + int batch_size = img1.size(0); + int img_dim = img1.numel() / batch_size; + int z_dim = z1.numel() / batch_size; + + auto img_diff = torch::empty({batch_size}, img1.options()); + auto z_diff = torch::empty({batch_size}, z1.options()); + auto output = torch::empty({batch_size}, img1.options()); + + int threads = 256; + int blocks = batch_size; + int shared_mem = threads * sizeof(float); + + reduce_l1_diff_kernel<<>>( + img1.data_ptr(), + img2.data_ptr(), + img_diff.data_ptr(), + img_dim + ); + + reduce_l1_diff_kernel<<>>( + z1.data_ptr(), + z2.data_ptr(), + z_diff.data_ptr(), + z_dim + ); + + int ratio_blocks = (batch_size + threads - 1) / threads; + compute_ratio_kernel<<>>( + img_diff.data_ptr(), + z_diff.data_ptr(), + output.data_ptr(), + batch_size, + eps + ); + + return output.mean(); + } + """ + + self.op = load_inline( + name="modeseekingloss_op", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["modeseekingloss_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, img1, img2, z1, z2): + return self.op.modeseekingloss_cuda(img1, img2, z1, z2, self.eps) \ No newline at end of file diff --git a/S1/uucoco_#99/ModeSeekingLoss_torch.py b/S1/uucoco_#99/ModeSeekingLoss_torch.py new file mode 100644 index 0000000..a0ab91d --- /dev/null +++ b/S1/uucoco_#99/ModeSeekingLoss_torch.py @@ -0,0 +1,32 @@ +import torch +import torch.nn as nn + + +class Model(nn.Module): + def __init__(self, eps=1e-5): + super().__init__() + self.eps = eps + + def forward(self, img1: torch.Tensor, img2: torch.Tensor, z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor: + img_diff = torch.abs(img1 - img2).view(img1.size(0), -1).mean(dim=1) + z_diff = torch.abs(z1 - z2).view(z1.size(0), -1).mean(dim=1) + + loss = z_diff / (img_diff + self.eps) + return loss.mean() + + +batch_size = 32 +c, h, w = 3, 64, 64 +z_dim = 128 + + +def get_inputs(): + img1 = torch.randn(batch_size, c, h, w, dtype=torch.float32) + img2 = torch.randn(batch_size, c, h, w, dtype=torch.float32) + z1 = torch.randn(batch_size, z_dim, dtype=torch.float32) + z2 = torch.randn(batch_size, z_dim, dtype=torch.float32) + return [img1, img2, z1, z2] + + +def get_init_inputs(): + return [1e-5] \ No newline at end of file diff --git a/S1/uucoco_#99/prompt.txt b/S1/uucoco_#99/prompt.txt new file mode 100644 index 0000000..4e26a5a --- /dev/null +++ b/S1/uucoco_#99/prompt.txt @@ -0,0 +1,53 @@ +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. +PyTorch C++/CUDA Extension: Inline compilation using torch.utils.cpp_extension.load_inline. + +Two‑Stage Custom CUDA Kernel: + +Parallel L1 Difference Reduction: Computes per‑batch L1 distance between two tensors (img1/img2 and z1/z2) using shared‑memory reduction. + +Ratio Computation Kernel: Calculates z_diff / (img_diff + eps) element‑wise. + +Shared‑Memory Parallel Reduction: Uses block‑level reduction with __shared__ memory and a tree‑based sum pattern. + +Batch‑Level Parallelism: Each batch processed by a separate CUDA block in the reduction step. + +Automatic Mean Reduction: Returns the mean of the per‑batch ratio values directly from the CUDA wrapper. + + + + +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 + + +class Model(nn.Module): + def __init__(self, eps=1e-5): + super().__init__() + self.eps = eps + + def forward(self, img1: torch.Tensor, img2: torch.Tensor, z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor: + img_diff = torch.abs(img1 - img2).view(img1.size(0), -1).mean(dim=1) + z_diff = torch.abs(z1 - z2).view(z1.size(0), -1).mean(dim=1) + + loss = z_diff / (img_diff + self.eps) + return loss.mean() + + +batch_size = 32 +c, h, w = 3, 64, 64 +z_dim = 128 + + +def get_inputs(): + img1 = torch.randn(batch_size, c, h, w, dtype=torch.float32) + img2 = torch.randn(batch_size, c, h, w, dtype=torch.float32) + z1 = torch.randn(batch_size, z_dim, dtype=torch.float32) + z2 = torch.randn(batch_size, z_dim, dtype=torch.float32) + return [img1, img2, z1, z2] + + +def get_init_inputs(): + return [1e-5] \ No newline at end of file diff --git a/S1/uucoco_#99/run_code.py b/S1/uucoco_#99/run_code.py new file mode 100644 index 0000000..040a3d6 --- /dev/null +++ b/S1/uucoco_#99/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from ModeSeekingLoss_torch import Model, get_inputs, get_init_inputs +from ModeSeekingLoss_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