Add RmsNorm operator

This commit is contained in:
daysgone 2025-10-12 11:07:15 +08:00
parent 2f77913144
commit 8e2a2877df
4 changed files with 251 additions and 0 deletions

29
S1/RMSNorm/prompt.txt Normal file
View File

@ -0,0 +1,29 @@
You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.norm = nn.RMSNorm(128)
def forward(self, x):
return self.norm(x)
def get_inputs():
x = torch.randn(1, 128).cuda()
return [x]
def get_init_inputs():
return []
```

101
S1/RMSNorm/rmsnorm_cuda.py Normal file
View File

@ -0,0 +1,101 @@
import torch
from torch.utils.cpp_extension import load_inline
rmsnorm_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__global__ void rmsnorm_kernel(
const float* __restrict__ x,
const float* __restrict__ weight,
float* __restrict__ y,
int batch,
int features,
float eps
) {
int row = blockIdx.x;
if (row >= batch) return;
int tid = threadIdx.x;
extern __shared__ float sdata[];
float sum_sq = 0.0f;
for (int i = tid; i < features; i += blockDim.x) {
float v = x[row * features + i];
sum_sq += v * v;
}
sdata[tid] = sum_sq;
__syncthreads();
for (int offset = blockDim.x >> 1; offset > 0; offset >>= 1) {
if (tid < offset) {
sdata[tid] += sdata[tid + offset];
}
__syncthreads();
}
float rms = rsqrtf(sdata[0] / features + eps);
__syncthreads(); // 保证 rms 可见
for (int i = tid; i < features; i += blockDim.x) {
float v = x[row * features + i];
float w = weight[i];
y[row * features + i] = v * rms * w;
}
}
torch::Tensor rmsnorm_cuda(torch::Tensor x, torch::Tensor weight, float eps) {
TORCH_CHECK(x.is_cuda(), "x 必须是 CUDA 张量");
TORCH_CHECK(weight.is_cuda(), "weight 必须是 CUDA 张量");
TORCH_CHECK(x.dim() == 2, "当前内核仅支持二维输入张量");
TORCH_CHECK(weight.dim() == 1, "RMSNorm 权重必须是一维向量");
TORCH_CHECK(x.size(1) == weight.size(0), "输入最后一维与权重长度不匹配");
int batch = x.size(0);
int features = x.size(1);
auto y = torch::empty_like(x);
int threads = 256;
if (features < threads) {
threads = 1;
while (threads < features) threads <<= 1;
if (threads < 32) threads = 32;
}
size_t shared = threads * sizeof(float);
rmsnorm_kernel<<<batch, threads, shared>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
y.data_ptr<float>(),
batch,
features,
eps
);
return y;
}
"""
rmsnorm_cpp_source = """
torch::Tensor rmsnorm_cuda(torch::Tensor x, torch::Tensor weight, float eps);
"""
rmsnorm = load_inline(
name="rmsnorm",
cpp_sources=rmsnorm_cpp_source,
cuda_sources=rmsnorm_source,
functions=["rmsnorm_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self, weight: torch.Tensor, eps: float = 1e-6):
super().__init__()
if weight.dim() != 1:
raise ValueError("RMSNorm 权重必须是一维向量。")
self.weight = nn.Parameter(weight.clone())
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
return rmsnorm.rmsnorm_cuda(x, self.weight, self.eps)

View File

@ -0,0 +1,33 @@
import torch
import torch.nn as nn
class Model(nn.Module):
"""使用 PyTorch RMSNorm 的基准实现。"""
def __init__(self, weight: torch.Tensor, eps: float = 1e-6):
super().__init__()
if weight.dim() != 1:
raise ValueError("RMSNorm 权重必须是一维向量。")
feature_dim = weight.shape[0]
self.rmsnorm = nn.RMSNorm(feature_dim, eps=eps, elementwise_affine=True)
with torch.no_grad():
self.rmsnorm.weight.copy_(weight)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""直接对输入做 RMSNorm输出形状与输入一致。"""
return self.rmsnorm(x)
batch_size = 16
feature_dim = 2048
def get_inputs():
x = torch.randn(batch_size, feature_dim)
return [x]
def get_init_inputs():
weight = torch.randn(feature_dim)
return [weight]

88
S1/RMSNorm/run_code.py Normal file
View File

@ -0,0 +1,88 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from rmsnorm_torch import Model, get_inputs, get_init_inputs
from rmsnorm_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)
# 更严格的精度检查
abs_diff = (output_torch - output_cuda).abs()
max_diff = abs_diff.max().item()
mean_diff = abs_diff.mean().item()
print(f"最大差异: {max_diff:.6f}")
print(f"平均差异: {mean_diff:.6f}")
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
if precision_flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
# Warm up
for _ in range(100):
_ = 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 平均执行时间: {torch_time:.6f}")
print(f"自定义 CUDA ReLU 平均执行时间: {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()