From c88899a43e3154fca2566fcdfbaeebde02b638f9 Mon Sep 17 00:00:00 2001 From: uucoco Date: Wed, 10 Dec 2025 19:07:43 +0800 Subject: [PATCH] finish expnormalizelog #86 --- S1/uucoco_#86/expnormalizelog_cuda.py | 114 +++++++++++++++++++++++++ S1/uucoco_#86/expnormalizelog_torch.py | 22 +++++ S1/uucoco_#86/prompt.txt | 80 +++++++++++++++++ S1/uucoco_#86/run_code.py | 77 +++++++++++++++++ 4 files changed, 293 insertions(+) create mode 100644 S1/uucoco_#86/expnormalizelog_cuda.py create mode 100644 S1/uucoco_#86/expnormalizelog_torch.py create mode 100644 S1/uucoco_#86/prompt.txt create mode 100644 S1/uucoco_#86/run_code.py diff --git a/S1/uucoco_#86/expnormalizelog_cuda.py b/S1/uucoco_#86/expnormalizelog_cuda.py new file mode 100644 index 0000000..bf4ebca --- /dev/null +++ b/S1/uucoco_#86/expnormalizelog_cuda.py @@ -0,0 +1,114 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__inline__ __device__ float warpReduceSum(float val) { + for (int offset = 16; offset > 0; offset /= 2) + val += __shfl_down_sync(0xffffffff, val, offset); + return val; +} + +__inline__ __device__ float blockReduceSum(float val) { + static __shared__ float shared[32]; + int lane = threadIdx.x % 32; + int wid = threadIdx.x / 32; + + val = warpReduceSum(val); + + if (lane == 0) shared[wid] = val; + __syncthreads(); + + val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0f; + + if (wid == 0) val = warpReduceSum(val); + + return val; +} + +__global__ void exp_normalize_log_kernel( + const float* __restrict__ input, + float* __restrict__ output, + int rows, + int cols, + float eps +) { + int bid = blockIdx.x; + int tid = threadIdx.x; + + if (bid >= rows) return; + + const float* row_in = input + bid * cols; + float* row_out = output + bid * cols; + + // Pass 1: Compute Y = exp(X) and Sum of Squares of Y + float sum_sq = 0.0f; + for (int i = tid; i < cols; i += blockDim.x) { + float y = expf(row_in[i]); + sum_sq += y * y; + } + + sum_sq = blockReduceSum(sum_sq); + + __shared__ float inv_norm; + if (tid == 0) { + inv_norm = rsqrtf(sum_sq + eps); + } + __syncthreads(); + + float norm_factor = inv_norm; + + // Pass 2: Normalize (Y * inv_norm) and Log + for (int i = tid; i < cols; i += blockDim.x) { + float y = expf(row_in[i]); + float z = y * norm_factor; + row_out[i] = logf(z); + } +} + +torch::Tensor exp_normalize_log_cuda(torch::Tensor input) { + auto output = torch::empty_like(input); + + int cols = input.size(input.dim() - 1); + int rows = input.numel() / cols; + + int block_size = 256; + while (block_size < cols && block_size < 1024) { + block_size *= 2; + } + + exp_normalize_log_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + rows, + cols, + 1e-12f + ); + + return output; +} +""" + +cpp_source = """ +torch::Tensor exp_normalize_log_cuda(torch::Tensor input); +""" + +module = load_inline( + name="exp_normalize_log", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["exp_normalize_log_cuda"], + verbose=True +) + + +class ModelNew(nn.Module): + def __init__(self): + super(ModelNew, self).__init__() + self.module = module + + def forward(self, x): + return self.module.exp_normalize_log_cuda(x) \ No newline at end of file diff --git a/S1/uucoco_#86/expnormalizelog_torch.py b/S1/uucoco_#86/expnormalizelog_torch.py new file mode 100644 index 0000000..ac089ee --- /dev/null +++ b/S1/uucoco_#86/expnormalizelog_torch.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, x): + y = torch.exp(x) + z = F.normalize(y, p=2.0, dim=-1, eps=1e-12) + return torch.log(z) + +batch_size = 1024 +dim = 1024 + +def get_inputs(): + x = torch.randn(batch_size, dim) + return [x] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/uucoco_#86/prompt.txt b/S1/uucoco_#86/prompt.txt new file mode 100644 index 0000000..8a6bbb2 --- /dev/null +++ b/S1/uucoco_#86/prompt.txt @@ -0,0 +1,80 @@ +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 +- **PyTorch**: Deep learning framework +- **CUDA**: NVIDIA GPU parallel computing +- **C++**: Kernel implementation + +## Advanced CUDA Features +- **Warp reduction**: `__shfl_down_sync()` for warp-level operations +- **Block reduction**: Two-level reduction (warp + shared memory) +- **Row-wise processing**: One CUDA block per row +- **Dynamic block sizing**: Adaptive thread block size +- **CUDA intrinsics**: `rsqrtf()` for reciprocal square root + +## Mathematical Operations +- **Exponential**: `expf(x)` element-wise +- **L2 Normalization**: Compute and apply vector norms +- **Logarithm**: `logf(z)` where z = normalized exp(x) +- **Sum of squares**: Compute squared L2 norm +- **Reciprocal square root**: `rsqrtf()` for normalization factor + +## Parallel Patterns +- **Two-pass algorithm**: First compute norm, then apply normalization +- **Row-level parallelism**: Each block processes one row +- **Efficient reduction**: Custom warp/block reduction functions +- **Grid-stride loops**: Threads process multiple columns per row + +## Optimization Techniques +- **Fused operations**: exp + normalize + log in single kernel +- **Numerical stability**: Epsilon (1e-12) for division safety +- **Memory coalescing**: Row-major access patterns +- **Adaptive block size**: Dynamically adjusted for column count + +## Performance Features +- **Massive parallelism**: Row-level and column-level parallelism +- **Low synchronization**: Minimal `__syncthreads()` usage +- **Efficient math**: Use of `rsqrtf()` intrinsic +- **Memory efficiency**: Shared memory for reduction results + +## Unique Mathematical Property +- **Composite function**: Computes log(exp(x)/||exp(x)||₂) +- **Numerical stability**: Handles large values via normalization +- **Softmax alternative**: Similar to log-softmax but with L2 norm +- **Row-wise normalization**: Each output row normalized independently + +## Numerical Considerations +- **Overflow prevention**: Normalization stabilizes exp() computation +- **Epsilon protection**: Prevents division by zero +- **Log domain safety**: Ensures positive argument for log() +- **Adaptive block size**: Optimized for varying column dimensions + + + +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(Model, self).__init__() + + def forward(self, x): + y = torch.exp(x) + z = F.normalize(y, p=2.0, dim=-1, eps=1e-12) + return torch.log(z) + +batch_size = 1024 +dim = 1024 + +def get_inputs(): + x = torch.randn(batch_size, dim) + return [x] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/uucoco_#86/run_code.py b/S1/uucoco_#86/run_code.py new file mode 100644 index 0000000..7398db4 --- /dev/null +++ b/S1/uucoco_#86/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from expnormalizelog_torch import Model, get_inputs, get_init_inputs +from expnormalizelog_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