From 751b24be1bb38954707e5c927f10e1a7b500206f Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 11 Nov 2025 19:05:29 +0800 Subject: [PATCH] fixes mseloss #28 --- S1/28/mseloss_cuda.py | 123 +++++++++++++++++++++++++++++++++++++++++ S1/28/mseloss_torch.py | 23 ++++++++ S1/28/prompt.txt | 30 ++++++++++ S1/28/run_code.py | 88 +++++++++++++++++++++++++++++ 4 files changed, 264 insertions(+) create mode 100644 S1/28/mseloss_cuda.py create mode 100644 S1/28/mseloss_torch.py create mode 100644 S1/28/prompt.txt create mode 100644 S1/28/run_code.py diff --git a/S1/28/mseloss_cuda.py b/S1/28/mseloss_cuda.py new file mode 100644 index 0000000..9f24384 --- /dev/null +++ b/S1/28/mseloss_cuda.py @@ -0,0 +1,123 @@ +# mseloss_cuda.py +import torch +from torch.utils.cpp_extension import load_inline +from mseloss_torch import BATCH_SIZE, DIM + +class ModelNew(torch.nn.Module): + + def __init__(self): + super().__init__() + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + #include + + torch::Tensor mse_forward_cuda(torch::Tensor pred, torch::Tensor target); + """ + + cuda_source = """ + #include + #include + + #define BLOCK_SIZE 1024 + #define VEC_SIZE 4 + + __global__ void mse_fused_reduction_kernel( + const float* __restrict__ pred, + const float* __restrict__ target, + double* __restrict__ output_sum, + int N_elements + ) { + __shared__ double sh_sum[BLOCK_SIZE]; + + double thread_sum = 0.0; + + int N_vec = N_elements / VEC_SIZE; + int grid_stride_vec = gridDim.x * blockDim.x; + + const float4* __restrict__ pred4 = (const float4*)pred; + const float4* __restrict__ target4 = (const float4*)target; + + + for (int idx_vec = blockIdx.x * blockDim.x + threadIdx.x; + idx_vec < N_vec; + idx_vec += grid_stride_vec) + { + + float4 p4 = pred4[idx_vec]; + float4 t4 = target4[idx_vec]; + + double diff1 = (double)p4.x - (double)t4.x; + thread_sum += diff1 * diff1; + + double diff2 = (double)p4.y - (double)t4.y; + thread_sum += diff2 * diff2; + + double diff3 = (double)p4.z - (double)t4.z; + thread_sum += diff3 * diff3; + + double diff4 = (double)p4.w - (double)t4.w; + thread_sum += diff4 * diff4; + } + + sh_sum[threadIdx.x] = thread_sum; + __syncthreads(); + + for (int s = BLOCK_SIZE / 2; s > 0; s /= 2) { + if (threadIdx.x < s) { + sh_sum[threadIdx.x] += sh_sum[threadIdx.x + s]; + } + __syncthreads(); + } + + if (threadIdx.x == 0) { + output_sum[blockIdx.x] = sh_sum[0]; + } + } + + torch::Tensor mse_forward_cuda(torch::Tensor pred, torch::Tensor target) { + TORCH_CHECK(pred.is_cuda() && target.is_cuda(), "Inputs must be CUDA tensors"); + + pred = pred.contiguous(); + target = target.contiguous(); + + int N_elements = pred.numel(); + + if (N_elements % VEC_SIZE != 0) { + TORCH_CHECK(false, "Total elements must be divisible by VEC_SIZE (4) for optimization."); + } + + const int block_size = BLOCK_SIZE; + const int grid_size = 256; + + auto partial_sum_output = torch::empty({grid_size}, pred.options().dtype(torch::kFloat64)); + + mse_fused_reduction_kernel<<>>( + pred.data_ptr(), + target.data_ptr(), + partial_sum_output.data_ptr(), + N_elements + ); + + + double total_sum = partial_sum_output.sum().item(); + + float mean_loss = (float)(total_sum / N_elements); + + return torch::tensor(mean_loss, pred.options()); + } + """ + + self.mse_op = load_inline( + name="mse_fused_vectorized_op", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["mse_forward_cuda"], + extra_cuda_cflags=["-O3", "--use_fast_math"], + verbose=True + ) + + def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + return self.mse_op.mse_forward_cuda(pred, target) \ No newline at end of file diff --git a/S1/28/mseloss_torch.py b/S1/28/mseloss_torch.py new file mode 100644 index 0000000..2e15f4f --- /dev/null +++ b/S1/28/mseloss_torch.py @@ -0,0 +1,23 @@ +# mseloss_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + + +BATCH_SIZE = 16 +DIM = 16384 * 16 + +class Model(nn.Module): + + def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + # F.mse_loss 默认返回 mean reduction + return F.mse_loss(pred, target, reduction='mean') + +def get_inputs(): + + pred = torch.randn(BATCH_SIZE, DIM, dtype=torch.float32) + target = pred + torch.rand_like(pred) * 0.1 + return [pred, target] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/28/prompt.txt b/S1/28/prompt.txt new file mode 100644 index 0000000..bb1b973 --- /dev/null +++ b/S1/28/prompt.txt @@ -0,0 +1,30 @@ +You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination. + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: + +```python +# mseloss_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + + +BATCH_SIZE = 16 +DIM = 16384 * 16 + +class Model(nn.Module): + + def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + # F.mse_loss 默认返回 mean reduction + return F.mse_loss(pred, target, reduction='mean') + +def get_inputs(): + + pred = torch.randn(BATCH_SIZE, DIM, dtype=torch.float32) + target = pred + torch.rand_like(pred) * 0.1 + return [pred, target] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/28/run_code.py b/S1/28/run_code.py new file mode 100644 index 0000000..0f531a7 --- /dev/null +++ b/S1/28/run_code.py @@ -0,0 +1,88 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from mseloss_torch import Model, get_inputs, get_init_inputs +from mseloss_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) + + # 更严格的精度检查 + abs_diff = (output_torch - output_cuda).abs() + max_diff = abs_diff.max().item() + mean_diff = abs_diff.mean().item() + + print(f"最大差异: {max_diff:.6f}") + print(f"平均差异: {mean_diff:.6f}") + + precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05) + if precision_flag: + print("✅ 精度对齐:两个模型的输出结果非常接近。") + else: + print("❌ 精度不一致!") + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量 + + # Warm up + for _ in range(100): + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA ReLU 平均执行时间: {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