From 86d3e17e562d0ee3eea7f161488ddb4e9ef5d879 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 9 Dec 2025 19:42:01 +0800 Subject: [PATCH] fixes TotalVariationLoss #78 --- S1/ZZZJ_#78/prompt.txt | 38 ++++++++++ S1/ZZZJ_#78/run_code.py | 74 ++++++++++++++++++++ S1/ZZZJ_#78/total_variation_loss_cuda.py | 85 +++++++++++++++++++++++ S1/ZZZJ_#78/total_variation_loss_torch.py | 30 ++++++++ 4 files changed, 227 insertions(+) create mode 100644 S1/ZZZJ_#78/prompt.txt create mode 100644 S1/ZZZJ_#78/run_code.py create mode 100644 S1/ZZZJ_#78/total_variation_loss_cuda.py create mode 100644 S1/ZZZJ_#78/total_variation_loss_torch.py diff --git a/S1/ZZZJ_#78/prompt.txt b/S1/ZZZJ_#78/prompt.txt new file mode 100644 index 00000000..32d64361 --- /dev/null +++ b/S1/ZZZJ_#78/prompt.txt @@ -0,0 +1,38 @@ +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 = 64 +CHANNELS = 64 +HEIGHT = 512 +WIDTH = 512 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + out = torch.zeros_like(x) + + out[..., :, :-1] += torch.abs(x[..., :, 1:] - x[..., :, :-1]) + + out[..., :-1, :] += torch.abs(x[..., 1:, :] - x[..., :-1, :]) + + return out + +def get_inputs(): + + x = torch.randint(low=-100, high=100, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#78/run_code.py b/S1/ZZZJ_#78/run_code.py new file mode 100644 index 00000000..ba60e573 --- /dev/null +++ b/S1/ZZZJ_#78/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from total_variation_loss_torch import Model,get_inputs,get_init_inputs +from total_variation_loss_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 diff --git a/S1/ZZZJ_#78/total_variation_loss_cuda.py b/S1/ZZZJ_#78/total_variation_loss_cuda.py new file mode 100644 index 00000000..f4ab3a70 --- /dev/null +++ b/S1/ZZZJ_#78/total_variation_loss_cuda.py @@ -0,0 +1,85 @@ +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 tv_loss_cuda(torch::Tensor input); + """ + + cuda_source = """ + #include + #include + + #define BLOCK_SIZE 256 + + // TV Loss Kernel (Per-pixel) + __global__ void tv_loss_kernel( + const float* __restrict__ input, + float* __restrict__ output, + int n_elements, + int height, + int width + ) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx >= n_elements) return; + + + int w = idx % width; + int tmp = idx / width; + int h = tmp % height; + + float val = input[idx]; + float res = 0.0f; + + if (w < width - 1) { + float right = input[idx + 1]; + res += fabsf(right - val); + } + + if (h < height - 1) { + float bottom = input[idx + width]; + res += fabsf(bottom - val); + } + + output[idx] = res; + } + + torch::Tensor tv_loss_cuda(torch::Tensor input) { + auto output = torch::empty_like(input); + + long long n_elements = input.numel(); + int height = input.size(2); + int width = input.size(3); + + const int grid_size = (n_elements + BLOCK_SIZE - 1) / BLOCK_SIZE; + + tv_loss_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + n_elements, + height, width + ); + + return output; + } + """ + + self.op = load_inline( + name="tv_loss_kernel_v2_fixed", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["tv_loss_cuda"], + extra_cuda_cflags=["-O3", "--use_fast_math"], + verbose=False + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not x.is_contiguous(): x = x.contiguous() + return self.op.tv_loss_cuda(x) \ No newline at end of file diff --git a/S1/ZZZJ_#78/total_variation_loss_torch.py b/S1/ZZZJ_#78/total_variation_loss_torch.py new file mode 100644 index 00000000..9d4eb05a --- /dev/null +++ b/S1/ZZZJ_#78/total_variation_loss_torch.py @@ -0,0 +1,30 @@ +import torch +import torch.nn as nn + + +BATCH = 64 +CHANNELS = 64 +HEIGHT = 512 +WIDTH = 512 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + out = torch.zeros_like(x) + + out[..., :, :-1] += torch.abs(x[..., :, 1:] - x[..., :, :-1]) + + out[..., :-1, :] += torch.abs(x[..., 1:, :] - x[..., :-1, :]) + + return out + +def get_inputs(): + + x = torch.randint(low=-100, high=100, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float() + return [x] + +def get_init_inputs(): + return [] \ No newline at end of file