finish tanhexp #20

This commit is contained in:
hli28146 2025-11-27 00:19:19 +08:00
parent f876a28ada
commit 0bd5f52b59
4 changed files with 264 additions and 0 deletions

View File

@ -0,0 +1,56 @@
Write a custom CUDA kernel to optimize the TanhExp activation function.
The mathematical definition is:
f(x) = x * tanh(exp(x))
Problem Analysis:
The standard PyTorch implementation involves a chain of element-wise operations: exponential, hyperbolic tangent, and multiplication.
1. exp(x) creates an intermediate tensor.
2. tanh(intermediate) creates another intermediate tensor.
3. x * result creates the final output.
This chain results in excessive global memory read/write traffic, making the operation memory-bound. Additionally, computing two transcendental functions (exp, tanh) per element creates high arithmetic pressure.
Optimization Strategy: Fused Element-wise Kernel with Vectorized Access and Fast Math
1. Operator Fusion: Create a single CUDA kernel that computes `x * tanh(exp(x))` in one pass. Each thread reads `x` once into a register, computes the entire mathematical expression, and writes the result back. This minimizes global memory accesses.
2. Vectorized Memory Access: Use `float4` types to load and store 128 bits (4 floats) per instruction. This drastically improves memory bandwidth utilization and reduces instruction overhead.
3. Grid-Stride Loop: Implement the kernel using a grid-stride loop pattern. This ensures the kernel works correctly and efficiently for input tensors of any size, decoupling the grid configuration from the specific data size.
4. Fast Math Intrinsics: Since the kernel involves `exp` and `tanh`, utilizing fast math intrinsics (like `__expf` or compiling with `--use_fast_math`) is crucial to reduce the latency of the ALU operations, allowing them to be effectively hidden by the optimized memory access.
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
DIM = 4096
SHAPE = (BATCH_SIZE, DIM)
class TanhExp(nn.Module):
"""
公式: f(x) = x * tanh(e^x)
"""
def __init__(self):
super(TanhExp, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.tanh(torch.exp(x))
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.act = TanhExp()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.act(x)
def get_inputs():
x = torch.randn(SHAPE, dtype=torch.float32)
return [x.contiguous()]
def get_init_inputs():
return []

View File

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

View File

@ -0,0 +1,103 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cpp_source = """
#include <torch/extension.h>
torch::Tensor tanhexp_cuda_forward(const torch::Tensor& input);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
struct __align__(16) Float4 {
float x, y, z, w;
};
// 计算 TanhExp: x * tanh(exp(x))
__device__ __forceinline__ float tanhexp_op(float x) {
// 标准 expf/tanhf 能妥善处理 inf
return x * tanhf(expf(x));
}
__global__ void tanhexp_kernel(
const float* __restrict__ input,
float* __restrict__ output,
const int n_elements)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
// 1. 向量化处理循环 (每次处理 4 float)
int vec_loops = n_elements / 4;
const Float4* vec_input = reinterpret_cast<const Float4*>(input);
Float4* vec_output = reinterpret_cast<Float4*>(output);
for (int i = idx; i < vec_loops; i += stride) {
Float4 in_val = vec_input[i];
Float4 out_val;
out_val.x = tanhexp_op(in_val.x);
out_val.y = tanhexp_op(in_val.y);
out_val.z = tanhexp_op(in_val.z);
out_val.w = tanhexp_op(in_val.w);
vec_output[i] = out_val;
}
// 2. 处理尾部剩余元素 ( 4 对齐的部分)
int tail_start = vec_loops * 4;
for (int i = tail_start + idx; i < n_elements; i += stride) {
output[i] = tanhexp_op(input[i]);
}
}
torch::Tensor tanhexp_cuda_forward(const torch::Tensor& input) {
TORCH_CHECK(input.is_cuda(), "Input tensor must be a CUDA tensor");
TORCH_CHECK(input.is_contiguous(), "Input tensor must be contiguous");
auto output = torch::empty_like(input);
const int n_elements = input.numel();
const int block_size = 256;
int grid_size = (n_elements + block_size * 4 - 1) / (block_size * 4);
if (grid_size > 65535) grid_size = 65535;
tanhexp_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
n_elements
);
return output;
}
"""
tanhexp_op = load_inline(
name='tanhexp_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['tanhexp_cuda_forward'],
verbose=False,
extra_cuda_cflags=['-O3', '--use_fast_math']
)
class TanhExpNew(nn.Module):
def __init__(self):
super(TanhExpNew, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return tanhexp_op.tanhexp_cuda_forward(x)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.act = TanhExpNew()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.act(x)

View File

@ -0,0 +1,31 @@
import torch
import torch.nn as nn
BATCH_SIZE = 4096
DIM = 4096
SHAPE = (BATCH_SIZE, DIM)
class TanhExp(nn.Module):
"""
公式: f(x) = x * tanh(e^x)
"""
def __init__(self):
super(TanhExp, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.tanh(torch.exp(x))
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.act = TanhExp()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.act(x)
def get_inputs():
x = torch.randn(SHAPE, dtype=torch.float32)
return [x.contiguous()]
def get_init_inputs():
return []