From 398b36178f9db9a044ed84ea8f2e4b728752d396 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:26:50 +0800 Subject: [PATCH] finish MsewithLogitLoss #100 --- S1/uucoco_#100/MsewithLogitLoss_cuda.py | 147 +++++++++++++++++++++++ S1/uucoco_#100/MsewithLogitLoss_torch.py | 26 ++++ S1/uucoco_#100/prompt.txt | 53 ++++++++ S1/uucoco_#100/run_code.py | 77 ++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 S1/uucoco_#100/MsewithLogitLoss_cuda.py create mode 100644 S1/uucoco_#100/MsewithLogitLoss_torch.py create mode 100644 S1/uucoco_#100/prompt.txt create mode 100644 S1/uucoco_#100/run_code.py diff --git a/S1/uucoco_#100/MsewithLogitLoss_cuda.py b/S1/uucoco_#100/MsewithLogitLoss_cuda.py new file mode 100644 index 00000000..9f52e55a --- /dev/null +++ b/S1/uucoco_#100/MsewithLogitLoss_cuda.py @@ -0,0 +1,147 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, reduction='mean'): + super().__init__() + self.reduction = reduction + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + torch::Tensor logits_loss_cuda( + torch::Tensor student, torch::Tensor teacher, + int reduction_mode); + """ + + cuda_source = """ + #include + #include + + __global__ void logits_loss_reduction_kernel( + const float* __restrict__ student, + const float* __restrict__ teacher, + float* __restrict__ output, + const int64_t n_elements) + { + extern __shared__ float sdata[]; + unsigned int tid = threadIdx.x; + unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; + unsigned int gridSize = blockDim.x * gridDim.x; + + float local_sum = 0.0f; + + int64_t n_vec = n_elements / 4; + const float4* stu_4 = reinterpret_cast(student); + const float4* tea_4 = reinterpret_cast(teacher); + + for (int64_t i = idx; i < n_vec; i += gridSize) { + float4 s = stu_4[i]; + float4 t = tea_4[i]; + + float d1 = s.x - t.x; + float d2 = s.y - t.y; + float d3 = s.z - t.z; + float d4 = s.w - t.w; + + local_sum += d1 * d1 + d2 * d2 + d3 * d3 + d4 * d4; + } + + for (int64_t i = n_vec * 4 + idx; i < n_elements; i += gridSize) { + float diff = student[i] - teacher[i]; + local_sum += diff * diff; + } + + sdata[tid] = local_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) { + atomicAdd(output, sdata[0]); + } + } + + __global__ void logits_loss_elementwise_kernel( + const float* __restrict__ student, + const float* __restrict__ teacher, + float* __restrict__ output, + const int64_t n_elements) + { + int64_t idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < n_elements) { + float diff = student[idx] - teacher[idx]; + output[idx] = diff * diff; + } + } + + torch::Tensor logits_loss_cuda( + torch::Tensor student, torch::Tensor teacher, + int reduction_mode) + { + TORCH_CHECK(student.is_cuda(), "student must be on CUDA"); + TORCH_CHECK(teacher.is_cuda(), "teacher must be on CUDA"); + + int64_t n = student.numel(); + TORCH_CHECK(teacher.numel() == n, "Size mismatch"); + + auto student_c = student.contiguous(); + auto teacher_c = teacher.contiguous(); + + if (reduction_mode == 0) { + auto output = torch::empty_like(student_c); + int threads = 256; + int blocks = (n + threads - 1) / threads; + logits_loss_elementwise_kernel<<>>( + student_c.data_ptr(), teacher_c.data_ptr(), + output.data_ptr(), n + ); + return output; + } else { + auto output = torch::zeros({1}, student.options()); + int threads = 256; + int blocks = min((int64_t)((n + threads - 1) / threads), (int64_t)1024); + size_t shared_mem = threads * sizeof(float); + + logits_loss_reduction_kernel<<>>( + student_c.data_ptr(), teacher_c.data_ptr(), + output.data_ptr(), n + ); + + if (reduction_mode == 1) { + return output / (float)n; + } else { + return output; + } + } + } + """ + + self.op = load_inline( + name="logits_loss_op", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["logits_loss_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor: + if not logits_student.is_cuda: + logits_student = logits_student.cuda() + logits_teacher = logits_teacher.cuda() + + mode = 0 + if self.reduction == 'mean': + mode = 1 + elif self.reduction == 'sum': + mode = 2 + + return self.op.logits_loss_cuda(logits_student, logits_teacher, mode) \ No newline at end of file diff --git a/S1/uucoco_#100/MsewithLogitLoss_torch.py b/S1/uucoco_#100/MsewithLogitLoss_torch.py new file mode 100644 index 00000000..278fb8de --- /dev/null +++ b/S1/uucoco_#100/MsewithLogitLoss_torch.py @@ -0,0 +1,26 @@ +import torch +import torch.nn as nn + + +class Model(nn.Module): + def __init__(self, reduction='mean'): + super().__init__() + self.reduction = reduction + self.mse_loss = nn.MSELoss(reduction=reduction) + + def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor: + return self.mse_loss(logits_student, logits_teacher) + + +batch_size = 256 +num_classes = 1000 + + +def get_inputs(): + logits_student = torch.randn(batch_size, num_classes, dtype=torch.float32) + logits_teacher = torch.randn(batch_size, num_classes, dtype=torch.float32) + return [logits_student, logits_teacher] + + +def get_init_inputs(): + return ['mean'] \ No newline at end of file diff --git a/S1/uucoco_#100/prompt.txt b/S1/uucoco_#100/prompt.txt new file mode 100644 index 00000000..516ad4b9 --- /dev/null +++ b/S1/uucoco_#100/prompt.txt @@ -0,0 +1,53 @@ +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. + +Dual‑Kernel Strategy: + +Element‑wise Kernel: Computes per‑element squared difference (student - teacher)^2 for reduction='none'. + +Vectorized Reduction Kernel: Uses float4 loads for high‑throughput, shared‑memory tree reduction for 'mean'/'sum'. + +Vectorized Processing: Main loop uses float4 (4‑element SIMD‑style) memory loads/stores for aligned data. + +Shared‑Memory Parallel Reduction: Tree‑based sum across threads with extern __shared__ memory. + +Atomic Finalization: atomicAdd accumulates block sums into a single‑element tensor. + +Reduction Mode Control: Python passes integer mode (0=none, 1=mean, 2=sum) to select kernel and post‑processing. + +Automatic GPU Transfer: Moves tensors to CUDA if not already on GPU. + +Block/Thread Configuration: 256 threads per block, grid size capped at 1024 for reduction kernel. + +Numerical Safety: Checks tensor sizes and CUDA device before kernel launch. + + + +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, reduction='mean'): + super().__init__() + self.reduction = reduction + self.mse_loss = nn.MSELoss(reduction=reduction) + + def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor: + return self.mse_loss(logits_student, logits_teacher) + + +batch_size = 256 +num_classes = 1000 + + +def get_inputs(): + logits_student = torch.randn(batch_size, num_classes, dtype=torch.float32) + logits_teacher = torch.randn(batch_size, num_classes, dtype=torch.float32) + return [logits_student, logits_teacher] + + +def get_init_inputs(): + return ['mean'] \ No newline at end of file diff --git a/S1/uucoco_#100/run_code.py b/S1/uucoco_#100/run_code.py new file mode 100644 index 00000000..bdfb13fc --- /dev/null +++ b/S1/uucoco_#100/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from MsewithLogitLoss_torch import Model, get_inputs, get_init_inputs +from MsewithLogitLoss_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