finish cosine_swish_gelu #120

This commit is contained in:
uucoco 2025-12-10 19:55:44 +08:00
parent 10eed82956
commit 852b5121b4
4 changed files with 290 additions and 0 deletions

View File

@ -0,0 +1,122 @@
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>
#include <math.h>
__inline__ __device__ float warp_reduce(float val) {
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_down_sync(0xffffffff, val, offset);
return val;
}
__global__ void cosine_swish_gelu_kernel(
const float* __restrict__ x,
const float* __restrict__ target,
float* __restrict__ y,
int batch_size,
int width)
{
int row = blockIdx.x;
int tid = threadIdx.x;
if (row >= batch_size) return;
const float* row_x = x + row * width;
float sum_dot = 0.0f;
float sum_xx = 0.0f;
float sum_tt = 0.0f;
for (int i = tid; i < width; i += blockDim.x) {
float val_x = row_x[i];
float val_t = target[i];
sum_dot += val_x * val_t;
sum_xx += val_x * val_x;
sum_tt += val_t * val_t;
}
sum_dot = warp_reduce(sum_dot);
sum_xx = warp_reduce(sum_xx);
sum_tt = warp_reduce(sum_tt);
static __shared__ float shared_dot[32];
static __shared__ float shared_xx[32];
static __shared__ float shared_tt[32];
int lane = tid % 32;
int wid = tid / 32;
if (lane == 0) {
shared_dot[wid] = sum_dot;
shared_xx[wid] = sum_xx;
shared_tt[wid] = sum_tt;
}
__syncthreads();
sum_dot = (tid < blockDim.x / 32) ? shared_dot[lane] : 0.0f;
sum_xx = (tid < blockDim.x / 32) ? shared_xx[lane] : 0.0f;
sum_tt = (tid < blockDim.x / 32) ? shared_tt[lane] : 0.0f;
if (wid == 0) {
sum_dot = warp_reduce(sum_dot);
sum_xx = warp_reduce(sum_xx);
sum_tt = warp_reduce(sum_tt);
}
if (tid == 0) {
float norm_x = sqrtf(sum_xx);
float norm_t = sqrtf(sum_tt);
float cosine = sum_dot / (norm_x * norm_t + 1e-6f);
float swish = cosine / (1.0f + expf(-cosine));
float gelu = swish * 0.5f * (1.0f + erff(swish * 0.70710678f));
y[row] = gelu;
}
}
torch::Tensor launch_cosine_swish_gelu(torch::Tensor x, torch::Tensor target) {
auto batch_size = x.size(0);
auto width = x.size(1);
auto y = torch::empty({batch_size}, x.options());
const int threads = 256;
const int blocks = batch_size;
cosine_swish_gelu_kernel<<<blocks, threads>>>(
x.data_ptr<float>(),
target.data_ptr<float>(),
y.data_ptr<float>(),
batch_size,
width
);
return y;
}
"""
cpp_source = """
torch::Tensor launch_cosine_swish_gelu(torch::Tensor x, torch::Tensor target);
"""
cosine_swish_gelu_module = load_inline(
name='cosine_swish_gelu_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['launch_cosine_swish_gelu'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, target):
super(ModelNew, self).__init__()
self.target = nn.Parameter(target)
self.op = cosine_swish_gelu_module
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.op.launch_cosine_swish_gelu(x.contiguous(), self.target.contiguous())

View File

@ -0,0 +1,33 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, target):
super(Model, self).__init__()
self.target = nn.Parameter(target)
def forward(self, x: torch.Tensor) -> torch.Tensor:
dot = torch.sum(x * self.target, dim=-1)
norm_x = torch.sqrt(torch.sum(x * x, dim=-1))
norm_target = torch.sqrt(torch.sum(self.target * self.target, dim=-1))
cosine = dot / (norm_x * norm_target + 1e-6)
swish = cosine * torch.sigmoid(cosine)
return F.gelu(swish)
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
target = torch.randn(input_dim)
return [target]

58
S1/uucoco_#120/prompt.txt Normal file
View File

@ -0,0 +1,58 @@
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.
This code implements cosine similarity + Swish + GELU activation with CUDA optimizations:
Triple parallel reduction - Warp shuffle for three sums: dot product, x², t².
Three shared memory buffers - Separate buffers to avoid bank conflicts.
Fused activation chain - Computes cosine similarity → Swish → GELU in one kernel.
Grid-stride loop - Threads process multiple elements for load balancing.
Numerical stability - Adds 1e-6 to denominator for safe division.
CUDA math functions - Uses sqrtf(), expf(), erff() for hardware acceleration.
Memory coalescing - Contiguous tensor access patterns.
Batch parallelism - One CUDA block per input row.
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, target):
super(Model, self).__init__()
self.target = nn.Parameter(target)
def forward(self, x: torch.Tensor) -> torch.Tensor:
dot = torch.sum(x * self.target, dim=-1)
norm_x = torch.sqrt(torch.sum(x * x, dim=-1))
norm_target = torch.sqrt(torch.sum(self.target * self.target, dim=-1))
cosine = dot / (norm_x * norm_target + 1e-6)
swish = cosine * torch.sigmoid(cosine)
return F.gelu(swish)
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
target = torch.randn(input_dim)
return [target]

View File

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