finish gateblendnormalize #89

This commit is contained in:
wawahejun 2025-12-13 18:50:11 +08:00
commit 46e2f0bb16
4 changed files with 313 additions and 0 deletions

View File

@ -0,0 +1,119 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__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 gate_blend_normalize_kernel(
const float* __restrict__ a,
const float* __restrict__ b,
const float* __restrict__ gate,
float* __restrict__ output,
int rows,
int cols,
float eps
) {
int bid = blockIdx.x;
int tid = threadIdx.x;
if (bid >= rows) return;
const float* a_row = a + bid * cols;
const float* b_row = b + bid * cols;
const float* gate_row = gate + bid * cols;
float* out_row = output + bid * cols;
float sum_sq = 0.0f;
for (int i = tid; i < cols; i += blockDim.x) {
float g = gate_row[i];
float blended = g * a_row[i] + (1.0f - g) * b_row[i];
sum_sq += blended * blended;
}
sum_sq = blockReduceSum(sum_sq);
__shared__ float inv_norm;
if (tid == 0) {
inv_norm = rsqrtf(sum_sq + eps);
}
__syncthreads();
float norm_factor = inv_norm;
for (int i = tid; i < cols; i += blockDim.x) {
float g = gate_row[i];
float blended = g * a_row[i] + (1.0f - g) * b_row[i];
out_row[i] = blended * norm_factor;
}
}
torch::Tensor gate_blend_normalize_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor gate) {
auto output = torch::empty_like(a);
int cols = a.size(a.dim() - 1);
int rows = a.numel() / cols;
int block_size = 256;
while (block_size < cols && block_size < 1024) {
block_size *= 2;
}
gate_blend_normalize_kernel<<<rows, block_size>>>(
a.data_ptr<float>(),
b.data_ptr<float>(),
gate.data_ptr<float>(),
output.data_ptr<float>(),
rows,
cols,
1e-12f
);
return output;
}
"""
cpp_source = """
torch::Tensor gate_blend_normalize_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor gate);
"""
module = load_inline(
name="gate_blend_normalize",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["gate_blend_normalize_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.module = module
def forward(self, a, b, gate):
return self.module.gate_blend_normalize_cuda(a, b, gate)

View File

@ -0,0 +1,23 @@
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, a, b, gate):
blended = gate * a + (1 - gate) * b
return F.normalize(blended, p=2.0, dim=-1, eps=1e-12)
batch_size = 1024
dim = 1024
def get_inputs():
a = torch.randn(batch_size, dim)
b = torch.randn(batch_size, dim)
gate = torch.rand(batch_size, dim)
return [a, b, gate]
def get_init_inputs():
return []

94
S1/uucoco_#89/prompt.txt Normal file
View File

@ -0,0 +1,94 @@
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
C++: For high-performance kernel implementation
CUDA/C++ Advanced Features
Warp Reduction: __shfl_down_sync() for warp-level operations
Block Reduction: Two-level reduction (warp + shared memory)
CUDA Intrinsics: rsqrtf() for reciprocal square root
Dynamic Block Sizing: Adaptive thread block size based on columns
Row-Level Parallelism: One CUDA block per row
Mathematical Operations
Gated Blending: g*a + (1-g)*b (element-wise gating)
L2 Normalization: Compute and apply vector norms
Reciprocal Square Root: Efficient 1/sqrt(x) computation
Sum of Squares: Compute squared L2 norm
Parallel Patterns
Row-Based Processing: Each block processes one row
Two-Pass Algorithm: First compute norm, then normalize
Efficient Reduction: Warp shuffles + shared memory
Grid-Stride Loops: Within each row for column processing
Optimization Techniques
Fused Operations: Blend and normalize 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 Aspects
Three-Input Gating: Uses gate tensor to blend two inputs
Per-Row Normalization: Each output row has unit L2 norm
Advanced Reduction: Custom two-level reduction functions
Auto-tuning: Block size adapts to input 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, a, b, gate):
blended = gate * a + (1 - gate) * b
return F.normalize(blended, p=2.0, dim=-1, eps=1e-12)
batch_size = 1024
dim = 1024
def get_inputs():
a = torch.randn(batch_size, dim)
b = torch.randn(batch_size, dim)
gate = torch.rand(batch_size, dim)
return [a, b, gate]
def get_init_inputs():
return []

77
S1/uucoco_#89/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from gateblendnormalize_torch import Model, get_inputs, get_init_inputs
from gateblendnormalize_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()