Merge pull request 'finish PTELU #122' (#855) from hli28146/GPUCodeForces:h122 into main

This commit is contained in:
wawahejun 2025-12-14 22:16:03 +08:00
commit 499f4ab413
4 changed files with 308 additions and 0 deletions

View File

@ -0,0 +1,113 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cpp_source = """
#include <torch/extension.h>
torch::Tensor ptelu_cuda_forward(const torch::Tensor& input, const torch::Tensor& alpha, const torch::Tensor& beta);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
#define BLOCK_SIZE 256
struct __align__(16) Float4 {
float x, y, z, w;
};
// P-TELU Logic
__device__ __forceinline__ float compute_ptelu(float x, float alpha, float beta) {
if (x >= 0.0f) {
return x;
} else {
return alpha * tanhf(beta * x);
}
}
__global__ void ptelu_kernel(
float* __restrict__ output,
const float* __restrict__ input,
const int n,
const float alpha,
const float beta)
{
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
const int vec_n = n / 4;
int i = idx;
const int stride = blockDim.x * gridDim.x;
for (; i < vec_n; i += stride) {
Float4 in_vec = reinterpret_cast<const Float4*>(input)[i];
Float4 out_vec;
out_vec.x = compute_ptelu(in_vec.x, alpha, beta);
out_vec.y = compute_ptelu(in_vec.y, alpha, beta);
out_vec.z = compute_ptelu(in_vec.z, alpha, beta);
out_vec.w = compute_ptelu(in_vec.w, alpha, beta);
reinterpret_cast<Float4*>(output)[i] = out_vec;
}
int start_scalar = vec_n * 4;
int global_tid = blockIdx.x * blockDim.x + threadIdx.x;
int total_threads = gridDim.x * gridDim.x;
int current_idx = start_scalar + global_tid;
while (current_idx < n) {
output[current_idx] = compute_ptelu(input[current_idx], alpha, beta);
current_idx += total_threads;
}
}
torch::Tensor ptelu_cuda_forward(const torch::Tensor& input, const torch::Tensor& alpha_t, const torch::Tensor& beta_t) {
TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
TORCH_CHECK(input.is_contiguous(), "Input must be contiguous");
const int n = input.numel();
auto output = torch::empty_like(input);
// Parameter Tensor 中提取 scalar
const float alpha = alpha_t.item<float>();
const float beta = beta_t.item<float>();
const int vec_n = n / 4;
const int grid_size = (vec_n + BLOCK_SIZE - 1) / BLOCK_SIZE;
int final_grid = (grid_size < 1) ? 1 : grid_size;
if (final_grid > 65535) final_grid = 65535;
ptelu_kernel<<<final_grid, BLOCK_SIZE>>>(
output.data_ptr<float>(),
input.data_ptr<float>(),
n,
alpha,
beta
);
return output;
}
"""
ptelu_op_module = load_inline(
name='ptelu_param_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['ptelu_cuda_forward'],
verbose=False,
extra_cuda_cflags=['-O3']
)
class ModelNew(nn.Module):
def __init__(self, alpha_init=1.0, beta_init=1.0):
super(ModelNew, self).__init__()
self.alpha = nn.Parameter(torch.tensor(alpha_init))
self.beta = nn.Parameter(torch.tensor(beta_init))
self.op = ptelu_op_module
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
return self.op.ptelu_cuda_forward(input_tensor.contiguous(), self.alpha, self.beta)

View File

@ -0,0 +1,46 @@
import torch
import torch.nn as nn
# --- 基准测试配置 ---
BATCH_SIZE = 4096
HIDDEN_DIM = 4096
SHAPE = (BATCH_SIZE, HIDDEN_DIM)
# P-TELU 初始参数
ALPHA_INIT = 1.0
BETA_INIT = 1.0
class PTELU(nn.Module):
'''
P-TELU: Parametric Tan Hyperbolic Linear Unit Activation for Deep Neural Networks
https://ieeexplore.ieee.org/document/8265328
Formula:
f(x) = x if x >= 0
f(x) = alpha * tanh(beta * x) if x < 0
'''
def __init__(self, alpha_init=1.0, beta_init=1.0):
super(PTELU, self).__init__()
self.alpha = nn.Parameter(torch.tensor(alpha_init))
self.beta = nn.Parameter(torch.tensor(beta_init))
def forward(self, x: torch.Tensor) -> torch.Tensor:
pos_part = x
neg_part = self.alpha * torch.tanh(self.beta * x)
return torch.where(x >= 0, pos_part, neg_part)
class Model(nn.Module):
def __init__(self, alpha_init=1.0, beta_init=1.0):
super(Model, self).__init__()
self.act = PTELU(alpha_init, beta_init)
def forward(self, x):
return self.act(x)
def get_inputs():
input_tensor = torch.randn(SHAPE, dtype=torch.float32) * 5.0
return [input_tensor.contiguous()]
def get_init_inputs():
# 传递初始值
return [ALPHA_INIT, BETA_INIT]

View File

@ -0,0 +1,75 @@
Write a custom CUDA kernel to optimize `P-TELU` with learnable parameters.
Formula:
f(x) = x if x >= 0
f(x) = alpha * tanh(beta * x) if x < 0
where alpha and beta are trainable `nn.Parameter`s.
Problem Analysis:
1. Memory Bound: This is an element-wise activation with a conditional branch.
2. Operator Chaining: The PyTorch implementation using `torch.where` creates intermediate tensors.
3. Trainable Parameters: The kernel must accept `alpha` and `beta` as scalar inputs that are determined at runtime.
Optimization Strategy: Fused Element-wise Kernel with Vectorization
1. One-Thread-per-Element: Map each element to a CUDA thread.
2. Vectorized Loads (float4): Use `float4` to process 128 bits per memory transaction.
3. Fused Branching Logic:
- The scalar parameters `alpha` and `beta` are passed to the kernel.
- For each element `x`, check `if (x < 0)`.
- If true, compute `alpha * tanhf(beta * x)`.
- If false, result is `x`.
4. One-Pass: Fuse all steps into a single read-compute-write kernel.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
```python
import torch
import torch.nn as nn
# --- 基准测试配置 ---
BATCH_SIZE = 4096
HIDDEN_DIM = 4096
SHAPE = (BATCH_SIZE, HIDDEN_DIM)
# P-TELU 初始参数
ALPHA_INIT = 1.0
BETA_INIT = 1.0
class PTELU(nn.Module):
'''
P-TELU: Parametric Tan Hyperbolic Linear Unit Activation for Deep Neural Networks
https://ieeexplore.ieee.org/document/8265328
Formula:
f(x) = x if x >= 0
f(x) = alpha * tanh(beta * x) if x < 0
'''
def __init__(self, alpha_init=1.0, beta_init=1.0):
super(PTELU, self).__init__()
self.alpha = nn.Parameter(torch.tensor(alpha_init))
self.beta = nn.Parameter(torch.tensor(beta_init))
def forward(self, x: torch.Tensor) -> torch.Tensor:
pos_part = x
neg_part = self.alpha * torch.tanh(self.beta * x)
return torch.where(x >= 0, pos_part, neg_part)
class Model(nn.Module):
def __init__(self, alpha_init=1.0, beta_init=1.0):
super(Model, self).__init__()
self.act = PTELU(alpha_init, beta_init)
def forward(self, x):
return self.act(x)
def get_inputs():
input_tensor = torch.randn(SHAPE, dtype=torch.float32) * 5.0
return [input_tensor.contiguous()]
def get_init_inputs():
# 传递初始值
return [ALPHA_INIT, BETA_INIT]

View File

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