From c76c5740a274825c3747525d39f2f8ca78bdb702 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 9 Dec 2025 17:46:00 +0800 Subject: [PATCH] fixes Roll1d #51 --- S1/ZZZJ_#51/prompt.txt | 32 +++++++++++ S1/ZZZJ_#51/roll1d_cuda.py | 102 ++++++++++++++++++++++++++++++++++++ S1/ZZZJ_#51/roll1d_torch.py | 24 +++++++++ S1/ZZZJ_#51/run_code.py | 74 ++++++++++++++++++++++++++ 4 files changed, 232 insertions(+) create mode 100644 S1/ZZZJ_#51/prompt.txt create mode 100644 S1/ZZZJ_#51/roll1d_cuda.py create mode 100644 S1/ZZZJ_#51/roll1d_torch.py create mode 100644 S1/ZZZJ_#51/run_code.py diff --git a/S1/ZZZJ_#51/prompt.txt b/S1/ZZZJ_#51/prompt.txt new file mode 100644 index 00000000..d6e636e8 --- /dev/null +++ b/S1/ZZZJ_#51/prompt.txt @@ -0,0 +1,32 @@ +You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination. + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: + +python +import torch +import torch.nn as nn + + +BATCH = 128 +CHANNELS = 1024 +LENGTH = 4096 +SHIFT = 3 + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.shift = SHIFT + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + return torch.roll(x, shifts=self.shift, dims=-1) + +def get_inputs(): + x = torch.randint(low=-100, high=100, size=(BATCH, CHANNELS, LENGTH), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#51/roll1d_cuda.py b/S1/ZZZJ_#51/roll1d_cuda.py new file mode 100644 index 00000000..b7e7765d --- /dev/null +++ b/S1/ZZZJ_#51/roll1d_cuda.py @@ -0,0 +1,102 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self.shift = 3 + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor roll1d_cuda(torch::Tensor input, int shift); + """ + + cuda_source = """ + #include + + #define BLOCK_SIZE 256 + + __global__ void roll1d_f4_kernel( + const float* __restrict__ input, + float* __restrict__ output, + int n_vec, // float4 总数 + int batch_channels, // B * C + int length, + int shift + ) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx >= n_vec) return; + + int len_vec = length / 4; + + int l_vec = idx % len_vec; + int bc = idx / len_vec; // Batch * Channel index + + int l_start = l_vec * 4; + + long long row_offset = (long long)bc * length; + + + int s = shift % length; + if (s < 0) s += length; + + int i0 = (l_start + 0 - s + length) % length; + int i1 = (l_start + 1 - s + length) % length; + int i2 = (l_start + 2 - s + length) % length; + int i3 = (l_start + 3 - s + length) % length; + + float v0 = input[row_offset + i0]; + float v1 = input[row_offset + i1]; + float v2 = input[row_offset + i2]; + float v3 = input[row_offset + i3]; + + + long long out_offset = row_offset + l_start; + + output[out_offset + 0] = v0; + output[out_offset + 1] = v1; + output[out_offset + 2] = v2; + output[out_offset + 3] = v3; + } + + torch::Tensor roll1d_cuda(torch::Tensor input, int shift) { + + int length = input.size(-1); + int total_elements = input.numel(); + int batch_channels = total_elements / length; + + auto output = torch::empty_like(input); + + if (length % 4 != 0) return output; + + int n_vec = total_elements / 4; + + const int block_size = 256; + const int grid_size = (n_vec + block_size - 1) / block_size; + + roll1d_f4_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + n_vec, + batch_channels, length, shift + ); + + return output; + } + """ + + self.op = load_inline( + name="roll1d_f4_opt", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["roll1d_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not x.is_contiguous(): x = x.contiguous() + return self.op.roll1d_cuda(x, self.shift) \ No newline at end of file diff --git a/S1/ZZZJ_#51/roll1d_torch.py b/S1/ZZZJ_#51/roll1d_torch.py new file mode 100644 index 00000000..5f3ed78f --- /dev/null +++ b/S1/ZZZJ_#51/roll1d_torch.py @@ -0,0 +1,24 @@ +import torch +import torch.nn as nn + + +BATCH = 128 +CHANNELS = 1024 +LENGTH = 4096 +SHIFT = 3 + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.shift = SHIFT + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + return torch.roll(x, shifts=self.shift, dims=-1) + +def get_inputs(): + x = torch.randint(low=-100, high=100, size=(BATCH, CHANNELS, LENGTH), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#51/run_code.py b/S1/ZZZJ_#51/run_code.py new file mode 100644 index 00000000..efeea0f5 --- /dev/null +++ b/S1/ZZZJ_#51/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from roll1d_torch import Model,get_inputs,get_init_inputs +from roll1d_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() \ No newline at end of file