From cbe487abe843929cbf5888944baa7b8d6466a175 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 18:57:59 +0800 Subject: [PATCH] finish affine_leaky_clamp #77 --- S1/uucoco_#77/affine_leaky_clamp_torch.py | 27 ++++++ S1/uucoco_#77/affineleakyreluclamp_cuda.py | 103 ++++++++++++++++++++ S1/uucoco_#77/prompt.txt | 107 +++++++++++++++++++++ S1/uucoco_#77/run_code.py | 77 +++++++++++++++ 4 files changed, 314 insertions(+) create mode 100644 S1/uucoco_#77/affine_leaky_clamp_torch.py create mode 100644 S1/uucoco_#77/affineleakyreluclamp_cuda.py create mode 100644 S1/uucoco_#77/prompt.txt create mode 100644 S1/uucoco_#77/run_code.py diff --git a/S1/uucoco_#77/affine_leaky_clamp_torch.py b/S1/uucoco_#77/affine_leaky_clamp_torch.py new file mode 100644 index 0000000..ee99a74 --- /dev/null +++ b/S1/uucoco_#77/affine_leaky_clamp_torch.py @@ -0,0 +1,27 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +class Model(nn.Module): + def __init__(self, scale, shift, negative_slope, min_val, max_val): + super(Model, self).__init__() + self.scale = scale + self.shift = shift + self.negative_slope = negative_slope + self.min_val = min_val + self.max_val = max_val + + def forward(self, x): + x = x * self.scale + self.shift + x = F.leaky_relu(x, negative_slope=self.negative_slope) + return torch.clamp(x, self.min_val, self.max_val) + +batch_size = 1024 +dim = 1024 + +def get_inputs(): + x = torch.randn(batch_size, dim) + return [x] + +def get_init_inputs(): + return [2.0, 0.5, 0.1, -1.0, 1.0] \ No newline at end of file diff --git a/S1/uucoco_#77/affineleakyreluclamp_cuda.py b/S1/uucoco_#77/affineleakyreluclamp_cuda.py new file mode 100644 index 0000000..5afd53f --- /dev/null +++ b/S1/uucoco_#77/affineleakyreluclamp_cuda.py @@ -0,0 +1,103 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__global__ void affine_leaky_clamp_kernel( + const float* __restrict__ input, + float* __restrict__ output, + float scale, + float shift, + float negative_slope, + float min_val, + float max_val, + int size +) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < size) { + float val = input[idx]; + + val = fmaf(val, scale, shift); + + if (val < 0.0f) { + val = val * negative_slope; + } + + val = fmaxf(val, min_val); + val = fminf(val, max_val); + + output[idx] = val; + } +} + +torch::Tensor affine_leaky_clamp_cuda( + torch::Tensor input, + float scale, + float shift, + float negative_slope, + float min_val, + float max_val +) { + auto output = torch::empty_like(input); + int size = input.numel(); + + const int block_size = 256; + int num_blocks = (size + block_size - 1) / block_size; + + affine_leaky_clamp_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + scale, + shift, + negative_slope, + min_val, + max_val, + size + ); + + return output; +} +""" + +cpp_source = """ +torch::Tensor affine_leaky_clamp_cuda( + torch::Tensor input, + float scale, + float shift, + float negative_slope, + float min_val, + float max_val +); +""" + +module = load_inline( + name="affine_leaky_clamp", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["affine_leaky_clamp_cuda"], + verbose=True +) + + +class ModelNew(nn.Module): + def __init__(self, scale, shift, negative_slope, min_val, max_val): + super(ModelNew, self).__init__() + self.scale = scale + self.shift = shift + self.negative_slope = negative_slope + self.min_val = min_val + self.max_val = max_val + self.module = module + + def forward(self, x): + return self.module.affine_leaky_clamp_cuda( + x, + self.scale, + self.shift, + self.negative_slope, + self.min_val, + self.max_val + ) \ No newline at end of file diff --git a/S1/uucoco_#77/prompt.txt b/S1/uucoco_#77/prompt.txt new file mode 100644 index 0000000..b7f726a --- /dev/null +++ b/S1/uucoco_#77/prompt.txt @@ -0,0 +1,107 @@ +You write custom CUDA kernels to replace the pytorch operators in the given GeGLU architecture to get speedups. + +You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. + +Technologies Used in This Code +Core Libraries & Frameworks +PyTorch: Deep learning framework + +CUDA: NVIDIA's parallel computing platform for GPU acceleration + +C++: For high-performance kernel implementation + +PyTorch Specific Components +torch.nn.Module: Base class for neural network modules + +torch.utils.cpp_extension.load_inline: For inline compilation of CUDA/C++ extensions + +PyTorch Tensors: Multi-dimensional arrays + +torch::empty_like(): Tensor creation with same properties + +CUDA/C++ Implementation Details +CUDA Kernels: Custom GPU kernel (affine_leaky_clamp_kernel) + +CUDA Math Functions: fmaf() (fused multiply-add), fmaxf(), fminf() + +Element-Wise Parallelism: One thread per tensor element + +Simple Grid/Block Configuration: Standard 1D parallelization pattern + +Activation Function Components +Affine Transformation: Linear scaling and shifting + +Leaky ReLU: Modified ReLU with non-zero negative slope + +Value Clamping: Hard limits on output range + +Fused Operations: Multiple operations in single kernel + +Mathematical Operations +Fused Multiply-Add: Efficient scale*x + shift computation + +Conditional Activation: Positive pass-through, negative scaling + +Range Limiting: Enforce min_val ≤ output ≤ max_val + +Element-Wise Processing: Independent processing per element + +Optimization Techniques +Fused Kernel Design: Single kernel combines multiple operations + +FMA Optimization: Use of fused multiply-add instruction + +Branching Efficiency: Simple conditional statements + +Memory Coalescing: Straightforward memory access pattern + +Performance Features +Massive Parallelization: GPU acceleration for activation function + +Minimal Memory Traffic: In-place style computation + +Low Computational Cost: Simple arithmetic operations + +Numerical Stability: No complex numerical issues + +Unique Implementation Aspects +Composite Activation: Combination of three different operations + +Parameterized Design: Five tunable hyperparameters + +Element-Wise Independence: No inter-element dependencies + +Deterministic Output: Simple, predictable computation + + + + + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: +import torch +import torch.nn as nn +import torch.nn.functional as F + +class Model(nn.Module): + def __init__(self, scale, shift, negative_slope, min_val, max_val): + super(Model, self).__init__() + self.scale = scale + self.shift = shift + self.negative_slope = negative_slope + self.min_val = min_val + self.max_val = max_val + + def forward(self, x): + x = x * self.scale + self.shift + x = F.leaky_relu(x, negative_slope=self.negative_slope) + return torch.clamp(x, self.min_val, self.max_val) + +batch_size = 1024 +dim = 1024 + +def get_inputs(): + x = torch.randn(batch_size, dim) + return [x] + +def get_init_inputs(): + return [2.0, 0.5, 0.1, -1.0, 1.0] \ No newline at end of file diff --git a/S1/uucoco_#77/run_code.py b/S1/uucoco_#77/run_code.py new file mode 100644 index 0000000..0d151c8 --- /dev/null +++ b/S1/uucoco_#77/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from affine_leaky_clamp_torch import Model, get_inputs, get_init_inputs +from affineleakyreluclamp_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