forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish CrossLayerNorm #136' (#788) from ZZZJ/GPUCodeForces:CrossLayerNorm into main
This commit is contained in:
commit
e409972e99
|
|
@ -0,0 +1,149 @@
|
|||
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.hidden_dim = 4096
|
||||
self.weight = nn.Parameter(torch.ones(self.hidden_dim, device='cuda'))
|
||||
self.eps = 1e-6
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor cross_ln_cuda(torch::Tensor x, torch::Tensor res, torch::Tensor weight, float eps);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
|
||||
// Warp Reduce
|
||||
__device__ __forceinline__ float warpReduceSum(float val) {
|
||||
#pragma unroll
|
||||
for (int offset = 16; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
return val;
|
||||
}
|
||||
|
||||
// Block Reduce
|
||||
__device__ __forceinline__ 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;
|
||||
}
|
||||
|
||||
// Fused Kernel: Add + RMSNorm with Float4
|
||||
__global__ void cross_ln_f4_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ res,
|
||||
const float* __restrict__ weight,
|
||||
float* __restrict__ output,
|
||||
int hidden_dim,
|
||||
int n_vec, // hidden_dim / 4
|
||||
float eps
|
||||
) {
|
||||
// Grid.x = Batch (Rows)
|
||||
int row_idx = blockIdx.x;
|
||||
int tid = threadIdx.x;
|
||||
|
||||
int offset = row_idx * hidden_dim;
|
||||
const float4* x_ptr = reinterpret_cast<const float4*>(x + offset);
|
||||
const float4* res_ptr = reinterpret_cast<const float4*>(res + offset);
|
||||
const float4* w_ptr = reinterpret_cast<const float4*>(weight);
|
||||
float4* out_ptr = reinterpret_cast<float4*>(output + offset);
|
||||
|
||||
// --- Pass 1: Sum of Squares (Compute Variance) ---
|
||||
float sum_sq = 0.0f;
|
||||
|
||||
for (int i = tid; i < n_vec; i += BLOCK_SIZE) {
|
||||
float4 vx = x_ptr[i];
|
||||
float4 vr = res_ptr[i];
|
||||
|
||||
// Fused Add
|
||||
float v0 = vx.x + vr.x;
|
||||
float v1 = vx.y + vr.y;
|
||||
float v2 = vx.z + vr.z;
|
||||
float v3 = vx.w + vr.w;
|
||||
|
||||
// Accumulate Square
|
||||
sum_sq += v0*v0 + v1*v1 + v2*v2 + v3*v3;
|
||||
}
|
||||
|
||||
// Block Reduction
|
||||
sum_sq = blockReduceSum(sum_sq);
|
||||
|
||||
// Broadcast Rsqrt
|
||||
__shared__ float rscale;
|
||||
if (tid == 0) {
|
||||
rscale = rsqrtf(sum_sq / (float)hidden_dim + eps);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float scale = rscale;
|
||||
|
||||
// --- Pass 2: Normalize and Write ---
|
||||
for (int i = tid; i < n_vec; i += BLOCK_SIZE) {
|
||||
float4 vx = x_ptr[i];
|
||||
float4 vr = res_ptr[i];
|
||||
float4 w = w_ptr[i];
|
||||
float4 out;
|
||||
|
||||
// Re-compute Add & Normalize
|
||||
out.x = (vx.x + vr.x) * scale * w.x;
|
||||
out.y = (vx.y + vr.y) * scale * w.y;
|
||||
out.z = (vx.z + vr.z) * scale * w.z;
|
||||
out.w = (vx.w + vr.w) * scale * w.w;
|
||||
|
||||
// Write
|
||||
out_ptr[i] = out;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor cross_ln_cuda(torch::Tensor x, torch::Tensor res, torch::Tensor weight, float eps) {
|
||||
int batch_seq = x.size(0);
|
||||
int hidden_dim = x.size(1);
|
||||
|
||||
auto output = torch::empty_like(x);
|
||||
|
||||
if (hidden_dim % 4 != 0) return output;
|
||||
|
||||
int n_vec = hidden_dim / 4;
|
||||
|
||||
// Grid = Batch Size, Block = 256
|
||||
cross_ln_f4_kernel<<<batch_seq, BLOCK_SIZE>>>(
|
||||
x.data_ptr<float>(),
|
||||
res.data_ptr<float>(),
|
||||
weight.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
hidden_dim,
|
||||
n_vec,
|
||||
eps
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="cross_ln_f4_optimized_v2",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["cross_ln_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
||||
if not x.is_contiguous(): x = x.contiguous()
|
||||
if not residual.is_contiguous(): residual = residual.contiguous()
|
||||
return self.op.cross_ln_cuda(x, residual, self.weight, self.eps)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
BATCH_SEQ = 8192
|
||||
HIDDEN_DIM = 4096
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(HIDDEN_DIM))
|
||||
self.eps = 1e-6
|
||||
|
||||
def forward(self, x: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
added = x + residual
|
||||
|
||||
input_dtype = added.dtype
|
||||
added_f32 = added.to(torch.float32)
|
||||
variance = added_f32.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = added_f32 * torch.rsqrt(variance + self.eps)
|
||||
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(BATCH_SEQ, HIDDEN_DIM, device='cuda', dtype=torch.float32)
|
||||
res = torch.randn(BATCH_SEQ, HIDDEN_DIM, device='cuda', dtype=torch.float32)
|
||||
return [x, res]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
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
|
||||
|
||||
|
||||
BATCH_SEQ = 8192
|
||||
HIDDEN_DIM = 4096
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(HIDDEN_DIM))
|
||||
self.eps = 1e-6
|
||||
|
||||
def forward(self, x: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
added = x + residual
|
||||
|
||||
input_dtype = added.dtype
|
||||
added_f32 = added.to(torch.float32)
|
||||
variance = added_f32.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = added_f32 * torch.rsqrt(variance + self.eps)
|
||||
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(BATCH_SEQ, HIDDEN_DIM, device='cuda', dtype=torch.float32)
|
||||
res = torch.randn(BATCH_SEQ, HIDDEN_DIM, device='cuda', dtype=torch.float32)
|
||||
return [x, res]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from cross_layer_norm_torch import Model,get_inputs,get_init_inputs
|
||||
from cross_layer_norm_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()
|
||||
Loading…
Reference in New Issue