From b621c6f78ecc3c417731c1f9114f227378a99423 Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Fri, 14 Nov 2025 10:52:35 +0800 Subject: [PATCH] fix geglu #2 --- S1/gsd123_#2/geglu_cuda.py | 96 +++++++++++++++++++++++++++++++++++++ S1/gsd123_#2/geglu_torch.py | 30 ++++++++++++ S1/gsd123_#2/prompt.txt | 45 +++++++++++++++++ S1/gsd123_#2/run_code.py | 78 ++++++++++++++++++++++++++++++ 4 files changed, 249 insertions(+) create mode 100644 S1/gsd123_#2/geglu_cuda.py create mode 100644 S1/gsd123_#2/geglu_torch.py create mode 100644 S1/gsd123_#2/prompt.txt create mode 100644 S1/gsd123_#2/run_code.py diff --git a/S1/gsd123_#2/geglu_cuda.py b/S1/gsd123_#2/geglu_cuda.py new file mode 100644 index 0000000..0ff71ba --- /dev/null +++ b/S1/gsd123_#2/geglu_cuda.py @@ -0,0 +1,96 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor geglu_dynamic_parallel(torch::Tensor input); + """ + + cuda_source = """ + #include + + __device__ float gelu_exact(float x) { + return 0.5f * x * (1.0f + erff(x * 0.7071067811865475f)); + } + + __global__ void geglu_dynamic_kernel( + const float* __restrict__ input, + float* __restrict__ output, + int feature_dim, int total_elements) { + + extern __shared__ float shared_data[]; + + int tid = threadIdx.x; + int bid = blockIdx.x; + int bdim = blockDim.x; + + // 动态确定每个block处理的元素数量 + int elements_per_block = min(bdim * 4, total_elements - bid * bdim * 4); + elements_per_block = max(elements_per_block, 0); + + float* gate_shared = shared_data; + float* act_shared = shared_data + elements_per_block; + + // 协作加载 + for (int i = tid; i < elements_per_block; i += bdim) { + int global_idx = bid * bdim * 4 + i; + if (global_idx < total_elements) { + int row = global_idx / (feature_dim / 2); + int col = global_idx % (feature_dim / 2); + + gate_shared[i] = input[row * feature_dim + col]; + act_shared[i] = input[row * feature_dim + col + (feature_dim / 2)]; + } + } + __syncthreads(); + + // 处理 + for (int i = tid; i < elements_per_block; i += bdim) { + int global_idx = bid * bdim * 4 + i; + if (global_idx < total_elements) { + float gate_val = gate_shared[i]; + float act_val = act_shared[i]; + output[global_idx] = gelu_exact(gate_val) * act_val; + } + } + } + + torch::Tensor geglu_dynamic_parallel(torch::Tensor input) { + input = input.contiguous(); + auto sizes = input.sizes().vec(); + int feature_dim = sizes.back(); + sizes.back() /= 2; + auto output = torch::empty(sizes, input.options()); + + int total_elements = output.numel(); + int threads = 128; + int blocks = (total_elements + threads * 4 - 1) / (threads * 4); + int shared_mem = threads * 4 * 2 * sizeof(float); + + geglu_dynamic_kernel<<>>( + input.data_ptr(), output.data_ptr(), + feature_dim, total_elements); + + return output; + } + """ + + self.op = load_inline( + name="geglu_dynamic", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["geglu_dynamic_parallel"], + extra_cuda_cflags=["-O3"], + verbose=True + ) + + def forward(self, x): + return self.op.geglu_dynamic_parallel(x) \ No newline at end of file diff --git a/S1/gsd123_#2/geglu_torch.py b/S1/gsd123_#2/geglu_torch.py new file mode 100644 index 0000000..f84a2b6 --- /dev/null +++ b/S1/gsd123_#2/geglu_torch.py @@ -0,0 +1,30 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Model(nn.Module): + + def __init__(self): + super().__init__() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + GeGLU(x) = GELU(gate) * act + """ + gate, act = x.chunk(2, dim=-1) + + return F.gelu(gate) * act + + +batch_size = 4096 +feature_dim = 4096 + + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [] diff --git a/S1/gsd123_#2/prompt.txt b/S1/gsd123_#2/prompt.txt new file mode 100644 index 0000000..1025985 --- /dev/null +++ b/S1/gsd123_#2/prompt.txt @@ -0,0 +1,45 @@ +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. + +Key optimization techniques used in this implementation: + +1. **Operator Fusion**: Fused chunk + gelu + elementwise multiplication into a single kernel +2. **Shared Memory Optimization**: Utilizes shared memory for cooperative data loading and reuse +3. **Dynamic Workload Balancing**: Adapts workload per block based on total elements +4. **Memory Access Coalescing**: Organized memory access patterns for better bandwidth utilization +5. **Exact GELU Implementation**: Maintains numerical precision with erf-based GELU + +The custom kernel eliminates intermediate tensor allocations and reduces global memory traffic by processing the entire GeGLU operation in a single fused kernel with optimized memory hierarchy usage. +""" +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): + super().__init__() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + GeGLU(x) = GELU(gate) * act + """ + gate, act = x.chunk(2, dim=-1) + + return F.gelu(gate) * act + + +batch_size = 4096 +feature_dim = 4096 + + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#2/run_code.py b/S1/gsd123_#2/run_code.py new file mode 100644 index 0000000..3653d83 --- /dev/null +++ b/S1/gsd123_#2/run_code.py @@ -0,0 +1,78 @@ +import torch +import time +from geglu_torch import Model, get_inputs, get_init_inputs +from geglu_cuda import ModelNew + +def run_benchmark(): + if not torch.cuda.is_available(): + print("CUDA 不可用") + return + + device = torch.device("cuda") + + # 准备输入数据 + inputs = [x.cuda(device=device) for x in get_inputs()] + init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()] + + # 初始化模型 + torch_model = Model(*init_inputs).cuda() + cuda_model = ModelNew(*init_inputs).cuda() + + torch_model.eval() + cuda_model.eval() + + print("-------------------- 精度对齐验证 --------------------") + with torch.no_grad(): + # 预热GPU + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 正式测试 + output_torch = torch_model(*inputs) + output_cuda = cuda_model(*inputs) + + # 精度验证 + abs_diff = torch.abs(output_torch - output_cuda) + max_diff = torch.max(abs_diff).item() + mean_diff = torch.mean(abs_diff).item() + + if max_diff < 1e-4 and mean_diff < 1e-5: + print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}") + precision_flag = True + else: + print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}") + precision_flag = False + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 100 + + # 预热GPU + for _ in range(10): + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 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内置Swish平均执行时间: {torch_time:.6f}秒") + print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}秒") + speedup = torch_time / cuda_time if cuda_time > 0 else 0 + print(f"加速比 (Speedup): {speedup:.2f}x") + + return precision_flag, speedup + +if __name__ == "__main__": + precision_flag, speedup = run_benchmark() \ No newline at end of file