diff --git a/S1/hli28146_#119/SCLMish_cuda.py b/S1/hli28146_#119/SCLMish_cuda.py new file mode 100644 index 0000000..da06312 --- /dev/null +++ b/S1/hli28146_#119/SCLMish_cuda.py @@ -0,0 +1,113 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_source = """ +#include + +torch::Tensor scl_mish_cuda_forward(const torch::Tensor& input, const torch::Tensor& alpha); +""" + +cuda_source = """ +#include +#include +#include + +#define BLOCK_SIZE 256 + +struct __align__(16) Float4 { + float x, y, z, w; +}; + +// SCL Mish Logic +__device__ __forceinline__ float compute_scl_mish(float x, float alpha) { + float ax = alpha * x; + float sp; + // Stable Softplus + if (ax > 20.0f) { + sp = ax; + } else { + sp = log1pf(expf(ax)); + } + float mish_part = x * tanhf(sp); + return fmaxf(mish_part, 0.0f); +} + +__global__ void scl_mish_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_scl_mish(in_vec.x, alpha); + out_vec.y = compute_scl_mish(in_vec.y, alpha); + out_vec.z = compute_scl_mish(in_vec.z, alpha); + out_vec.w = compute_scl_mish(in_vec.w, alpha); + + reinterpret_cast(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_scl_mish(input[current_idx], alpha); + current_idx += total_threads; + } +} + +torch::Tensor scl_mish_cuda_forward(const torch::Tensor& input, const torch::Tensor& alpha_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); + + const float alpha = alpha_t.item(); + + 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; + + scl_mish_kernel<<>>( + output.data_ptr(), + input.data_ptr(), + n, + alpha + ); + + return output; +} +""" + +scl_mish_op_module = load_inline( + name='scl_mish_op', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['scl_mish_cuda_forward'], + verbose=False, + extra_cuda_cflags=['-O3'] +) + +class ModelNew(nn.Module): + def __init__(self, alpha_init=0.25): + super(ModelNew, self).__init__() + self.alpha = nn.Parameter(torch.tensor(alpha_init)) + self.op = scl_mish_op_module + + def forward(self, input_tensor: torch.Tensor) -> torch.Tensor: + return self.op.scl_mish_cuda_forward(input_tensor.contiguous(), self.alpha) \ No newline at end of file diff --git a/S1/hli28146_#119/SCLMish_torch.py b/S1/hli28146_#119/SCLMish_torch.py new file mode 100644 index 0000000..d08bf61 --- /dev/null +++ b/S1/hli28146_#119/SCLMish_torch.py @@ -0,0 +1,42 @@ +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_INIT = 0.25 + +class SCLMish(nn.Module): + """ + Soft Clipping Mish (learnable). + Soft Clipping Mish - A Novel Activation Function for Deep Learning + DOI:10.1109/ICICT52872.2021.00010 + + Formula: f(x) = max(0, x * tanh(softplus(alpha * x))) + """ + def __init__(self, alpha_init=0.25): + super(SCLMish, self).__init__() + self.alpha = nn.Parameter(torch.tensor(alpha_init)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + mish_part = x * F.mish(self.alpha * x) / (self.alpha * x + 1e-8) # Re-normalize + mish_part_correct = x * torch.tanh(F.softplus(self.alpha * x)) + + return F.relu(mish_part_correct) + +class Model(nn.Module): + def __init__(self, alpha_init=0.25): + super(Model, self).__init__() + self.act = SCLMish(alpha_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] \ No newline at end of file diff --git a/S1/hli28146_#119/prompt.txt b/S1/hli28146_#119/prompt.txt new file mode 100644 index 0000000..cd6c25c --- /dev/null +++ b/S1/hli28146_#119/prompt.txt @@ -0,0 +1,50 @@ +Write a custom CUDA kernel to optimize `SCL Mish` (Soft Clipping Mish learnable). + +Formula: f(x) = max(0, x * tanh(softplus(alpha * x))) +where softplus(z) = log(1 + exp(z)). + +Problem Analysis: +1. Computationally Intensive & Memory Bound: The operation is element-wise but involves a long chain of transcendental functions (exp, log, tanh). +2. Operator Chaining: A standard PyTorch implementation creates multiple intermediate tensors and kernel launches. + +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 Stable Math: + - For each element `x`, compute `ax = alpha * x`. + - Compute stable softplus: `sp = (ax > 20) ? ax : log1pf(__expf(ax))`. + - Compute `mish_part = x * tanhf(sp)`. + - Result `fmaxf(mish_part, 0.0f)`. + - All steps are fused in registers. + +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 +import torch.nn.functional as F + + +class Model(nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward(self, a, b): + return a + b + + +def get_inputs(): + # randomly generate input tensors based on the model architecture + a = torch.randn(1, 128).cuda() + b = torch.randn(1, 128).cuda() + return [a, b] + + +def get_init_inputs(): + # randomly generate tensors required for initialization based on the model architecture + return [] \ No newline at end of file diff --git a/S1/hli28146_#119/run_code.py b/S1/hli28146_#119/run_code.py new file mode 100644 index 0000000..2438829 --- /dev/null +++ b/S1/hli28146_#119/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from SCLMish_torch import Model,get_inputs,get_init_inputs +from SCLMish_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