finish logsigmoid (affine-gate) #41

This commit is contained in:
Ljy123 2025-12-03 23:40:06 +08:00
parent 10eed82956
commit be3b41a2a8
4 changed files with 133 additions and 0 deletions

55
S1/Ljy123_#41/cudacode.py Normal file
View File

@ -0,0 +1,55 @@
import torch
from torch.utils.cpp_extension import load_inline
source = """
#include <torch/extension.h>
__global__ void logsigmoid_affine_gate_kernel(const float* x, const float* scale, const float* bias, float* y, int B, int D){
long long tid = blockIdx.x * blockDim.x + threadIdx.x;
long long stride = blockDim.x * gridDim.x;
long long total = (long long)B * D;
for(long long i = tid; i < total; i += stride){
int b = (int)(i / D);
int d = (int)(i % D);
float z = x[i] * scale[d] + bias[d];
float g = -log1pf(expf(-z));
y[i] = x[i] * g;
}
}
torch::Tensor logsigmoid_affine_gate_cuda(torch::Tensor x, torch::Tensor scale, torch::Tensor bias){
auto xc = x.contiguous();
auto sc = scale.contiguous();
auto bc = bias.contiguous();
auto y = torch::empty_like(xc);
int B = (int)xc.size(0);
int D = (int)xc.size(1);
int block = 1024;
int grid = (int)((long long)B * D / block);
if(grid < 1) grid = 1; if(grid > 65535) grid = 65535;
logsigmoid_affine_gate_kernel<<<grid, block>>>(xc.data_ptr<float>(), sc.data_ptr<float>(), bc.data_ptr<float>(), y.data_ptr<float>(), B, D);
return y;
}
"""
cpp_source = """
torch::Tensor logsigmoid_affine_gate_cuda(torch::Tensor x, torch::Tensor scale, torch::Tensor bias);
"""
ops = load_inline(
name="logsigmoid_affine_gate",
cpp_sources=cpp_source,
cuda_sources=source,
functions=["logsigmoid_affine_gate_cuda"],
verbose=True
)
class ModelNew(torch.nn.Module):
def __init__(self, scale: torch.Tensor, bias: torch.Tensor):
super(ModelNew, self).__init__()
self.ops = ops
self.register_buffer("scale", scale)
self.register_buffer("bias", bias)
def forward(self, x: torch.Tensor):
return self.ops.logsigmoid_affine_gate_cuda(x, self.scale, self.bias)

2
S1/Ljy123_#41/prompt.txt Normal file
View File

@ -0,0 +1,2 @@
You write custom CUDA kernels to replace PyTorch operators for speedups.
Implement LogSigmoid Affine Gate: For x[B,D], per-dim scale[D] and bias[D], compute z = x*scale + bias, gate g = logsigmoid(z) = -log(1+exp(-z)), and output y = x * g. Use a single grid-stride kernel to fuse affine, logsigmoid, and gating into one pass. Provide a PyTorch reference using nn.Parameters. Accuracy rtol=1e-3.

52
S1/Ljy123_#41/run_code.py Normal file
View File

@ -0,0 +1,52 @@
import torch
import time
from torchcode import Model, get_inputs, get_init_inputs
from cudacode import ModelNew
def run_benchmark():
if not torch.cuda.is_available():
print("CUDA 不可用,请确保您有可用的 NVIDIA GPU 并已正确安装 PyTorch CUDA 版本。")
return
device = torch.device("cuda")
init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()]
inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_inputs()]
torch_model = Model(*init_inputs).cuda()
cuda_model = ModelNew(*init_inputs).cuda()
torch_model.eval(); cuda_model.eval()
print("-------------------- 精度对齐验证 --------------------")
with torch.no_grad():
out_torch = torch_model(*inputs)
out_cuda = cuda_model(*inputs)
flag = torch.allclose(out_torch, out_cuda, rtol=1e-03)
if flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print(f"最大绝对误差: {(out_torch - out_cuda).abs().max().item()}" )
print("\n-------------------- 性能加速比测试 --------------------")
iters = 100
torch.cuda.synchronize(); t0 = time.time()
for _ in range(iters):
_ = torch_model(*inputs)
torch.cuda.synchronize(); t_torch = (time.time() - t0) / iters
torch.cuda.synchronize(); t0 = time.time()
for _ in range(iters):
_ = cuda_model(*inputs)
torch.cuda.synchronize(); t_cuda = (time.time() - t0) / iters
print(f"PyTorch LogSigmoid-Affine-Gate 平均执行时间: {t_torch:.6f}")
print(f"自定义 CUDA 融合内核 平均执行时间: {t_cuda:.6f}")
sp = t_torch / t_cuda if t_cuda > 0 else 0
if t_cuda > 0:
print(f"加速比 (Speedup): {sp:.2f}x")
else:
print("CUDA 内核执行时间为0无法计算加速比。")
return flag, sp
if __name__ == "__main__":
run_benchmark()

View File

@ -0,0 +1,24 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, scale: torch.Tensor, bias: torch.Tensor):
super(Model, self).__init__()
self.scale = nn.Parameter(scale)
self.bias = nn.Parameter(bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
z = x * self.scale.view(1,-1) + self.bias.view(1,-1)
g = torch.nn.functional.logsigmoid(z)
return x * g
B, D = 64, 8192
def get_inputs():
x = torch.randn(B, D)
return [x]
def get_init_inputs():
scale = torch.randn(D)
bias = torch.randn(D)
return [scale, bias]