finish QlearningLoss #103

This commit is contained in:
uucoco 2025-12-10 19:29:49 +08:00
parent 10eed82956
commit d66bd454b6
4 changed files with 305 additions and 0 deletions

View File

@ -0,0 +1,129 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, gamma):
super().__init__()
self.gamma = gamma.item() if isinstance(gamma, torch.Tensor) else gamma
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor dqn_loss_cuda(
torch::Tensor q_values,
torch::Tensor actions,
torch::Tensor rewards,
torch::Tensor next_q_values,
torch::Tensor dones,
float gamma);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void dqn_loss_kernel(
const float* __restrict__ q_values,
const long* __restrict__ actions,
const float* __restrict__ rewards,
const float* __restrict__ next_q_values,
const float* __restrict__ dones,
float* __restrict__ output,
float gamma,
int batch_size,
int action_dim)
{
extern __shared__ float sdata[];
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int gridSize = blockDim.x * gridDim.x;
float local_sum = 0.0f;
while (i < batch_size) {
int row_offset = i * action_dim;
long action = actions[i];
float q_pred = q_values[row_offset + action];
float max_next_q = -1e20f;
for (int a = 0; a < action_dim; ++a) {
float val = next_q_values[row_offset + a];
if (val > max_next_q) {
max_next_q = val;
}
}
float q_target = rewards[i] + gamma * max_next_q * (1.0f - dones[i]);
float diff = q_pred - q_target;
local_sum += diff * diff;
i += gridSize;
}
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] / batch_size);
}
}
torch::Tensor dqn_loss_cuda(
torch::Tensor q_values,
torch::Tensor actions,
torch::Tensor rewards,
torch::Tensor next_q_values,
torch::Tensor dones,
float gamma)
{
auto q_values_c = q_values.contiguous();
auto actions_c = actions.contiguous();
auto rewards_c = rewards.contiguous();
auto next_q_values_c = next_q_values.contiguous();
auto dones_c = dones.contiguous();
int batch_size = q_values_c.size(0);
int action_dim = q_values_c.size(1);
auto output = torch::zeros({1}, q_values.options());
const int threads = 256;
const int blocks = min((batch_size + threads - 1) / threads, 1024);
const int shared_mem = threads * sizeof(float);
dqn_loss_kernel<<<blocks, threads, shared_mem>>>(
q_values_c.data_ptr<float>(),
actions_c.data_ptr<long>(),
rewards_c.data_ptr<float>(),
next_q_values_c.data_ptr<float>(),
dones_c.data_ptr<float>(),
output.data_ptr<float>(),
gamma,
batch_size,
action_dim
);
return output[0];
}
"""
self.op = load_inline(
name="dqn_loss_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["dqn_loss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, q_values, actions, rewards, next_q_values, dones):
return self.op.dqn_loss_cuda(q_values, actions, rewards, next_q_values, dones, self.gamma)

View File

@ -0,0 +1,34 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, gamma):
super(Model, self).__init__()
self.gamma = gamma
def forward(self, q_values: torch.Tensor, actions: torch.Tensor, rewards: torch.Tensor, next_q_values: torch.Tensor,
dones: torch.Tensor) -> torch.Tensor:
batch_size = q_values.shape[0]
q_pred = q_values[torch.arange(batch_size), actions.long()]
q_target = rewards + self.gamma * next_q_values.max(dim=1)[0] * (1 - dones)
loss = ((q_pred - q_target) ** 2).mean()
return loss
batch_size = 32
action_dim = 4
def get_inputs():
q_values = torch.randn(batch_size, action_dim)
actions = torch.randint(0, action_dim, (batch_size,))
rewards = torch.randn(batch_size)
next_q_values = torch.randn(batch_size, action_dim)
dones = torch.randint(0, 2, (batch_size,)).float()
return [q_values, actions, rewards, next_q_values, dones]
def get_init_inputs():
gamma = torch.tensor(0.99)
return [gamma]

65
S1/uucoco_#103/prompt.txt Normal file
View File

@ -0,0 +1,65 @@
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.
SharedMemory Parallel Reduction: Uses extern __shared__ and treebased reduction to sum loss across threads.
Strided Loop for Large Batches: Each thread processes multiple batch items with stride gridDim.x * blockDim.x.
DQN TDError Calculation:
Extracts Qvalue for taken action via indexing.
Computes max(next_q_values) across action dimension (serial loop).
Target: reward + gamma * max_next_q * (1 - done).
Loss: squared difference (q_pred - q_target)^2.
Atomic Finalization: atomicAdd accumulates blockaveraged loss into a singleelement tensor.
Block/Thread Setup: 256 threads per block, up to 1024 blocks, with dynamic shared memory.
Hyperparameter Handling: Constructor takes gamma (converted from Tensor if needed) and passes it to the kernel.
Mixed Datatypes: Uses long for action indices and float for Qvalues, rewards, and dones.
Memory Contiguity: Ensures all input tensors are contiguous 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, gamma):
super(Model, self).__init__()
self.gamma = gamma
def forward(self, q_values: torch.Tensor, actions: torch.Tensor, rewards: torch.Tensor, next_q_values: torch.Tensor,
dones: torch.Tensor) -> torch.Tensor:
batch_size = q_values.shape[0]
q_pred = q_values[torch.arange(batch_size), actions.long()]
q_target = rewards + self.gamma * next_q_values.max(dim=1)[0] * (1 - dones)
loss = ((q_pred - q_target) ** 2).mean()
return loss
batch_size = 32
action_dim = 4
def get_inputs():
q_values = torch.randn(batch_size, action_dim)
actions = torch.randint(0, action_dim, (batch_size,))
rewards = torch.randn(batch_size)
next_q_values = torch.randn(batch_size, action_dim)
dones = torch.randint(0, 2, (batch_size,)).float()
return [q_values, actions, rewards, next_q_values, dones]
def get_init_inputs():
gamma = torch.tensor(0.99)
return [gamma]

View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from QLearningLoss_torch import Model, get_inputs, get_init_inputs
from QLearningLoss_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()