From e5cfdc480fe57b8304fa3272ea793a6f5a5210cf Mon Sep 17 00:00:00 2001 From: Ljy123 Date: Wed, 3 Dec 2025 23:32:42 +0800 Subject: [PATCH] finish spatial-diff gate #38 --- S1/Ljy123_#38/cudacode.py | 64 ++++++++++++++++++++++++++++++++++++++ S1/Ljy123_#38/prompt.txt | 2 ++ S1/Ljy123_#38/run_code.py | 52 +++++++++++++++++++++++++++++++ S1/Ljy123_#38/torchcode.py | 23 ++++++++++++++ 4 files changed, 141 insertions(+) create mode 100644 S1/Ljy123_#38/cudacode.py create mode 100644 S1/Ljy123_#38/prompt.txt create mode 100644 S1/Ljy123_#38/run_code.py create mode 100644 S1/Ljy123_#38/torchcode.py diff --git a/S1/Ljy123_#38/cudacode.py b/S1/Ljy123_#38/cudacode.py new file mode 100644 index 00000000..7e44ca1b --- /dev/null +++ b/S1/Ljy123_#38/cudacode.py @@ -0,0 +1,64 @@ +import torch +from torch.utils.cpp_extension import load_inline + +source = """ +#include + +__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 b = beta.item(); + 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<<>>(xc.data_ptr(), y.data_ptr(), 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) diff --git a/S1/Ljy123_#38/prompt.txt b/S1/Ljy123_#38/prompt.txt new file mode 100644 index 00000000..b9b9b9ee --- /dev/null +++ b/S1/Ljy123_#38/prompt.txt @@ -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. diff --git a/S1/Ljy123_#38/run_code.py b/S1/Ljy123_#38/run_code.py new file mode 100644 index 00000000..7c2e3751 --- /dev/null +++ b/S1/Ljy123_#38/run_code.py @@ -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() diff --git a/S1/Ljy123_#38/torchcode.py b/S1/Ljy123_#38/torchcode.py new file mode 100644 index 00000000..a00545a9 --- /dev/null +++ b/S1/Ljy123_#38/torchcode.py @@ -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]