fixes L2Normalize #126

This commit is contained in:
ZZZJ 2025-12-09 21:08:17 +08:00
parent cc73715277
commit 383b623ef2
4 changed files with 265 additions and 0 deletions

View File

@ -0,0 +1,139 @@
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/extension.h>
torch::Tensor l2_normalize_cuda(torch::Tensor input, float eps);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <math.h>
#define BLOCK_SIZE 256
__device__ __forceinline__ double warpReduceSum(double val) {
#pragma unroll
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_down_sync(0xffffffff, val, offset);
return val;
}
__device__ __forceinline__ double blockReduceSum(double val) {
static __shared__ double 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 < (BLOCK_SIZE / 32)) ? shared[lane] : 0.0;
if (wid == 0) val = warpReduceSum(val);
return val;
}
__global__ void l2_normalize_f4_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int rows,
int cols,
int n_vec, // cols / 4
float eps
) {
int row = blockIdx.x;
if (row >= rows) return;
int tid = threadIdx.x;
int stride = BLOCK_SIZE;
// Row pointers
const float* in_row = input + row * cols;
float* out_row = output + row * cols;
// 1. Reduce: Calculate Sum of Squares
double sum_sq = 0.0;
// Vectorized Loop
for (int i = tid; i < n_vec; i += stride) {
float4 v = reinterpret_cast<const float4*>(in_row)[i];
sum_sq += (double)v.x * v.x + (double)v.y * v.y +
(double)v.z * v.z + (double)v.w * v.w;
}
// Block Reduction
sum_sq = blockReduceSum(sum_sq);
// 2. Broadcast Inverse Norm
__shared__ float s_inv_norm;
if (tid == 0) {
// max(norm, eps) logic
// norm = sqrt(sum_sq)
float norm = sqrtf((float)sum_sq);
float max_norm = (norm > eps) ? norm : eps;
s_inv_norm = 1.0f / max_norm;
}
__syncthreads();
float inv_norm = s_inv_norm;
// 3. Apply & Write (Vectorized)
// Re-read input (Streaming load, fast cache hit)
for (int i = tid; i < n_vec; i += stride) {
float4 v = reinterpret_cast<const float4*>(in_row)[i];
float4 out_v;
out_v.x = v.x * inv_norm;
out_v.y = v.y * inv_norm;
out_v.z = v.z * inv_norm;
out_v.w = v.w * inv_norm;
reinterpret_cast<float4*>(out_row)[i] = out_v;
}
}
torch::Tensor l2_normalize_cuda(torch::Tensor input, float eps) {
int rows = input.size(0);
int cols = input.size(1);
auto output = torch::empty_like(input);
// Assume cols % 4 == 0 (4096 OK)
if (cols % 4 != 0) return output;
int n_vec = cols / 4;
dim3 grid(rows);
dim3 block(BLOCK_SIZE);
l2_normalize_f4_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
rows, cols, n_vec, eps
);
return output;
}
"""
self.op = load_inline(
name="l2_normalize_f4_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["l2_normalize_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not x.is_contiguous(): x = x.contiguous()
return self.op.l2_normalize_cuda(x, 1e-12)

View File

@ -0,0 +1,22 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH = 4096
DIM = 4096
EPS = 1e-12
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.normalize(x, p=2.0, dim=1, eps=EPS)
def get_inputs():
x = torch.randint(low=-5, high=6, size=(BATCH, DIM), device='cuda').float()
return [x]
def get_init_inputs():
return []

30
S1/ZZZJ_#126/prompt.txt Normal file
View File

@ -0,0 +1,30 @@
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
BATCH = 4096
DIM = 4096
EPS = 1e-12
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.normalize(x, p=2.0, dim=1, eps=EPS)
def get_inputs():
x = torch.randint(low=-5, high=6, size=(BATCH, DIM), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

74
S1/ZZZJ_#126/run_code.py Normal file
View File

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