Merge pull request 'finish l1loss Operator #26' (#52) from ZZZJ/GPUCodeForces:l1loss into main

This commit is contained in:
Kuohais 2025-11-12 09:42:09 +08:00
commit 126ab19916
4 changed files with 322 additions and 0 deletions

179
S1/26/l1loss_cuda.py Normal file
View File

@ -0,0 +1,179 @@
# l1loss_cuda.py
import torch
from torch.utils.cpp_extension import load_inline
class ModelNew(torch.nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor l1_forward_cuda(torch::Tensor pred, torch::Tensor target);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#define BLOCK_SIZE 256
#define VEC_SIZE 4
#define WARP_SIZE 32
// Warp-level reduction using shuffle instructions
__device__ __forceinline__ float warp_reduce_sum(float val) {
#pragma unroll
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
val += __shfl_down_sync(0xffffffff, val, offset);
}
return val;
}
// Optimized L1 kernel with multiple improvements
__global__ void l1_optimized_kernel(
const float* __restrict__ pred,
const float* __restrict__ target,
float* __restrict__ output_sum,
int N_elements
) {
float thread_sum = 0.0f;
int N_vec = N_elements / VEC_SIZE;
int grid_stride_vec = gridDim.x * blockDim.x;
const float4* __restrict__ pred4 = reinterpret_cast<const float4*>(pred);
const float4* __restrict__ target4 = reinterpret_cast<const float4*>(target);
// Grid-stride loop with vectorized loads
for (int idx_vec = blockIdx.x * blockDim.x + threadIdx.x;
idx_vec < N_vec;
idx_vec += grid_stride_vec)
{
// Use read-only cache for better memory performance
float4 p4 = __ldg(&pred4[idx_vec]);
float4 t4 = __ldg(&target4[idx_vec]);
// Use fabsf() instead of std::abs() - much faster on GPU
// fabsf is a single instruction, while std::abs may have overhead
thread_sum += fabsf(p4.x - t4.x);
thread_sum += fabsf(p4.y - t4.y);
thread_sum += fabsf(p4.z - t4.z);
thread_sum += fabsf(p4.w - t4.w);
}
// Warp-level reduction (no shared memory for intra-warp)
thread_sum = warp_reduce_sum(thread_sum);
// Shared memory only for inter-warp reduction
__shared__ float warp_sums[BLOCK_SIZE / WARP_SIZE];
int lane = threadIdx.x % WARP_SIZE;
int warp_id = threadIdx.x / WARP_SIZE;
// First thread in each warp writes to shared memory
if (lane == 0) {
warp_sums[warp_id] = thread_sum;
}
__syncthreads();
// Final reduction by first warp
if (warp_id == 0) {
thread_sum = (threadIdx.x < BLOCK_SIZE / WARP_SIZE) ? warp_sums[lane] : 0.0f;
thread_sum = warp_reduce_sum(thread_sum);
if (threadIdx.x == 0) {
output_sum[blockIdx.x] = thread_sum;
}
}
}
// Final reduction kernel - sums up partial results on GPU
__global__ void final_reduction_kernel(
const float* __restrict__ partial_sums,
float* __restrict__ output,
int n
) {
__shared__ float sh_sum[BLOCK_SIZE];
float sum = 0.0f;
// Grid-stride loop to handle any number of partial sums
for (int i = threadIdx.x; i < n; i += blockDim.x) {
sum += partial_sums[i];
}
sh_sum[threadIdx.x] = sum;
__syncthreads();
// Tree reduction in shared memory
#pragma unroll
for (int s = BLOCK_SIZE / 2; s > 0; s /= 2) {
if (threadIdx.x < s) {
sh_sum[threadIdx.x] += sh_sum[threadIdx.x + s];
}
__syncthreads();
}
if (threadIdx.x == 0) {
output[0] = sh_sum[0];
}
}
torch::Tensor l1_forward_cuda(torch::Tensor pred, torch::Tensor target) {
TORCH_CHECK(pred.is_cuda() && target.is_cuda(), "Inputs must be CUDA tensors");
pred = pred.contiguous();
target = target.contiguous();
int N_elements = pred.numel();
TORCH_CHECK(N_elements % VEC_SIZE == 0,
"Total elements must be divisible by VEC_SIZE (4)");
// Adaptive grid size based on GPU architecture
const int block_size = BLOCK_SIZE;
int num_sms;
cudaDeviceGetAttribute(&num_sms, cudaDevAttrMultiProcessorCount, 0);
// Heuristic: 4 blocks per SM for good occupancy
const int grid_size = min(num_sms * 4, (N_elements / VEC_SIZE + block_size - 1) / block_size);
// Allocate temporary storage for partial sums
auto partial_sum = torch::empty({grid_size}, pred.options());
auto final_result = torch::empty({1}, pred.options());
// Launch main reduction kernel
l1_optimized_kernel<<<grid_size, block_size>>>(
pred.data_ptr<float>(),
target.data_ptr<float>(),
partial_sum.data_ptr<float>(),
N_elements
);
// Launch final reduction kernel (entirely on GPU)
final_reduction_kernel<<<1, block_size>>>(
partial_sum.data_ptr<float>(),
final_result.data_ptr<float>(),
grid_size
);
// Compute mean on GPU
final_result.div_(N_elements);
return final_result;
}
"""
self.l1_op = load_inline(
name="l1loss_optimized_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["l1_forward_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math", "-lineinfo"],
verbose=True
)
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return self.l1_op.l1_forward_cuda(pred, target)

24
S1/26/l1loss_torch.py Normal file
View File

@ -0,0 +1,24 @@
# l1loss_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 16
DIM = 16384 * 16
class Model(nn.Module):
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return F.l1_loss(pred, target, reduction='mean')
def get_inputs():
pred = torch.randn(BATCH_SIZE, DIM, dtype=torch.float32)
target = pred + torch.rand_like(pred) * 0.1
return [pred, target]
def get_init_inputs():
return []

31
S1/26/prompt.txt Normal file
View File

@ -0,0 +1,31 @@
You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
```python
# l1loss_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 16
DIM = 16384 * 16
class Model(nn.Module):
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return F.l1_loss(pred, target, reduction='mean')
def get_inputs():
pred = torch.randn(BATCH_SIZE, DIM, dtype=torch.float32)
target = pred + torch.rand_like(pred) * 0.1
return [pred, target]
def get_init_inputs():
return []

88
S1/26/run_code.py Normal file
View File

@ -0,0 +1,88 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from l1loss_torch import Model, get_inputs, get_init_inputs
from l1loss_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)
# 更严格的精度检查
abs_diff = (output_torch - output_cuda).abs()
max_diff = abs_diff.max().item()
mean_diff = abs_diff.mean().item()
print(f"最大差异: {max_diff:.6f}")
print(f"平均差异: {mean_diff:.6f}")
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
if precision_flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
# Warm up
for _ in range(100):
_ = torch_model(*inputs)
_ = cuda_model(*inputs)
# 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 (matmul + relu) 平均执行时间: {torch_time:.6f}")
print(f"自定义 CUDA ReLU 平均执行时间: {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()