diff --git a/S1/gsd123_#130/SSIMLoss_cuda.py b/S1/gsd123_#130/SSIMLoss_cuda.py new file mode 100644 index 0000000..1625443 --- /dev/null +++ b/S1/gsd123_#130/SSIMLoss_cuda.py @@ -0,0 +1,128 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline +import math + +cuda_source = """ +#include +#include + +#define WINDOW_SIZE 11 +#define RADIUS 5 +#define C1 (0.01f * 0.01f) +#define C2 (0.03f * 0.03f) + +__global__ void fused_ssim_kernel( + const float* __restrict__ img1, + const float* __restrict__ img2, + const float* __restrict__ gaussian_kernel, + float* __restrict__ out_map, + int B, int C, int H, int W +) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + int total_pixels = B * C * H * W; + + if (idx >= total_pixels) return; + + int w_idx = idx % W; + int h_idx = (idx / W) % H; + int c_idx = (idx / (W * H)) % C; + int b_idx = idx / (W * H * C); + + int pixel_offset = b_idx * (C * H * W) + c_idx * (H * W); + + float mu1 = 0.0f; + float mu2 = 0.0f; + float sigma1_sq_sum = 0.0f; + float sigma2_sq_sum = 0.0f; + float sigma12_sum = 0.0f; + + for (int i = -RADIUS; i <= RADIUS; ++i) { + for (int j = -RADIUS; j <= RADIUS; ++j) { + int cur_h = h_idx + i; + int cur_w = w_idx + j; + + float val1 = 0.0f; + float val2 = 0.0f; + + if (cur_h >= 0 && cur_h < H && cur_w >= 0 && cur_w < W) { + int neighbor_idx = pixel_offset + cur_h * W + cur_w; + val1 = img1[neighbor_idx]; + val2 = img2[neighbor_idx]; + } + + float weight = gaussian_kernel[(i + RADIUS) * WINDOW_SIZE + (j + RADIUS)]; + + mu1 += weight * val1; + mu2 += weight * val2; + sigma1_sq_sum += weight * val1 * val1; + sigma2_sq_sum += weight * val2 * val2; + sigma12_sum += weight * val1 * val2; + } + } + + float mu1_sq = mu1 * mu1; + float mu2_sq = mu2 * mu2; + float mu1_mu2 = mu1 * mu2; + + float sigma1_sq = sigma1_sq_sum - mu1_sq; + float sigma2_sq = sigma2_sq_sum - mu2_sq; + float sigma12 = sigma12_sum - mu1_mu2; + + float num = (2.0f * mu1_mu2 + C1) * (2.0f * sigma12 + C2); + float den = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2); + + out_map[idx] = num / den; +} + +torch::Tensor ssim_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor kernel) { + int B = img1.size(0); + int C = img1.size(1); + int H = img1.size(2); + int W = img1.size(3); + + auto out_map = torch::empty_like(img1); + + int total_pixels = B * C * H * W; + int threads = 256; + int blocks = (total_pixels + threads - 1) / threads; + + fused_ssim_kernel<<>>( + img1.data_ptr(), + img2.data_ptr(), + kernel.data_ptr(), + out_map.data_ptr(), + B, C, H, W + ); + + return 1.0f - out_map.mean(); +} +""" + +cpp_source = """ +torch::Tensor ssim_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor kernel); +""" + +ssim_loss = load_inline( + name="ssim_loss", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["ssim_cuda"], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self, window_size=11, sigma=1.5): + super(ModelNew, self).__init__() + self.register_buffer("kernel", self._create_kernel(window_size, sigma)) + + def _create_kernel(self, window_size, sigma): + coords = torch.arange(window_size).float() - window_size // 2 + g = torch.exp(-(coords ** 2) / (2 * sigma ** 2)) + g = g / g.sum() + kernel = g.unsqueeze(1) @ g.unsqueeze(0) + return kernel.contiguous() + + def forward(self, img1, img2): + return ssim_loss.ssim_cuda(img1, img2, self.kernel) \ No newline at end of file diff --git a/S1/gsd123_#130/SSIMLoss_torch.py b/S1/gsd123_#130/SSIMLoss_torch.py new file mode 100644 index 0000000..f689d17 --- /dev/null +++ b/S1/gsd123_#130/SSIMLoss_torch.py @@ -0,0 +1,61 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + + +class Model(nn.Module): + def __init__(self, window_size=11, channel=3): + super(Model, self).__init__() + self.window_size = window_size + self.channel = channel + self.window = self.create_window(window_size, channel) + + def create_window(self, window_size, channel): + def _gaussian(window_size, sigma): + gauss = torch.Tensor( + [math.exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)]) + return gauss / gauss.sum() + + _1D_window = _gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() + return window + + def forward(self, img1, img2): + if self.window.device != img1.device: + self.window = self.window.to(img1.device) + self.window = self.window.type_as(img1) + + mu1 = F.conv2d(img1, self.window, padding=self.window_size // 2, groups=self.channel) + mu2 = F.conv2d(img2, self.window, padding=self.window_size // 2, groups=self.channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(img1 * img1, self.window, padding=self.window_size // 2, groups=self.channel) - mu1_sq + sigma2_sq = F.conv2d(img2 * img2, self.window, padding=self.window_size // 2, groups=self.channel) - mu2_sq + sigma12 = F.conv2d(img1 * img2, self.window, padding=self.window_size // 2, groups=self.channel) - mu1_mu2 + + C1 = 0.01 ** 2 + C2 = 0.03 ** 2 + + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) + return 1 - ssim_map.mean() + + +batch_size = 16 +channels = 3 +height = 256 +width = 256 + + +def get_inputs(): + img1 = torch.rand(batch_size, channels, height, width) + img2 = torch.rand(batch_size, channels, height, width) + return [img1, img2] + + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#130/prompt.txt b/S1/gsd123_#130/prompt.txt new file mode 100644 index 0000000..e024f66 --- /dev/null +++ b/S1/gsd123_#130/prompt.txt @@ -0,0 +1,90 @@ +You write custom CUDA kernels to replace the pytorch operators in the given GeGLU 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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. +Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline + +Structural Similarity Index (SSIM) loss computation + +Fused window-based SSIM calculation (11×11 Gaussian window) + +Local statistics computation: means, variances, covariance + +Gaussian kernel weighting for spatial weighting + +SSIM formula: (2μ₁μ₂ + C₁)(2σ₁₂ + C₂) / ((μ₁² + μ₂² + C₁)(σ₁² + σ₂² + C₂)) + +Boundary handling with conditional checks + +Element-wise parallelization across all pixels×channels×batches + +Fixed block size (256 threads) with dynamic grid sizing + +Mean reduction across all pixels (1 - SSIM mean) + +Precomputed Gaussian kernel as PyTorch buffer + + + + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + + +class Model(nn.Module): + def __init__(self, window_size=11, channel=3): + super(Model, self).__init__() + self.window_size = window_size + self.channel = channel + self.window = self.create_window(window_size, channel) + + def create_window(self, window_size, channel): + def _gaussian(window_size, sigma): + gauss = torch.Tensor( + [math.exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)]) + return gauss / gauss.sum() + + _1D_window = _gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() + return window + + def forward(self, img1, img2): + if self.window.device != img1.device: + self.window = self.window.to(img1.device) + self.window = self.window.type_as(img1) + + mu1 = F.conv2d(img1, self.window, padding=self.window_size // 2, groups=self.channel) + mu2 = F.conv2d(img2, self.window, padding=self.window_size // 2, groups=self.channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(img1 * img1, self.window, padding=self.window_size // 2, groups=self.channel) - mu1_sq + sigma2_sq = F.conv2d(img2 * img2, self.window, padding=self.window_size // 2, groups=self.channel) - mu2_sq + sigma12 = F.conv2d(img1 * img2, self.window, padding=self.window_size // 2, groups=self.channel) - mu1_mu2 + + C1 = 0.01 ** 2 + C2 = 0.03 ** 2 + + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) + return 1 - ssim_map.mean() + + +batch_size = 16 +channels = 3 +height = 256 +width = 256 + + +def get_inputs(): + img1 = torch.rand(batch_size, channels, height, width) + img2 = torch.rand(batch_size, channels, height, width) + return [img1, img2] + + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#130/run_code.py b/S1/gsd123_#130/run_code.py new file mode 100644 index 0000000..b6011a3 --- /dev/null +++ b/S1/gsd123_#130/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from SSIMLoss_torch import Model, get_inputs, get_init_inputs +from SSIMLoss_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