From 1f9e78b6db0e62f17cd78165cd3c82ec596fb8d8 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 9 Dec 2025 20:21:42 +0800 Subject: [PATCH] fixes PerspectiveTransform #97 --- S1/ZZZJ_#97/perspective_transform_cuda.py | 146 +++++++++++++++++++++ S1/ZZZJ_#97/perspective_transform_torch.py | 52 ++++++++ S1/ZZZJ_#97/prompt.txt | 60 +++++++++ S1/ZZZJ_#97/run_code.py | 74 +++++++++++ 4 files changed, 332 insertions(+) create mode 100644 S1/ZZZJ_#97/perspective_transform_cuda.py create mode 100644 S1/ZZZJ_#97/perspective_transform_torch.py create mode 100644 S1/ZZZJ_#97/prompt.txt create mode 100644 S1/ZZZJ_#97/run_code.py diff --git a/S1/ZZZJ_#97/perspective_transform_cuda.py b/S1/ZZZJ_#97/perspective_transform_cuda.py new file mode 100644 index 00000000..67a8720b --- /dev/null +++ b/S1/ZZZJ_#97/perspective_transform_cuda.py @@ -0,0 +1,146 @@ +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._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor perspective_cuda(torch::Tensor input, torch::Tensor matrix); + """ + + cuda_source = """ + #include + + #define BLOCK_W 32 + #define BLOCK_H 8 + __device__ __forceinline__ float get_pixel( + const float* __restrict__ data, + int h, int w, + int H, int W, + long long offset + ) { + if (h >= 0 && h < H && w >= 0 && w < W) { + return data[offset + h * W + w]; + } + return 0.0f; + } + + __global__ void perspective_safe_kernel( + const float* __restrict__ input, + const float* __restrict__ matrix, + float* __restrict__ output, + int batch, + int channels, + int height, + int width, + int n_vec_c // Channels / 4 + ) { + int ow = blockIdx.x * blockDim.x + threadIdx.x; + int oh = blockIdx.y * blockDim.y + threadIdx.y; + int b = blockIdx.z; + + if (ow >= width || oh >= height || b >= batch) return; + + const float* m_ptr = matrix + b * 9; + double m00 = m_ptr[0], m01 = m_ptr[1], m02 = m_ptr[2]; + double m10 = m_ptr[3], m11 = m_ptr[4], m12 = m_ptr[5]; + double m20 = m_ptr[6], m21 = m_ptr[7], m22 = m_ptr[8]; + + double y_dst = 2.0 * oh / (height - 1.0) - 1.0; + double x_dst = 2.0 * ow / (width - 1.0) - 1.0; + + double x_src_raw = m00 * x_dst + m01 * y_dst + m02; + double y_src_raw = m10 * x_dst + m11 * y_dst + m12; + double z_src_raw = m20 * x_dst + m21 * y_dst + m22; + + if (abs(z_src_raw) < 1e-6) z_src_raw = (z_src_raw > 0 ? 1e-6 : -1e-6); + double inv_z = 1.0 / z_src_raw; + + double x_src_norm = x_src_raw * inv_z; + double y_src_norm = y_src_raw * inv_z; + + double u = (x_src_norm + 1.0) * (width - 1.0) * 0.5; + double v = (y_src_norm + 1.0) * (height - 1.0) * 0.5; + + + int u_w = floor(u + 0.5); + int v_n = floor(v + 0.5); + int u_e = u_w + 1; + int v_s = v_n + 1; + + double dw = u - u_w; + double dn = v - v_n; + double w_nw = (1.0 - dw) * (1.0 - dn); + double w_ne = dw * (1.0 - dn); + double w_sw = (1.0 - dw) * dn; + double w_se = dw * dn; + + long long batch_offset = (long long)b * (channels * height * width); + long long spatial_offset = oh * width + ow; + long long stride_c = height * width; + + for (int k = 0; k < n_vec_c; ++k) { + // Unroll 4 channels manually + #pragma unroll + for (int i = 0; i < 4; ++i) { + int c = k * 4 + i; + long long c_offset = batch_offset + c * stride_c; + + float v_nw = get_pixel(input, v_n, u_w, height, width, c_offset); + float v_ne = get_pixel(input, v_n, u_e, height, width, c_offset); + float v_sw = get_pixel(input, v_s, u_w, height, width, c_offset); + float v_se = get_pixel(input, v_s, u_e, height, width, c_offset); + + float val = (float)(v_nw * w_nw + v_ne * w_ne + v_sw * w_sw + v_se * w_se); + + output[c_offset + spatial_offset] = val; + } + } + } + + torch::Tensor perspective_cuda(torch::Tensor input, torch::Tensor matrix) { + int batch = input.size(0); + int channels = input.size(1); + int height = input.size(2); + int width = input.size(3); + + auto output = torch::empty_like(input); + + if (channels % 4 != 0) return output; + int n_vec_c = channels / 4; + + dim3 block(BLOCK_W, BLOCK_H); + dim3 grid( + (width + BLOCK_W - 1) / BLOCK_W, + (height + BLOCK_H - 1) / BLOCK_H, + batch + ); + + perspective_safe_kernel<<>>( + input.data_ptr(), + matrix.data_ptr(), + output.data_ptr(), + batch, channels, height, width, n_vec_c + ); + + return output; + } + """ + + self.op = load_inline( + name="perspective_safe_v2", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["perspective_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x: torch.Tensor, matrix: torch.Tensor) -> torch.Tensor: + if not x.is_contiguous(): x = x.contiguous() + return self.op.perspective_cuda(x, matrix) \ No newline at end of file diff --git a/S1/ZZZJ_#97/perspective_transform_torch.py b/S1/ZZZJ_#97/perspective_transform_torch.py new file mode 100644 index 00000000..f9817450 --- /dev/null +++ b/S1/ZZZJ_#97/perspective_transform_torch.py @@ -0,0 +1,52 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +BATCH = 16 +CHANNELS = 64 +HEIGHT = 512 +WIDTH = 512 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x: torch.Tensor, matrix: torch.Tensor) -> torch.Tensor: + + B, C, H, W = x.shape + + y_idx = torch.arange(H, device=x.device, dtype=torch.float64) + x_idx = torch.arange(W, device=x.device, dtype=torch.float64) + grid_y, grid_x = torch.meshgrid(y_idx, x_idx, indexing='ij') + + grid_y = 2.0 * grid_y / (H - 1.0) - 1.0 + grid_x = 2.0 * grid_x / (W - 1.0) - 1.0 + ones = torch.ones_like(grid_x) + + grid = torch.stack([grid_x, grid_y, ones], dim=-1).unsqueeze(0).expand(B, -1, -1, -1) + + matrix_dbl = matrix.to(torch.float64) + + grid = grid.reshape(B, -1, 3) + + new_grid = torch.bmm(grid, matrix_dbl.transpose(1, 2)) + + z = new_grid[..., 2:3] + z = torch.where(torch.abs(z) < 1e-6, torch.sign(z) * 1e-6, z) + new_grid = new_grid[..., 0:2] / z + + new_grid = new_grid.view(B, H, W, 2).to(torch.float32) + + return F.grid_sample(x, new_grid, align_corners=True, mode='bilinear', padding_mode='zeros') + +def get_inputs(): + h = torch.arange(HEIGHT, device='cuda', dtype=torch.float32).view(1, 1, HEIGHT, 1) + w = torch.arange(WIDTH, device='cuda', dtype=torch.float32).view(1, 1, 1, WIDTH) + x = (h + w).expand(BATCH, CHANNELS, HEIGHT, WIDTH).contiguous() + + matrix = torch.eye(3, device='cuda', dtype=torch.float32).unsqueeze(0).repeat(BATCH, 1, 1) + + return [x, matrix] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#97/prompt.txt b/S1/ZZZJ_#97/prompt.txt new file mode 100644 index 00000000..6b0ea0ad --- /dev/null +++ b/S1/ZZZJ_#97/prompt.txt @@ -0,0 +1,60 @@ +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 +import torch.nn.functional as F + +BATCH = 16 +CHANNELS = 64 +HEIGHT = 512 +WIDTH = 512 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x: torch.Tensor, matrix: torch.Tensor) -> torch.Tensor: + + B, C, H, W = x.shape + + y_idx = torch.arange(H, device=x.device, dtype=torch.float64) + x_idx = torch.arange(W, device=x.device, dtype=torch.float64) + grid_y, grid_x = torch.meshgrid(y_idx, x_idx, indexing='ij') + + grid_y = 2.0 * grid_y / (H - 1.0) - 1.0 + grid_x = 2.0 * grid_x / (W - 1.0) - 1.0 + ones = torch.ones_like(grid_x) + + grid = torch.stack([grid_x, grid_y, ones], dim=-1).unsqueeze(0).expand(B, -1, -1, -1) + + matrix_dbl = matrix.to(torch.float64) + + grid = grid.reshape(B, -1, 3) + + new_grid = torch.bmm(grid, matrix_dbl.transpose(1, 2)) + + z = new_grid[..., 2:3] + z = torch.where(torch.abs(z) < 1e-6, torch.sign(z) * 1e-6, z) + new_grid = new_grid[..., 0:2] / z + + new_grid = new_grid.view(B, H, W, 2).to(torch.float32) + + return F.grid_sample(x, new_grid, align_corners=True, mode='bilinear', padding_mode='zeros') + +def get_inputs(): + h = torch.arange(HEIGHT, device='cuda', dtype=torch.float32).view(1, 1, HEIGHT, 1) + w = torch.arange(WIDTH, device='cuda', dtype=torch.float32).view(1, 1, 1, WIDTH) + x = (h + w).expand(BATCH, CHANNELS, HEIGHT, WIDTH).contiguous() + + matrix = torch.eye(3, device='cuda', dtype=torch.float32).unsqueeze(0).repeat(BATCH, 1, 1) + + return [x, matrix] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#97/run_code.py b/S1/ZZZJ_#97/run_code.py new file mode 100644 index 00000000..f86ed6f4 --- /dev/null +++ b/S1/ZZZJ_#97/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from perspective_transform_torch import Model,get_inputs,get_init_inputs +from perspective_transform_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