finish signmuladd #108

This commit is contained in:
uucoco 2025-12-10 19:36:52 +08:00
parent 10eed82956
commit dc5fb4e1f0
4 changed files with 232 additions and 0 deletions

61
S1/uucoco_#108/prompt.txt Normal file
View File

@ -0,0 +1,61 @@
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.
Technologies Used in This Code
Core Libraries
PyTorch: Deep learning framework
CUDA: GPU parallel computing
C++: Kernel implementation
CUDA Components
CUDA kernel: sign_mul_add_kernel
Element-wise parallelism: One thread per element
Simple branching: Sign extraction logic
Mathematical Operations
Sign function: Extract sign of tensor a (1, 0, or -1)
Element-wise multiplication: sign(a) × b
Element-wise addition: (sign(a) × b) + c
Three-input operation: Combines three tensors
Architecture
Standard CUDA pattern: 1D grid/block configuration
Three tensor inputs: a, b, c of same shape
Conditional logic: Branching for sign extraction
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, a, b, c):
return torch.sign(a) * b + c
batch_size = 4096
dim = 1024
def get_inputs():
a = torch.randn(batch_size, dim)
b = torch.randn(batch_size, dim)
c = torch.randn(batch_size, dim)
return [a, b, c]
def get_init_inputs():
return []

View File

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

View File

@ -0,0 +1,73 @@
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>
__global__ void sign_mul_add_kernel(
const float* __restrict__ a,
const float* __restrict__ b,
const float* __restrict__ c,
float* __restrict__ output,
int size
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < size) {
float a_val = a[idx];
float b_val = b[idx];
float c_val = c[idx];
float sign_val;
if (a_val > 0.0f) {
sign_val = 1.0f;
} else if (a_val < 0.0f) {
sign_val = -1.0f;
} else {
sign_val = 0.0f;
}
output[idx] = sign_val * b_val + c_val;
}
}
torch::Tensor sign_mul_add_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c) {
auto output = torch::empty_like(a);
int size = a.numel();
const int block_size = 256;
int num_blocks = (size + block_size - 1) / block_size;
sign_mul_add_kernel<<<num_blocks, block_size>>>(
a.data_ptr<float>(),
b.data_ptr<float>(),
c.data_ptr<float>(),
output.data_ptr<float>(),
size
);
return output;
}
"""
cpp_source = """
torch::Tensor sign_mul_add_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c);
"""
module = load_inline(
name="sign_mul_add",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["sign_mul_add_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.module = module
def forward(self, a, b, c):
return self.module.sign_mul_add_cuda(a, b, c)

View File

@ -0,0 +1,21 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, a, b, c):
return torch.sign(a) * b + c
batch_size = 4096
dim = 1024
def get_inputs():
a = torch.randn(batch_size, dim)
b = torch.randn(batch_size, dim)
c = torch.randn(batch_size, dim)
return [a, b, c]
def get_init_inputs():
return []