This commit is contained in:
ZZZJ 2025-10-29 10:49:42 +08:00
parent bee0a2a683
commit 8751927b14
4 changed files with 253 additions and 0 deletions

34
S1/1/prompt.txt Normal file
View File

@ -0,0 +1,34 @@
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
# swiglu_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
SwiGLU(x) = SiLU(gate) * act
"""
gate, act = x.chunk(2, dim=-1)
return F.silu(gate) * act
batch_size = 4096
feature_dim = 4096
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []

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

@ -0,0 +1,88 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from swiglu_torch import Model, get_inputs, get_init_inputs
from swiglu_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 (matmul + relu) 平均执行时间: {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()

104
S1/1/swiglu_cuda.py Normal file
View File

@ -0,0 +1,104 @@
# swiglu_cuda.py
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from swiglu_torch import feature_dim
assert (feature_dim / 2) % 2 == 0, "feature_dim/2 must be a multiple of 2 for float2 vectorization"
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
torch::Tensor swiglu_forward_cuda(torch::Tensor input);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <cmath> // For expf
__global__ void swiglu_fused_vectorized_kernel(
const float* __restrict__ x,
float* __restrict__ y,
int feature_dim, // 原始输入的特征维度
int n_elements_out // 输出张量的元素总数
) {
const float2* x2 = reinterpret_cast<const float2*>(x);
float2* y2 = reinterpret_cast<float2*>(y);
int n_work_items = n_elements_out / 2;
int grid_stride = gridDim.x * blockDim.x;
for (int idx = blockIdx.x * blockDim.x + threadIdx.x;
idx < n_work_items;
idx += grid_stride)
{
int feature_dim_out_f2 = (feature_dim / 2) / 2;
int feature_dim_in_f2 = feature_dim / 2;
int row = idx / feature_dim_out_f2;
int col_f2 = idx % feature_dim_out_f2;
int gate_idx_f2 = row * feature_dim_in_f2 + col_f2;
int act_idx_f2 = gate_idx_f2 + feature_dim_out_f2;
float2 gate_vec = x2[gate_idx_f2];
float2 act_vec = x2[act_idx_f2];
float sigmoid_gate_x = 1.0f / (1.0f + expf(-gate_vec.x));
float silu_out_x = gate_vec.x * sigmoid_gate_x;
float sigmoid_gate_y = 1.0f / (1.0f + expf(-gate_vec.y));
float silu_out_y = gate_vec.y * sigmoid_gate_y;
y2[idx] = make_float2(silu_out_x * act_vec.x, silu_out_y * act_vec.y);
}
}
torch::Tensor swiglu_forward_cuda(torch::Tensor input) {
input = input.contiguous();
TORCH_CHECK(input.size(-1) % 2 == 0, "Last dimension must be even for SwiGLU");
auto original_sizes = input.sizes().vec();
int feature_dim = original_sizes.back();
original_sizes.back() /= 2;
auto output = torch::empty(original_sizes, input.options());
int n_elements_out = output.numel();
TORCH_CHECK(n_elements_out % 2 == 0, "Output elements must be even for float2 vectorization");
const int block_size = 256;
const int n_work_items = n_elements_out / 2;
const int grid_size = (n_work_items + block_size - 1) / block_size;
swiglu_fused_vectorized_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
feature_dim,
n_elements_out
);
return output;
}
"""
self.swiglu_op = load_inline(
name="swiglu_fused_vectorized_op_fixed",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["swiglu_forward_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=True
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.swiglu_op.swiglu_forward_cuda(x)

27
S1/1/swiglu_torch.py Normal file
View File

@ -0,0 +1,27 @@
# swiglu_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
SwiGLU(x) = SiLU(gate) * act
"""
gate, act = x.chunk(2, dim=-1)
return F.silu(gate) * act
batch_size = 4096
feature_dim = 4096
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []