From d66bd454b60d6c389fa62eb281194fd4a28e6e82 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:29:49 +0800 Subject: [PATCH] finish QlearningLoss #103 --- S1/uucoco_#103/QLearningLoss_cuda.py | 129 ++++++++++++++++++++++++++ S1/uucoco_#103/QLearningLoss_torch.py | 34 +++++++ S1/uucoco_#103/prompt.txt | 65 +++++++++++++ S1/uucoco_#103/run_code.py | 77 +++++++++++++++ 4 files changed, 305 insertions(+) create mode 100644 S1/uucoco_#103/QLearningLoss_cuda.py create mode 100644 S1/uucoco_#103/QLearningLoss_torch.py create mode 100644 S1/uucoco_#103/prompt.txt create mode 100644 S1/uucoco_#103/run_code.py diff --git a/S1/uucoco_#103/QLearningLoss_cuda.py b/S1/uucoco_#103/QLearningLoss_cuda.py new file mode 100644 index 0000000..e836d57 --- /dev/null +++ b/S1/uucoco_#103/QLearningLoss_cuda.py @@ -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 + #include + + __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<<>>( + q_values_c.data_ptr(), + actions_c.data_ptr(), + rewards_c.data_ptr(), + next_q_values_c.data_ptr(), + dones_c.data_ptr(), + output.data_ptr(), + 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) \ No newline at end of file diff --git a/S1/uucoco_#103/QLearningLoss_torch.py b/S1/uucoco_#103/QLearningLoss_torch.py new file mode 100644 index 0000000..3f899c9 --- /dev/null +++ b/S1/uucoco_#103/QLearningLoss_torch.py @@ -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] \ No newline at end of file diff --git a/S1/uucoco_#103/prompt.txt b/S1/uucoco_#103/prompt.txt new file mode 100644 index 0000000..5b06b7b --- /dev/null +++ b/S1/uucoco_#103/prompt.txt @@ -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. + +Shared‑Memory Parallel Reduction: Uses extern __shared__ and tree‑based reduction to sum loss across threads. + +Strided Loop for Large Batches: Each thread processes multiple batch items with stride gridDim.x * blockDim.x. + +DQN TD‑Error Calculation: + +Extracts Q‑value 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 block‑averaged loss into a single‑element 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 Q‑values, 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] \ No newline at end of file diff --git a/S1/uucoco_#103/run_code.py b/S1/uucoco_#103/run_code.py new file mode 100644 index 0000000..840a4fc --- /dev/null +++ b/S1/uucoco_#103/run_code.py @@ -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() \ No newline at end of file