forked from ccf-ai-infra/GPUCodeForces
finish BellmanLoss #80
This commit is contained in:
parent
10eed82956
commit
d0cda4a9f1
|
|
@ -0,0 +1,103 @@
|
|||
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 bellman_loss_kernel(
|
||||
const float* __restrict__ q_values,
|
||||
const int64_t* __restrict__ actions,
|
||||
const float* __restrict__ rewards,
|
||||
const float* __restrict__ next_q_values,
|
||||
const float* __restrict__ dones,
|
||||
float* __restrict__ output,
|
||||
int batch_size,
|
||||
int num_actions,
|
||||
float gamma
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx < batch_size) {
|
||||
int64_t action = actions[idx];
|
||||
|
||||
float curr_q = q_values[idx * num_actions + action];
|
||||
|
||||
float max_next_q = -1e20f; // -inf
|
||||
int next_q_offset = idx * num_actions;
|
||||
for (int a = 0; a < num_actions; ++a) {
|
||||
float val = next_q_values[next_q_offset + a];
|
||||
if (val > max_next_q) {
|
||||
max_next_q = val;
|
||||
}
|
||||
}
|
||||
|
||||
float target = rewards[idx] + gamma * max_next_q * (1.0f - dones[idx]);
|
||||
|
||||
float diff = curr_q - target;
|
||||
output[idx] = diff * diff;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor bellman_loss_cuda(
|
||||
torch::Tensor q_values,
|
||||
torch::Tensor actions,
|
||||
torch::Tensor rewards,
|
||||
torch::Tensor next_q_values,
|
||||
torch::Tensor dones,
|
||||
float gamma
|
||||
) {
|
||||
int batch_size = q_values.size(0);
|
||||
int num_actions = q_values.size(1);
|
||||
|
||||
auto output = at::empty({batch_size}, q_values.options());
|
||||
|
||||
int threads = 256;
|
||||
int blocks = (batch_size + threads - 1) / threads;
|
||||
|
||||
bellman_loss_kernel<<<blocks, threads>>>(
|
||||
q_values.data_ptr<float>(),
|
||||
actions.data_ptr<int64_t>(),
|
||||
rewards.data_ptr<float>(),
|
||||
next_q_values.data_ptr<float>(),
|
||||
dones.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch_size,
|
||||
num_actions,
|
||||
gamma
|
||||
);
|
||||
|
||||
return output.mean();
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor bellman_loss_cuda(
|
||||
torch::Tensor q_values,
|
||||
torch::Tensor actions,
|
||||
torch::Tensor rewards,
|
||||
torch::Tensor next_q_values,
|
||||
torch::Tensor dones,
|
||||
float gamma
|
||||
);
|
||||
"""
|
||||
|
||||
bellman_loss = load_inline(
|
||||
name="bellman_loss",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["bellman_loss_cuda"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, gamma=0.99):
|
||||
super(ModelNew, self).__init__()
|
||||
self.gamma = gamma
|
||||
|
||||
def forward(self, q_values, actions, rewards, next_q_values, dones):
|
||||
return bellman_loss.bellman_loss_cuda(
|
||||
q_values, actions, rewards, next_q_values, dones, self.gamma
|
||||
)
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, gamma=0.99):
|
||||
super(Model, self).__init__()
|
||||
self.gamma = gamma
|
||||
|
||||
def forward(self, q_values, actions, rewards, next_q_values, dones):
|
||||
curr_q = q_values.gather(1, actions.unsqueeze(1)).squeeze(1)
|
||||
next_q_max = next_q_values.max(1)[0]
|
||||
target = rewards + self.gamma * next_q_max * (1.0 - dones)
|
||||
loss = (curr_q - target) ** 2
|
||||
return loss.mean()
|
||||
|
||||
batch_size = 1024
|
||||
num_actions = 6
|
||||
|
||||
def get_inputs():
|
||||
q_values = torch.randn(batch_size, num_actions, requires_grad=True)
|
||||
actions = torch.randint(0, num_actions, (batch_size,))
|
||||
rewards = torch.randn(batch_size)
|
||||
next_q_values = torch.randn(batch_size, num_actions)
|
||||
dones = torch.zeros(batch_size) # float 0.0 or 1.0
|
||||
return [q_values, actions, rewards, next_q_values, dones]
|
||||
|
||||
def get_init_inputs():
|
||||
return [0.99]
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
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.
|
||||
Technologies Used in This Code
|
||||
Core Libraries & Frameworks
|
||||
PyTorch: Deep learning framework
|
||||
|
||||
CUDA: NVIDIA's parallel computing platform for GPU acceleration
|
||||
|
||||
C++: For high-performance kernel implementation
|
||||
|
||||
PyTorch Specific Components
|
||||
torch.nn.Module: Base class for neural network modules
|
||||
|
||||
torch.utils.cpp_extension.load_inline: For inline compilation of CUDA/C++ extensions
|
||||
|
||||
PyTorch Tensors: Multi-dimensional arrays with automatic differentiation
|
||||
|
||||
CUDA/C++ Implementation Details
|
||||
CUDA Kernels: Custom GPU kernel (bellman_loss_kernel)
|
||||
|
||||
CUDA Thread Management: Block/grid configuration for parallel execution
|
||||
|
||||
Memory Access Patterns: Using __restrict__ keyword for optimized memory access
|
||||
|
||||
Parallel Reduction: For finding maximum Q-value across actions
|
||||
|
||||
Reinforcement Learning Components
|
||||
Bellman Equation: Q-learning update rule
|
||||
|
||||
Temporal Difference (TD) Error: Difference between current Q-value and target Q-value
|
||||
|
||||
Experience Components: Q-values, actions, rewards, next states, done flags
|
||||
|
||||
Discount Factor (gamma): Future reward discounting
|
||||
|
||||
Performance Optimizations
|
||||
GPU Parallelization: Batch-level parallel processing
|
||||
|
||||
In-place Computation: Direct tensor operations without unnecessary copies
|
||||
|
||||
Fused Operations: Single kernel for complete loss computation
|
||||
|
||||
|
||||
|
||||
|
||||
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=0.99):
|
||||
super(Model, self).__init__()
|
||||
self.gamma = gamma
|
||||
|
||||
def forward(self, q_values, actions, rewards, next_q_values, dones):
|
||||
curr_q = q_values.gather(1, actions.unsqueeze(1)).squeeze(1)
|
||||
next_q_max = next_q_values.max(1)[0]
|
||||
target = rewards + self.gamma * next_q_max * (1.0 - dones)
|
||||
loss = (curr_q - target) ** 2
|
||||
return loss.mean()
|
||||
|
||||
batch_size = 1024
|
||||
num_actions = 6
|
||||
|
||||
def get_inputs():
|
||||
q_values = torch.randn(batch_size, num_actions, requires_grad=True)
|
||||
actions = torch.randint(0, num_actions, (batch_size,))
|
||||
rewards = torch.randn(batch_size)
|
||||
next_q_values = torch.randn(batch_size, num_actions)
|
||||
dones = torch.zeros(batch_size) # float 0.0 or 1.0
|
||||
return [q_values, actions, rewards, next_q_values, dones]
|
||||
|
||||
def get_init_inputs():
|
||||
return [0.99]
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from BellmanLoss_torch import Model, get_inputs, get_init_inputs
|
||||
from BellmanLoss_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()
|
||||
Loading…
Reference in New Issue