From 3edff0378e80fe8455a80299ceb660ad2a6328f6 Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Thu, 30 Oct 2025 18:06:44 +0800 Subject: [PATCH] fixes geglu #4 --- S1/4/geglu_cude.py | 96 +++++++++++++++++++++++++++++++++++++++++++++ S1/4/geglu_torch.py | 30 ++++++++++++++ S1/4/prompt.txt | 45 +++++++++++++++++++++ S1/4/run_code.py | 77 ++++++++++++++++++++++++++++++++++++ 4 files changed, 248 insertions(+) create mode 100644 S1/4/geglu_cude.py create mode 100644 S1/4/geglu_torch.py create mode 100644 S1/4/prompt.txt create mode 100644 S1/4/run_code.py diff --git a/S1/4/geglu_cude.py b/S1/4/geglu_cude.py new file mode 100644 index 0000000..0ff71ba --- /dev/null +++ b/S1/4/geglu_cude.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/4/geglu_torch.py b/S1/4/geglu_torch.py new file mode 100644 index 0000000..f84a2b6 --- /dev/null +++ b/S1/4/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/4/prompt.txt b/S1/4/prompt.txt new file mode 100644 index 0000000..1025985 --- /dev/null +++ b/S1/4/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/4/run_code.py b/S1/4/run_code.py new file mode 100644 index 0000000..9a45890 --- /dev/null +++ b/S1/4/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from geglu_torch import Model, get_inputs, get_init_inputs +from geglu_cude 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