finish PPOLoss #102

This commit is contained in:
uucoco 2025-12-10 19:28:46 +08:00
parent 10eed82956
commit da60705645
4 changed files with 228 additions and 0 deletions

View File

@ -0,0 +1,74 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__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<<<blocks, threads>>>(
new_log_probs.data_ptr<float>(),
old_log_probs.data_ptr<float>(),
advantages.data_ptr<float>(),
output.data_ptr<float>(),
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)

View File

@ -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]

53
S1/uucoco_#102/prompt.txt Normal file
View File

@ -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]

View File

@ -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()