diff --git a/S1/ZZZJ_#170/polar_cuda.py b/S1/ZZZJ_#170/polar_cuda.py new file mode 100644 index 00000000..22072767 --- /dev/null +++ b/S1/ZZZJ_#170/polar_cuda.py @@ -0,0 +1,147 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_src = """ +torch::Tensor polar_cuda(torch::Tensor abs, torch::Tensor angle); +""" + +cuda_src = """ +#include +#include +#include + +__device__ __forceinline__ float2 polar_op(float r, float theta) { + float c, s; + __sincosf(theta, &s, &c); + return make_float2(r * c, r * s); +} + +__global__ void __launch_bounds__(256) polar_kernel_fast( + const float4* __restrict__ abs_ptr, + const float4* __restrict__ angle_ptr, + float2* __restrict__ out_ptr, + int num_vectors +) { + int tid = threadIdx.x; + int bid = blockIdx.x; + + int block_stride = 256 * 4; + int base_idx = bid * block_stride + tid; + + const float4* a_p = abs_ptr + base_idx; + const float4* ang_p = angle_ptr + base_idx; + + // Output is complex64 (float2), so pointer arithmetic is different + // We process 4 elements (4 float2s) per thread iteration + float2* o_p = out_ptr + base_idx * 4; + + float4 abs_r[4], ang_r[4]; + float2 res[4][4]; // 4 iterations, 4 elements each + bool mask[4]; + + #pragma unroll + for (int k = 0; k < 4; ++k) { + int global_vec_idx = base_idx + k * 256; + mask[k] = (global_vec_idx < num_vectors); + if (mask[k]) { + abs_r[k] = a_p[k * 256]; + ang_r[k] = ang_p[k * 256]; + } + } + + #pragma unroll + for (int k = 0; k < 4; ++k) { + if (mask[k]) { + res[k][0] = polar_op(abs_r[k].x, ang_r[k].x); + res[k][1] = polar_op(abs_r[k].y, ang_r[k].y); + res[k][2] = polar_op(abs_r[k].z, ang_r[k].z); + res[k][3] = polar_op(abs_r[k].w, ang_r[k].w); + } + } + + #pragma unroll + for (int k = 0; k < 4; ++k) { + if (mask[k]) { + // Write 4 float2s + // Reinterpreting float2* as float4* to perform 128-bit stores + // 4 complex numbers = 8 floats = 2 float4s + float4* out_cast = reinterpret_cast(o_p + k * 256 * 4); + + float4 out1, out2; + out1.x = res[k][0].x; out1.y = res[k][0].y; + out1.z = res[k][1].x; out1.w = res[k][1].y; + + out2.x = res[k][2].x; out2.y = res[k][2].y; + out2.z = res[k][3].x; out2.w = res[k][3].y; + + out_cast[0] = out1; + out_cast[1] = out2; + } + } +} + +torch::Tensor polar_cuda(torch::Tensor abs, torch::Tensor angle) { + int num_elements = abs.numel(); + + abs = abs.contiguous(); + angle = angle.contiguous(); + + // Output is complex64 + auto output = torch::empty_like(abs, abs.options().dtype(torch::kComplexFloat)); + + bool aligned = (num_elements % 4 == 0) && + ((long long)abs.data_ptr() % 16 == 0) && + ((long long)angle.data_ptr() % 16 == 0) && + ((long long)output.data_ptr() % 16 == 0); + + if (aligned) { + int num_vectors = num_elements / 4; + const int block_size = 256; + int elems_per_block = block_size * 4; + int grid_size = (num_vectors + elems_per_block - 1) / elems_per_block; + + if (grid_size > 2147483647) grid_size = 2147483647; + + polar_kernel_fast<<>>( + (const float4*)abs.data_ptr(), + (const float4*)angle.data_ptr(), + (float2*)output.data_ptr>(), + num_vectors + ); + } else { + return torch::polar(abs, angle); + } + + return output; +} +""" + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self.module = load_inline( + name="polar_opt_v1", + cpp_sources=cpp_src, + cuda_sources=cuda_src, + functions=["polar_cuda"], + verbose=False, + extra_cuda_cflags=["-O3", "--use_fast_math"] + ) + + def forward(self, abs, angle): + return self.module.polar_cuda(abs, angle) + +N = 1024 +C = 1024 +H = 64 +W = 64 +shape = (N, C) + +def get_inputs(): + abs_t = torch.randn(shape, dtype=torch.float32).abs() + angle_t = torch.randn(shape, dtype=torch.float32) + return [abs_t, angle_t] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#170/polar_torch.py b/S1/ZZZJ_#170/polar_torch.py new file mode 100644 index 00000000..61b33083 --- /dev/null +++ b/S1/ZZZJ_#170/polar_torch.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, abs_t: torch.Tensor, angle_t: torch.Tensor) -> torch.Tensor: + + return torch.polar(abs_t, angle_t) + +N = 1024 +C = 1024 +shape = (N, C) + +def get_inputs(): + abs_t = torch.randn(shape, dtype=torch.float32).abs() + angle_t = torch.randn(shape, dtype=torch.float32) + return [abs_t, angle_t] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#170/prompt.txt b/S1/ZZZJ_#170/prompt.txt new file mode 100644 index 00000000..6b5eba5d --- /dev/null +++ b/S1/ZZZJ_#170/prompt.txt @@ -0,0 +1,29 @@ +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 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, abs_t: torch.Tensor, angle_t: torch.Tensor) -> torch.Tensor: + + return torch.polar(abs_t, angle_t) + +N = 1024 +C = 1024 +shape = (N, C) + +def get_inputs(): + abs_t = torch.randn(shape, dtype=torch.float32).abs() + angle_t = torch.randn(shape, dtype=torch.float32) + return [abs_t, angle_t] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#170/run_code.py b/S1/ZZZJ_#170/run_code.py new file mode 100644 index 00000000..a59582f7 --- /dev/null +++ b/S1/ZZZJ_#170/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from polar_torch import Model,get_inputs,get_init_inputs +from polar_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