finish chebyshev_abs_square #119

This commit is contained in:
uucoco 2025-12-10 19:54:48 +08:00
parent 10eed82956
commit c7cf4d7d9a
4 changed files with 208 additions and 0 deletions

View File

@ -0,0 +1,56 @@
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>
__global__ void chebyshev_abs_square_kernel(const float* __restrict__ x, float* __restrict__ y, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
float val = x[idx];
float x2 = val * val;
float p = fmaf(16.0f, x2, -20.0f);
p = fmaf(p, x2, 5.0f);
p = p * val;
float abs_p = fabsf(p);
y[idx] = abs_p * abs_p;
}
}
torch::Tensor launch_chebyshev_abs_square(torch::Tensor x) {
auto n = x.numel();
auto y = torch::empty_like(x);
const int threads = 256;
const int blocks = (n + threads - 1) / threads;
chebyshev_abs_square_kernel<<<blocks, threads>>>(x.data_ptr<float>(), y.data_ptr<float>(), n);
return y;
}
"""
cpp_source = """
torch::Tensor launch_chebyshev_abs_square(torch::Tensor x);
"""
chebyshev_abs_square_module = load_inline(
name='chebyshev_abs_square_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['launch_chebyshev_abs_square'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.op = chebyshev_abs_square_module
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.op.launch_chebyshev_abs_square(x.contiguous())

View File

@ -0,0 +1,23 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x2 = x * x
x3 = x2 * x
x5 = x3 * x2
t5 = 16.0 * x5 - 20.0 * x3 + 5.0 * x
return torch.square(torch.abs(t5))
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
return []

52
S1/uucoco_#119/prompt.txt Normal file
View File

@ -0,0 +1,52 @@
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 Chebyshev polynomial + absolute value + square with CUDA optimizations:
Element-wise parallelism - Each thread processes one element independently (no reduction needed).
FMA (fused multiply-add) optimization - Uses fmaf() for efficient polynomial evaluation: 16x⁴ - 20x² + 5.
Chebyshev polynomial T₅(x) - Computes 5th-order Chebyshev polynomial: T₅(x) = 16x⁵ - 20x³ + 5x.
Fused operations - Combines polynomial evaluation, absolute value, and squaring in one kernel.
Memory coalescing - Contiguous tensor access patterns.
Grid-stride mapping - Standard 1D grid/block mapping for element-wise operations.
No shared memory - Simple element-wise kernel avoids synchronization overhead.
CUDA math functions - Uses fmaf() and fabsf() for hardware-accelerated operations.
Efficient polynomial computation - Uses Horner-like scheme with FMA for numerical stability.
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
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x2 = x * x
x3 = x2 * x
x5 = x3 * x2
t5 = 16.0 * x5 - 20.0 * x3 + 5.0 * x
return torch.square(torch.abs(t5))
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
return []

View File

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