From d1997f14271fe58f58537bd1d9dfa9beeb08ee63 Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Tue, 9 Dec 2025 09:48:49 +0800 Subject: [PATCH] finish LayerDrop #70 --- S1/gsd123_#70/LayerDrop_cuda.py | 95 ++++++++++++++++++++++++++++++++ S1/gsd123_#70/LayerDrop_torch.py | 22 ++++++++ S1/gsd123_#70/prompt.txt | 83 ++++++++++++++++++++++++++++ S1/gsd123_#70/run_code.py | 77 ++++++++++++++++++++++++++ 4 files changed, 277 insertions(+) create mode 100644 S1/gsd123_#70/LayerDrop_cuda.py create mode 100644 S1/gsd123_#70/LayerDrop_torch.py create mode 100644 S1/gsd123_#70/prompt.txt create mode 100644 S1/gsd123_#70/run_code.py diff --git a/S1/gsd123_#70/LayerDrop_cuda.py b/S1/gsd123_#70/LayerDrop_cuda.py new file mode 100644 index 00000000..ad046e62 --- /dev/null +++ b/S1/gsd123_#70/LayerDrop_cuda.py @@ -0,0 +1,95 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, p=0.2): + super().__init__() + self.p = p + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor layer_drop_cuda(torch::Tensor x, torch::Tensor mask, float p); + """ + + cuda_source = """ + #include + + __global__ void layer_drop_vec4_kernel( + const float* __restrict__ x, + const float* __restrict__ mask, + float* __restrict__ y, + int feature_dim, + int batch_size, + float scale) + { + int bid = blockIdx.x; + if (bid >= batch_size) return; + + float m = mask[bid]; + float effective_scale = m * scale; + + // Optimization: If mask is 0, we can just write 0s or skip if initialized + // But for standard behavior we write the result + + const float4* x_row = reinterpret_cast(x + bid * feature_dim); + float4* y_row = reinterpret_cast(y + bid * feature_dim); + + int vec_dim = feature_dim / 4; + int tid = threadIdx.x; + + for (int i = tid; i < vec_dim; i += blockDim.x) { + float4 v = x_row[i]; + float4 out; + + out.x = v.x * effective_scale; + out.y = v.y * effective_scale; + out.z = v.z * effective_scale; + out.w = v.w * effective_scale; + + y_row[i] = out; + } + } + + torch::Tensor layer_drop_cuda(torch::Tensor x, torch::Tensor mask, float p) { + auto x_c = x.contiguous(); + auto mask_c = mask.contiguous(); + + int batch_size = x_c.size(0); + int feature_dim = x_c.size(1); + + TORCH_CHECK(feature_dim % 4 == 0, "Feature dim must be divisible by 4"); + + auto output = torch::empty_like(x_c); + float scale = 1.0f / (1.0f - p); + + int threads = 256; + int blocks = batch_size; + + layer_drop_vec4_kernel<<>>( + reinterpret_cast(x_c.data_ptr()), + mask_c.data_ptr(), + reinterpret_cast(output.data_ptr()), + feature_dim, + batch_size, + scale + ); + + return output; + } + """ + + self.op = load_inline( + name="layer_drop_opt_vec4", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["layer_drop_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x, mask): + return self.op.layer_drop_cuda(x, mask, self.p) \ No newline at end of file diff --git a/S1/gsd123_#70/LayerDrop_torch.py b/S1/gsd123_#70/LayerDrop_torch.py new file mode 100644 index 00000000..a410c573 --- /dev/null +++ b/S1/gsd123_#70/LayerDrop_torch.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, p=0.2): + super().__init__() + self.p = p + + def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + scale = 1.0 / (1.0 - self.p) + return x * mask.unsqueeze(-1) * scale + +batch_size = 1024 +feature_dim = 2048 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + mask = torch.bernoulli(torch.full((batch_size,), 0.8)).to(dtype=torch.float32) + return [x, mask] + +def get_init_inputs(): + return [0.2] \ No newline at end of file diff --git a/S1/gsd123_#70/prompt.txt b/S1/gsd123_#70/prompt.txt new file mode 100644 index 00000000..a217e8f7 --- /dev/null +++ b/S1/gsd123_#70/prompt.txt @@ -0,0 +1,83 @@ +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. + + +CUDA Optimization Strategies: + +Vectorized Memory Access + +Uses float4 for 4-element vector loads/stores + +Reduces memory instructions by 4x + +Requires feature dimension divisible by 4 + +Memory Access Pattern + +contiguous() tensors for coalescing + +__restrict__ pointers + +Row-based sequential access per batch + +Layer Drop Implementation + +Precomputes scaling factor: scale = 1/(1-p) + +Applies element-wise: x * mask * scale + +Efficient scaling with vector operations + +Kernel Design + +One block per batch sample + +256 threads per block for feature processing + +Grid-stride loop within each block + +Performance Optimization + +Compiler flag: -O3 + +Efficient branching (mask applied per sample) + +Minimal control flow divergence + +Numerical Efficiency + +Single scaling factor per sample + +Vectorized multiplication operations + +No expensive operations or reductions + +Key Innovation: Vectorized layer drop implementation with per-sample masking and scaling, optimized for transformer layer dropout during training. + + + + +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 + +class Model(nn.Module): + def __init__(self, p=0.2): + super().__init__() + self.p = p + + def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + scale = 1.0 / (1.0 - self.p) + return x * mask.unsqueeze(-1) * scale + +batch_size = 1024 +feature_dim = 2048 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + mask = torch.bernoulli(torch.full((batch_size,), 0.8)).to(dtype=torch.float32) + return [x, mask] + +def get_init_inputs(): + return [0.2] \ No newline at end of file diff --git a/S1/gsd123_#70/run_code.py b/S1/gsd123_#70/run_code.py new file mode 100644 index 00000000..2f7fc7e3 --- /dev/null +++ b/S1/gsd123_#70/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from LayerDrop_torch import Model, get_inputs, get_init_inputs +from LayerDrop_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