Merge pull request 'finish ValueLoss #115' (#1021) from uucoco/GPUCodeForces:uucoco115 into main

This commit is contained in:
Kuohais 2025-12-11 16:30:29 +08:00
commit fe79b16a4f
4 changed files with 230 additions and 0 deletions

View File

@ -0,0 +1,86 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor value_loss_cuda(torch::Tensor values, torch::Tensor returns);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void value_loss_kernel(
const float* __restrict__ values,
const float* __restrict__ returns,
float* __restrict__ output,
int n)
{
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 < n) {
float diff = values[i] - returns[i];
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] / n);
}
}
torch::Tensor value_loss_cuda(torch::Tensor values, torch::Tensor returns) {
auto values_c = values.contiguous();
auto returns_c = returns.contiguous();
int n = values_c.numel();
auto output = torch::zeros({1}, values.options());
const int threads = 256;
const int blocks = min((n + threads - 1) / threads, 1024);
const int shared_mem = threads * sizeof(float);
value_loss_kernel<<<blocks, threads, shared_mem>>>(
values_c.data_ptr<float>(),
returns_c.data_ptr<float>(),
output.data_ptr<float>(),
n
);
return output[0];
}
"""
self.op = load_inline(
name="value_loss_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["value_loss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, values, returns):
return self.op.value_loss_cuda(values, returns)

View File

@ -0,0 +1,24 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, values: torch.Tensor, returns: torch.Tensor) -> torch.Tensor:
loss = ((values - returns) ** 2).mean()
return loss
batch_size = 32
def get_inputs():
values = torch.randn(batch_size)
returns = torch.randn(batch_size)
return [values, returns]
def get_init_inputs():
return []

43
S1/uucoco_#115/prompt.txt Normal file
View File

@ -0,0 +1,43 @@
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__ memory and treebased reduction to sum squared differences.
Strided Loop for Scalability: Each thread processes multiple elements with stride gridDim.x * blockDim.x.
ValueFunction MSE Loss: Computes squared error (values - returns)^2 per element.
Atomic Finalization: atomicAdd accumulates the blockaveraged loss into a singleelement output tensor.
Block/Thread Configuration: 256 threads per block, up to 1024 blocks, with dynamic shared memory allocation.
Memory Contiguity: Ensures 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):
super(Model, self).__init__()
def forward(self, values: torch.Tensor, returns: torch.Tensor) -> torch.Tensor:
loss = ((values - returns) ** 2).mean()
return loss
batch_size = 32
def get_inputs():
values = torch.randn(batch_size)
returns = torch.randn(batch_size)
return [values, returns]
def get_init_inputs():
return []

View File

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