diff --git a/S1/hli28146_#20/prompt.txt b/S1/hli28146_#20/prompt.txt new file mode 100644 index 00000000..a488d908 --- /dev/null +++ b/S1/hli28146_#20/prompt.txt @@ -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 [] \ No newline at end of file diff --git a/S1/hli28146_#20/run_code.py b/S1/hli28146_#20/run_code.py new file mode 100644 index 00000000..aa50865b --- /dev/null +++ b/S1/hli28146_#20/run_code.py @@ -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() \ No newline at end of file diff --git a/S1/hli28146_#20/tanhexp_cuda.py b/S1/hli28146_#20/tanhexp_cuda.py new file mode 100644 index 00000000..402907dc --- /dev/null +++ b/S1/hli28146_#20/tanhexp_cuda.py @@ -0,0 +1,103 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_source = """ +#include + +torch::Tensor tanhexp_cuda_forward(const torch::Tensor& input); +""" + +cuda_source = """ +#include +#include +#include + +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(input); + Float4* vec_output = reinterpret_cast(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<<>>( + input.data_ptr(), + output.data_ptr(), + 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) \ No newline at end of file diff --git a/S1/hli28146_#20/tanhexp_torch.py b/S1/hli28146_#20/tanhexp_torch.py new file mode 100644 index 00000000..42dd1d29 --- /dev/null +++ b/S1/hli28146_#20/tanhexp_torch.py @@ -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 [] \ No newline at end of file