diff --git a/S1/Ljy123_#78/cudacode.py b/S1/Ljy123_#78/cudacode.py new file mode 100644 index 0000000..090feba --- /dev/null +++ b/S1/Ljy123_#78/cudacode.py @@ -0,0 +1,110 @@ +import torch +from torch.utils.cpp_extension import load_inline + +source = """ +#include +#include +#include + +__device__ __forceinline__ float hs(float t){ + float s = (t + 3.0f) * (1.0f/6.0f); + s = fminf(fmaxf(s, 0.0f), 1.0f); + return s; +} + +__global__ __launch_bounds__(256) void hardsigmoid_affine_gate_kernel(const float* __restrict__ x, const float* __restrict__ scale, const float* __restrict__ bias, float* __restrict__ y, int B, int D, float alpha, float beta){ + int row = blockIdx.x; + int tid = threadIdx.x; + int col_block = blockIdx.y; + int stride4 = blockDim.x * 4; + int col_idx = (col_block * stride4) + tid * 4; + const float* xr = x + row * D; + float* yr = y + row * D; + for(int base = col_idx; base < D; base += stride4 * 2){ + if (base < D){ + float4 xv = reinterpret_cast(xr + base)[0]; + float4 sv = reinterpret_cast(scale + base)[0]; + float4 bv = reinterpret_cast(bias + base)[0]; + float4 yv; + float z0 = fmaf(xv.x, sv.x, bv.x); + float z1 = fmaf(xv.y, sv.y, bv.y); + float z2 = fmaf(xv.z, sv.z, bv.z); + float z3 = fmaf(xv.w, sv.w, bv.w); + float g0 = hs(fmaf(alpha, z0, beta)); + float g1 = hs(fmaf(alpha, z1, beta)); + float g2 = hs(fmaf(alpha, z2, beta)); + float g3 = hs(fmaf(alpha, z3, beta)); + yv.x = xv.x * g0; + yv.y = xv.y * g1; + yv.z = xv.z * g2; + yv.w = xv.w * g3; + reinterpret_cast(yr + base)[0] = yv; + } + int base2 = base + stride4; + if (base2 < D){ + float4 xv2 = reinterpret_cast(xr + base2)[0]; + float4 sv2 = reinterpret_cast(scale + base2)[0]; + float4 bv2 = reinterpret_cast(bias + base2)[0]; + float4 yv2; + float z0b = fmaf(xv2.x, sv2.x, bv2.x); + float z1b = fmaf(xv2.y, sv2.y, bv2.y); + float z2b = fmaf(xv2.z, sv2.z, bv2.z); + float z3b = fmaf(xv2.w, sv2.w, bv2.w); + float g0b = hs(fmaf(alpha, z0b, beta)); + float g1b = hs(fmaf(alpha, z1b, beta)); + float g2b = hs(fmaf(alpha, z2b, beta)); + float g3b = hs(fmaf(alpha, z3b, beta)); + yv2.x = xv2.x * g0b; + yv2.y = xv2.y * g1b; + yv2.z = xv2.z * g2b; + yv2.w = xv2.w * g3b; + reinterpret_cast(yr + base2)[0] = yv2; + } + } +} + +torch::Tensor hardsigmoid_affine_gate_cuda(torch::Tensor x, torch::Tensor scale, torch::Tensor bias, double alpha, double beta){ + 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); + float a = (float)alpha; + float be = (float)beta; + int block = 256; + int elements_per_thread = 4; + int elements_per_block = block * elements_per_thread; + int gy = (D + elements_per_block - 1) / elements_per_block; + dim3 grid(B, gy); + hardsigmoid_affine_gate_kernel<<>>(xc.data_ptr(), sc.data_ptr(), bc.data_ptr(), y.data_ptr(), B, D, a, be); + return y; +} +""" + +cpp_source = """ +#include +torch::Tensor hardsigmoid_affine_gate_cuda(torch::Tensor x, torch::Tensor scale, torch::Tensor bias, double alpha, double beta); +""" + +ops = load_inline( + name="hardsigmoid_affine_gate", + cpp_sources=cpp_source, + cuda_sources=source, + functions=["hardsigmoid_affine_gate_cuda"], + extra_cflags=["-O3","-std=c++17"], + extra_cuda_cflags=["-O3","--use_fast_math","-std=c++17","-Xptxas","-O3,-dlcm=ca","-maxrregcount=64"], + verbose=True +) + +class ModelNew(torch.nn.Module): + def __init__(self, scale: torch.Tensor, bias: torch.Tensor, alpha: float, beta: float): + super(ModelNew, self).__init__() + self.ops = ops + self.register_buffer("scale", scale) + self.register_buffer("bias", bias) + self.alpha = float(alpha) + self.beta = float(beta) + + def forward(self, x): + return self.ops.hardsigmoid_affine_gate_cuda(x, self.scale, self.bias, self.alpha, self.beta) diff --git a/S1/Ljy123_#78/prompt.txt b/S1/Ljy123_#78/prompt.txt new file mode 100644 index 0000000..3bae444 --- /dev/null +++ b/S1/Ljy123_#78/prompt.txt @@ -0,0 +1,37 @@ +Operator: HardSigmoid-Affine-Gate (Fused CUDA Kernel) + +Goal +- Implement a fused affine–HardSigmoid gate operator to reduce memory traffic and kernel launches, targeting ≥1.30x speedup. + +Inputs/Outputs +- Input `x`: [B, D], float32 (contiguous) +- Parameters `scale`, `bias`: [D], float32 (contiguous) +- Scalars `alpha`, `beta`: float32 +- Output `y`: [B, D], float32 + +Definition +- z = x * scale + bias +- g = hardsigmoid(alpha * z + beta) = clamp((alpha*z + beta) * (1/6) + 0.5, 0, 1) +- y = x * g + +CUDA Design +- 2D grid: grid.x = B; grid.y = ceil(D / (block * ILP * 4)) +- Block size: 128; ILP = 1 (1 x float4 per thread) +- Vectorized memory with float4; fast math intrinsics; FMA for affine +- Requires contiguous tensors; D multiple of 4 recommended + +Build +- PyTorch inline extension; flags: `-O3`, `--use_fast_math`, `-std=c++14` + +Validation +- Precision: `torch.allclose(rtol=1e-3)` vs PyTorch reference +- Performance: speedup ≥ 1.30x at B=16, D=16384, 100 iterations + +How to Run +- Execute `run_code.py` to check precision and speedup + + Extended Benchmark & Requirements +- Cover at least 3 shapes (e.g., D=4096/16384/65536) and dtypes (FP32, FP16, BF16 if available) +- Report per-case wall-clock time and speedup; use multiple iterations and synchronization +- Use `rtol=1e-3` for FP32, relax to `rtol=1e-2` for FP16/BF16 +- If speedup <1.3x for any case, print bottleneck analysis and next-step optimization plan diff --git a/S1/Ljy123_#78/run_code.py b/S1/Ljy123_#78/run_code.py new file mode 100644 index 0000000..ce029c5 --- /dev/null +++ b/S1/Ljy123_#78/run_code.py @@ -0,0 +1,50 @@ +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().eval() + cuda_model = ModelNew(*init_inputs).cuda().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 + 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 + + 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 HardSigmoid-Affine-Gate 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA 融合内核 平均执行时间: {cuda_time:.6f} 秒") + speedup = torch_time / cuda_time if cuda_time > 0 else 0 + if cuda_time > 0: + print(f"加速比 (Speedup): {speedup:.2f}x") + else: + print("CUDA 内核执行时间为0,无法计算加速比。") + return precision_flag, speedup + +if __name__ == "__main__": + run_benchmark() diff --git a/S1/Ljy123_#78/torchcode.py b/S1/Ljy123_#78/torchcode.py new file mode 100644 index 0000000..847effa --- /dev/null +++ b/S1/Ljy123_#78/torchcode.py @@ -0,0 +1,29 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +class Model(nn.Module): + def __init__(self, scale: torch.Tensor, bias: torch.Tensor, alpha: float, beta: float): + super(Model, self).__init__() + self.register_buffer("scale", scale) + self.register_buffer("bias", bias) + 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) -> torch.Tensor: + z = x * self.scale + self.bias + t = self.alpha * z + self.beta + g = F.hardsigmoid(t) + return x * g + +batch_size = 16 +dim = 16384 + +def get_inputs(): + x = torch.randn(batch_size, dim) + return [x] + +def get_init_inputs(): + scale = torch.randn(dim) + bias = torch.randn(dim) + return [scale, bias, 1.0, 0.0]