From da60705645ec73e43f0bccbe2ec35f1bd7905764 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:28:46 +0800 Subject: [PATCH] finish PPOLoss #102 --- S1/uucoco_#102/PPOLoss_cuda.py | 74 +++++++++++++++++++++++++++++++ S1/uucoco_#102/PPOLoss_torch.py | 24 ++++++++++ S1/uucoco_#102/prompt.txt | 53 +++++++++++++++++++++++ S1/uucoco_#102/run_code.py | 77 +++++++++++++++++++++++++++++++++ 4 files changed, 228 insertions(+) create mode 100644 S1/uucoco_#102/PPOLoss_cuda.py create mode 100644 S1/uucoco_#102/PPOLoss_torch.py create mode 100644 S1/uucoco_#102/prompt.txt create mode 100644 S1/uucoco_#102/run_code.py diff --git a/S1/uucoco_#102/PPOLoss_cuda.py b/S1/uucoco_#102/PPOLoss_cuda.py new file mode 100644 index 0000000..5c6fd92 --- /dev/null +++ b/S1/uucoco_#102/PPOLoss_cuda.py @@ -0,0 +1,74 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__global__ void ppo_loss_kernel( + const float* __restrict__ new_log_probs, + const float* __restrict__ old_log_probs, + const float* __restrict__ advantages, + float* __restrict__ output, + float clip_param, + int n +) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < n) { + float ratio = expf(new_log_probs[idx] - old_log_probs[idx]); + float adv = advantages[idx]; + + float surr1 = ratio * adv; + + float low = 1.0f - clip_param; + float high = 1.0f + clip_param; + float ratio_clipped = fminf(fmaxf(ratio, low), high); + + float surr2 = ratio_clipped * adv; + + output[idx] = -fminf(surr1, surr2); + } +} + +torch::Tensor ppo_loss_cuda(torch::Tensor new_log_probs, torch::Tensor old_log_probs, torch::Tensor advantages, float clip_param) { + int n = new_log_probs.numel(); + + auto output = at::empty_like(new_log_probs); + + int threads = 256; + int blocks = (n + threads - 1) / threads; + + ppo_loss_kernel<<>>( + new_log_probs.data_ptr(), + old_log_probs.data_ptr(), + advantages.data_ptr(), + output.data_ptr(), + clip_param, + n + ); + + return output.mean(); +} +""" + +cpp_source = """ +torch::Tensor ppo_loss_cuda(torch::Tensor new_log_probs, torch::Tensor old_log_probs, torch::Tensor advantages, float clip_param); +""" + +ppo_loss = load_inline( + name="ppo_loss", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["ppo_loss_cuda"], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self, clip_param=0.2): + super(ModelNew, self).__init__() + self.clip_param = clip_param + + def forward(self, new_log_probs, old_log_probs, advantages): + return ppo_loss.ppo_loss_cuda(new_log_probs, old_log_probs, advantages, self.clip_param) \ No newline at end of file diff --git a/S1/uucoco_#102/PPOLoss_torch.py b/S1/uucoco_#102/PPOLoss_torch.py new file mode 100644 index 0000000..e84c561 --- /dev/null +++ b/S1/uucoco_#102/PPOLoss_torch.py @@ -0,0 +1,24 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, clip_param=0.2): + super(Model, self).__init__() + self.clip_param = clip_param + + def forward(self, new_log_probs, old_log_probs, advantages): + ratio = torch.exp(new_log_probs - old_log_probs) + surr1 = ratio * advantages + surr2 = torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * advantages + return -torch.min(surr1, surr2).mean() + +batch_size = 1024 + +def get_inputs(): + new_log_probs = torch.randn(batch_size, requires_grad=True) + old_log_probs = torch.randn(batch_size) + advantages = torch.randn(batch_size) + return [new_log_probs, old_log_probs, advantages] + +def get_init_inputs(): + return [0.2] diff --git a/S1/uucoco_#102/prompt.txt b/S1/uucoco_#102/prompt.txt new file mode 100644 index 0000000..6aa2e77 --- /dev/null +++ b/S1/uucoco_#102/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. +Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline + +Proximal Policy Optimization (PPO) loss computation (clipped surrogate objective) + +Probability ratio calculation: exp(new_log_prob - old_log_prob) + +Clipping mechanism to bound ratio within [1-ε, 1+ε] + +Advantage-weighted objective: min(ratio·A, clip(ratio)·A) + +Element-wise parallelization across all timesteps/actions + +Fixed block size (256 threads) with dynamic grid sizing + +Contiguous tensor handling for memory coalescing + +Mean reduction across all elements + +Numerical stability via log-prob difference instead of division + + + + + + +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, clip_param=0.2): + super(Model, self).__init__() + self.clip_param = clip_param + + def forward(self, new_log_probs, old_log_probs, advantages): + ratio = torch.exp(new_log_probs - old_log_probs) + surr1 = ratio * advantages + surr2 = torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * advantages + return -torch.min(surr1, surr2).mean() + +batch_size = 1024 + +def get_inputs(): + new_log_probs = torch.randn(batch_size, requires_grad=True) + old_log_probs = torch.randn(batch_size) + advantages = torch.randn(batch_size) + return [new_log_probs, old_log_probs, advantages] + +def get_init_inputs(): + return [0.2] diff --git a/S1/uucoco_#102/run_code.py b/S1/uucoco_#102/run_code.py new file mode 100644 index 0000000..7ad5c7c --- /dev/null +++ b/S1/uucoco_#102/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from PPOLoss_torch import Model, get_inputs, get_init_inputs +from PPOLoss_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