forked from ccf-ai-infra/GPUCodeForces
finish spatial-diff gate #38
This commit is contained in:
parent
10eed82956
commit
e5cfdc480f
|
|
@ -0,0 +1,64 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
__global__ void spatial_diff_gate_kernel(const float* x, float* y, int N, int C, int H, int W, float alpha, float beta){
|
||||
long long tid = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
long long stride = blockDim.x * gridDim.x;
|
||||
long long total = (long long)N * C * H * W;
|
||||
for(long long i = tid; i < total; i += stride){
|
||||
long long w = i % W;
|
||||
long long hwc = i / W;
|
||||
long long h = hwc % H;
|
||||
long long nc = hwc / H;
|
||||
long long n = nc / C;
|
||||
long long c = nc % C;
|
||||
long long base = ((long long)n * C + c) * (long long)H * (long long)W + (long long)h * W;
|
||||
float xv = x[i];
|
||||
float prev = (w > 0) ? x[base + (w - 1)] : 0.0f;
|
||||
float d = (w > 0) ? (xv - prev) : 0.0f;
|
||||
float g = 1.0f / (1.0f + expf(-(alpha * d + beta)));
|
||||
y[i] = xv * g;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor spatial_diff_gate_cuda(torch::Tensor x, torch::Tensor alpha, torch::Tensor beta){
|
||||
auto xc = x.contiguous();
|
||||
auto y = torch::empty_like(xc);
|
||||
int N = (int)xc.size(0);
|
||||
int C = (int)xc.size(1);
|
||||
int H = (int)xc.size(2);
|
||||
int W = (int)xc.size(3);
|
||||
float a = alpha.item<float>();
|
||||
float b = beta.item<float>();
|
||||
int block = 1024;
|
||||
int grid = (int)((long long)N * C * H * W / block);
|
||||
if(grid < 1) grid = 1; if(grid > 65535) grid = 65535;
|
||||
spatial_diff_gate_kernel<<<grid, block>>>(xc.data_ptr<float>(), y.data_ptr<float>(), N, C, H, W, a, b);
|
||||
return y;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor spatial_diff_gate_cuda(torch::Tensor x, torch::Tensor alpha, torch::Tensor beta);
|
||||
"""
|
||||
|
||||
ops = load_inline(
|
||||
name="spatial_diff_gate",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=source,
|
||||
functions=["spatial_diff_gate_cuda"],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self, alpha: float, beta: float):
|
||||
super(ModelNew, self).__init__()
|
||||
self.ops = ops
|
||||
self.register_buffer("alpha", torch.tensor(float(alpha), dtype=torch.float32))
|
||||
self.register_buffer("beta", torch.tensor(float(beta), dtype=torch.float32))
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
return self.ops.spatial_diff_gate_cuda(x, self.alpha, self.beta)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
You write custom CUDA kernels to replace PyTorch operators for speedups.
|
||||
Implement Spatial-Diff Sigmoid Gate on NCHW tensors: For each element x[n,c,h,w], compute d = x[n,c,h,w] - x[n,c,h,w-1] (use 0 for w=0), gate g = sigmoid(alpha*d + beta), and output y = x * g. Use a single grid-stride kernel over all elements that reads the left neighbor efficiently and applies gating in-place to the output. Provide a PyTorch reference using nn.Parameter alpha and beta. Accuracy within rtol=1e-3.
|
||||
|
|
@ -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 = 50
|
||||
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 Spatial-Diff-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()
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, alpha: float, beta: float):
|
||||
super(Model, self).__init__()
|
||||
self.alpha = nn.Parameter(torch.tensor(float(alpha), dtype=torch.float32))
|
||||
self.beta = nn.Parameter(torch.tensor(float(beta), dtype=torch.float32))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
d = torch.zeros_like(x)
|
||||
d[..., :, 1:] = x[..., :, 1:] - x[..., :, :-1]
|
||||
g = torch.sigmoid(self.alpha * d + self.beta)
|
||||
return x * g
|
||||
|
||||
N, C, H, W = 8, 64, 64, 64
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, H, W)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return [1.0, 0.0]
|
||||
Loading…
Reference in New Issue