diff --git a/S1/hli28146_#64/penalizedtanh_cuda.py b/S1/hli28146_#64/penalizedtanh_cuda.py new file mode 100644 index 00000000..5eadbd69 --- /dev/null +++ b/S1/hli28146_#64/penalizedtanh_cuda.py @@ -0,0 +1,108 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_source = """ +#include + +torch::Tensor ptanh_cuda_forward(const torch::Tensor& input, float alpha); +""" + +cuda_source = """ +#include +#include +#include + +#define BLOCK_SIZE 256 + +struct __align__(16) Float4 { + float x, y, z, w; +}; + +// Penalized Tanh Logic +// t = tanh(x) +// res = (x > 0) ? t : t * alpha +__device__ __forceinline__ float compute_ptanh(float x, float alpha) { + float t = tanhf(x); + if (x > 0.0f) { + return t; + } else { + return t * alpha; + } +} + +__global__ void ptanh_kernel( + float* __restrict__ output, + const float* __restrict__ input, + const int n, + const float alpha) +{ + 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(input)[i]; + Float4 out_vec; + + out_vec.x = compute_ptanh(in_vec.x, alpha); + out_vec.y = compute_ptanh(in_vec.y, alpha); + out_vec.z = compute_ptanh(in_vec.z, alpha); + out_vec.w = compute_ptanh(in_vec.w, alpha); + + reinterpret_cast(output)[i] = out_vec; + } + + int tail_start = vec_n * 4; + int global_tid = blockIdx.x * blockDim.x + threadIdx.x; + + if (global_tid < (n - tail_start)) { + int real_idx = tail_start + global_tid; + output[real_idx] = compute_ptanh(input[real_idx], alpha); + } +} + +torch::Tensor ptanh_cuda_forward(const torch::Tensor& input, float alpha) { + 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); + + const int vec_n = n / 4; + // Launch enough blocks + 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; + + ptanh_kernel<<>>( + output.data_ptr(), + input.data_ptr(), + n, + alpha + ); + + return output; +} +""" + +ptanh_op_module = load_inline( + name='ptanh_op', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['ptanh_cuda_forward'], + verbose=False, + extra_cuda_cflags=['-O3', '--use_fast_math'] +) + +class ModelNew(nn.Module): + def __init__(self, alpha=0.25): + super(ModelNew, self).__init__() + self.alpha = alpha + self.op = ptanh_op_module + + def forward(self, input_tensor: torch.Tensor) -> torch.Tensor: + return self.op.ptanh_cuda_forward(input_tensor.contiguous(), self.alpha) \ No newline at end of file diff --git a/S1/hli28146_#64/penalizedtanh_torch.py b/S1/hli28146_#64/penalizedtanh_torch.py new file mode 100644 index 00000000..d1f2b20e --- /dev/null +++ b/S1/hli28146_#64/penalizedtanh_torch.py @@ -0,0 +1,39 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +BATCH_SIZE = 4096 +HIDDEN_DIM = 4096 +SHAPE = (BATCH_SIZE, HIDDEN_DIM) + +ALPHA_VAL = 0.25 + +class PenalizedTanh(nn.Module): + """ + Penalized Tanh + https://arxiv.org/pdf/1602.05980 + f(x) = tanh(x) if x > 0 + alpha * tanh(x) if x <= 0 + """ + def __init__(self, alpha=0.25): + super(PenalizedTanh, self).__init__() + self.alpha = alpha + + def forward(self, x: torch.Tensor) -> torch.Tensor: + t = torch.tanh(x) + return torch.where(x > 0, t, self.alpha * t) + +class Model(nn.Module): + def __init__(self, alpha=0.25): + super(Model, self).__init__() + self.act = PenalizedTanh(alpha=alpha) + + def forward(self, x): + return self.act(x) + +def get_inputs(): + input_tensor = torch.randn(SHAPE, dtype=torch.float32) + return [input_tensor.contiguous()] + +def get_init_inputs(): + return [ALPHA_VAL] \ No newline at end of file diff --git a/S1/hli28146_#64/prompt.txt b/S1/hli28146_#64/prompt.txt new file mode 100644 index 00000000..b6e60fd2 --- /dev/null +++ b/S1/hli28146_#64/prompt.txt @@ -0,0 +1,62 @@ +Write a custom CUDA kernel to optimize `Penalized Tanh` activation. + +Formula: f(x) = tanh(x) if x > 0 else alpha * tanh(x) +This is equivalent to: tanh(x) * (x > 0 ? 1 : alpha) + +Problem Analysis: +1. Memory Bandwidth: As an element-wise activation function, the arithmetic intensity is low. The performance is dominated by the speed of reading input and writing output (Memory Bound). +2. Tanh Cost: calculating `tanh` involves expensive exponential operations. However, modern GPUs have Special Function Units (SFUs), and the memory latency usually dominates. +3. Multiple Passes: A naive PyTorch implementation might compute `tanh(x)`, create a mask `x>0`, and then combine, resulting in redundant reads/writes. + +Optimization Strategy: Fused Element-wise Kernel with Vectorization + +1. One-Pass Fused Kernel: Perform the tanh computation and the conditional scaling in a single pass. Load `x`, compute `t = tanh(x)`, apply scaling based on the sign of `x`, and store. + +2. Vectorized Loads (float4): Use `float4` to load 4 float elements (128 bits) per thread instruction. This is the most effective optimization for memory-bound kernels on Nvidia GPUs. + +3. Instruction Optimization: Calculate `tanh(x)` once per element. The branching logic `x > 0` is cheap compared to memory access. + +4. Kernel Configuration: Launch a 1D grid with enough blocks to cover the entire tensor size. + +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 +import torch.nn.functional as F + +BATCH_SIZE = 4096 +HIDDEN_DIM = 4096 +SHAPE = (BATCH_SIZE, HIDDEN_DIM) + +ALPHA_VAL = 0.25 + +class PenalizedTanh(nn.Module): + """ + Penalized Tanh + https://arxiv.org/pdf/1602.05980 + f(x) = tanh(x) if x > 0 + alpha * tanh(x) if x <= 0 + """ + def __init__(self, alpha=0.25): + super(PenalizedTanh, self).__init__() + self.alpha = alpha + + def forward(self, x: torch.Tensor) -> torch.Tensor: + t = torch.tanh(x) + return torch.where(x > 0, t, self.alpha * t) + +class Model(nn.Module): + def __init__(self, alpha=0.25): + super(Model, self).__init__() + self.act = PenalizedTanh(alpha=alpha) + + def forward(self, x): + return self.act(x) + +def get_inputs(): + input_tensor = torch.randn(SHAPE, dtype=torch.float32) + return [input_tensor.contiguous()] + +def get_init_inputs(): + return [ALPHA_VAL] \ No newline at end of file diff --git a/S1/hli28146_#64/run_code.py b/S1/hli28146_#64/run_code.py new file mode 100644 index 00000000..75c265d9 --- /dev/null +++ b/S1/hli28146_#64/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from penalizedtanh_torch import Model,get_inputs,get_init_inputs +from penalizedtanh_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