Merge pull request 'finish softplus #15' (#209) from uucoco/GPUCodeForces:uucoco15 into main

This commit is contained in:
Kuohais 2025-11-27 15:31:34 +08:00
commit b533bef7cc
4 changed files with 317 additions and 0 deletions

81
S1/uucoco_#15/prompt.txt Normal file
View File

@ -0,0 +1,81 @@
You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm 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 normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
Techniques used:
CUDA inline extension in PyTorch
Float4 vectorization for memory coalescing
Element-wise kernel with grid-stride loops
Numerical optimization: precompute reciprocal (inv_beta)
Branch optimization: threshold-based condition for numerical stability
Fast math compilation with --use_fast_math flag
Memory layout optimization: contiguous tensor access
Grid size tuning: automatic block calculation with 1024 limit
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
import torch.nn.functional as F
# --- Hyperparameters ---
N, C, H, W = 16, 16, 64, 64
BETA = 1.0
THRESHOLD = 20.0
class Softplus(nn.Module):
def __init__(self, beta=BETA, threshold=THRESHOLD):
super().__init__()
self.beta = beta
self.threshold = threshold
def forward(self, input: torch.Tensor) -> torch.Tensor:
scaled_input = input * self.beta
mask = (scaled_input > self.threshold)
stable_output = (1.0 / self.beta) * torch.log1p(torch.exp(scaled_input))
linear_output = input
return torch.where(mask, linear_output, stable_output)
class Model(nn.Module):
def __init__(self, beta=BETA, threshold=THRESHOLD):
super().__init__()
self.op = Softplus(beta=beta, threshold=threshold)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.op(input)
def get_inputs():
torch.manual_seed(42)
x = torch.randn(N, C, H, W, dtype=torch.float32) * (THRESHOLD / BETA) / 5.0
x[0, 0, 0, 0] = THRESHOLD / BETA + 1.0
return [x]
def get_init_inputs():
return [BETA, THRESHOLD]

80
S1/uucoco_#15/run_code.py Normal file
View File

@ -0,0 +1,80 @@
import torch
import time
from softplus_torch import Model, get_inputs, get_init_inputs
from softplus_cuda import ModelNew
def run_benchmark():
if not torch.cuda.is_available():
print("CUDA 不可用")
return
device = torch.device("cuda")
# 准备输入数据
inputs = [x.cuda(device=device) for x in get_inputs()]
init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()]
# 初始化模型
torch_model = Model(*init_inputs).cuda()
cuda_model = ModelNew(*init_inputs).cuda()
torch_model.eval()
cuda_model.eval()
print("-------------------- 精度对齐验证 --------------------")
with torch.no_grad():
# 预热GPU
_ = torch_model(*inputs)
_ = cuda_model(*inputs)
# 正式测试
output_torch = torch_model(*inputs)
output_cuda = cuda_model(*inputs)
# 精度验证
abs_diff = torch.abs(output_torch - output_cuda)
max_diff = torch.max(abs_diff).item()
mean_diff = torch.mean(abs_diff).item()
if max_diff < 1e-4 and mean_diff < 1e-5:
print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
precision_flag = True
else:
print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
precision_flag = False
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 100
# 预热GPU
for _ in range(10):
_ = 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内置Swish平均执行时间: {torch_time:.6f}")
print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}")
speedup = torch_time / cuda_time if cuda_time > 0 else 0
print(f"加速比 (Speedup): {speedup:.2f}x")
return precision_flag, speedup
if __name__ == "__main__":
precision_flag, speedup = run_benchmark()

View File

@ -0,0 +1,107 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
N, C, H, W = 16, 16, 64, 64
BETA = 1.0
THRESHOLD = 20.0
BLOCK_SIZE = 256
class ModelNew(nn.Module):
def __init__(self, beta=BETA, threshold=THRESHOLD):
super().__init__()
self.beta = beta
self.threshold = threshold
self.block_size = BLOCK_SIZE
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
total_elements = N * C * H * W
if total_elements % 4 != 0:
raise ValueError("Total elements must be divisible by 4 for float4 vectorization.")
cpp_source = """
#include <torch/extension.h>
torch::Tensor softplus_cuda_vec(torch::Tensor input, float beta, float threshold);
"""
cuda_source = f"""
#include <cuda_runtime.h>
#include <math.h>
#define BLOCK_SIZE {self.block_size}
__device__ __forceinline__ float softplus_elem(float x, float beta, float threshold, float inv_beta) {{
float scaled_x = x * beta;
return (scaled_x > threshold) ? x : inv_beta * __logf(1.0f + __expf(scaled_x));
}}
__global__ void softplus_kernel_vec(
const float4* __restrict__ input,
float4* __restrict__ output,
int total_vec_elements,
float beta,
float threshold,
float inv_beta
) {{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
for (int i = idx; i < total_vec_elements; i += stride) {{
float4 in_vec = input[i];
float4 out_vec;
out_vec.x = softplus_elem(in_vec.x, beta, threshold, inv_beta);
out_vec.y = softplus_elem(in_vec.y, beta, threshold, inv_beta);
out_vec.z = softplus_elem(in_vec.z, beta, threshold, inv_beta);
out_vec.w = softplus_elem(in_vec.w, beta, threshold, inv_beta);
output[i] = out_vec;
}}
}}
torch::Tensor softplus_cuda_vec(torch::Tensor input, float beta, float threshold) {{
TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
TORCH_CHECK(input.scalar_type() == torch::kFloat32, "Input must be float32");
int total_elements = input.numel();
TORCH_CHECK(total_elements % 4 == 0, "Total elements must be divisible by 4 for float4 vectorization.");
input = input.contiguous();
auto output = torch::empty_like(input);
int total_vec_elements = total_elements / 4;
float inv_beta = 1.0f / beta;
int blocks = std::min((total_vec_elements + BLOCK_SIZE - 1) / BLOCK_SIZE, 1024);
softplus_kernel_vec<<<blocks, BLOCK_SIZE>>>(
reinterpret_cast<const float4*>(input.data_ptr<float>()),
reinterpret_cast<float4*>(output.data_ptr<float>()),
total_vec_elements,
beta,
threshold,
inv_beta
);
return output;
}}
"""
nvcc_flags = ['-O3', '--use_fast_math']
self.op = load_inline(
name='softplus_opt_vec',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['softplus_cuda_vec'],
extra_cuda_cflags=nvcc_flags,
verbose=False
)
def forward(self, input: torch.Tensor) -> torch.Tensor:
if not input.is_cuda: input = input.cuda()
input_cont = input.contiguous()
return self.op.softplus_cuda_vec(input_cont, self.beta, self.threshold)

View File

@ -0,0 +1,49 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
# --- Hyperparameters ---
N, C, H, W = 16, 16, 64, 64
BETA = 1.0
THRESHOLD = 20.0
class Softplus(nn.Module):
def __init__(self, beta=BETA, threshold=THRESHOLD):
super().__init__()
self.beta = beta
self.threshold = threshold
def forward(self, input: torch.Tensor) -> torch.Tensor:
scaled_input = input * self.beta
mask = (scaled_input > self.threshold)
stable_output = (1.0 / self.beta) * torch.log1p(torch.exp(scaled_input))
linear_output = input
return torch.where(mask, linear_output, stable_output)
class Model(nn.Module):
def __init__(self, beta=BETA, threshold=THRESHOLD):
super().__init__()
self.op = Softplus(beta=beta, threshold=threshold)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.op(input)
def get_inputs():
torch.manual_seed(42)
x = torch.randn(N, C, H, W, dtype=torch.float32) * (THRESHOLD / BETA) / 5.0
x[0, 0, 0, 0] = THRESHOLD / BETA + 1.0
return [x]
def get_init_inputs():
return [BETA, THRESHOLD]