finish PerceptualLoss #101

This commit is contained in:
uucoco 2025-12-10 19:27:56 +08:00
parent 10eed82956
commit e1a0d3acc6
4 changed files with 279 additions and 0 deletions

View File

@ -0,0 +1,107 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.reduction = reduction
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor mse_loss_cuda(torch::Tensor input, torch::Tensor target);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void mse_loss_kernel_vectorized(
const float* __restrict__ input,
const float* __restrict__ target,
float* __restrict__ output,
const int64_t n)
{
const int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;
const int64_t stride = blockDim.x * gridDim.x;
const int64_t n_vec = n / 4;
const float4* in_vec = reinterpret_cast<const float4*>(input);
const float4* tgt_vec = reinterpret_cast<const float4*>(target);
float4* out_vec = reinterpret_cast<float4*>(output);
for (int64_t i = idx; i < n_vec; i += stride) {
float4 a = in_vec[i];
float4 b = tgt_vec[i];
float4 res;
float d;
d = __fsub_rn(a.x, b.x); res.x = __fmul_rn(d, d);
d = __fsub_rn(a.y, b.y); res.y = __fmul_rn(d, d);
d = __fsub_rn(a.z, b.z); res.z = __fmul_rn(d, d);
d = __fsub_rn(a.w, b.w); res.w = __fmul_rn(d, d);
out_vec[i] = res;
}
const int64_t tail_offset = n_vec * 4;
for (int64_t i = tail_offset + idx; i < n; i += stride) {
float diff = __fsub_rn(input[i], target[i]);
output[i] = __fmul_rn(diff, diff);
}
}
torch::Tensor mse_loss_cuda(torch::Tensor input, torch::Tensor target) {
TORCH_CHECK(input.is_cuda(), "Input tensor must be on CUDA");
TORCH_CHECK(target.is_cuda(), "Target tensor must be on CUDA");
TORCH_CHECK(input.numel() == target.numel(), "Input and target must have the same number of elements");
auto input_c = input.contiguous();
auto target_c = target.contiguous();
const int64_t n = input_c.numel();
auto output = torch::empty_like(input_c);
const int threads = 256;
const int blocks = min((int64_t)((n + threads * 4 - 1) / (threads * 4)), (int64_t)65535);
mse_loss_kernel_vectorized<<<blocks, threads>>>(
input_c.data_ptr<float>(),
target_c.data_ptr<float>(),
output.data_ptr<float>(),
n
);
return output;
}
"""
self.op = load_inline(
name="perceptual_loss_opt_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["mse_loss_cuda"],
extra_cuda_cflags=["-O3", "-fmad=false"],
verbose=False
)
def forward(self, input_features: list[torch.Tensor], target_features: list[torch.Tensor]) -> torch.Tensor:
if len(input_features) > 0 and not input_features[0].is_cuda:
input_features = [f.cuda() for f in input_features]
target_features = [f.cuda() for f in target_features]
loss_val = 0.0
for i in range(len(input_features)):
squared_diff = self.op.mse_loss_cuda(input_features[i], target_features[i])
if self.reduction == 'mean':
loss_val += squared_diff.mean()
elif self.reduction == 'sum':
loss_val += squared_diff.sum()
else:
loss_val += squared_diff.mean()
return loss_val

View File

@ -0,0 +1,32 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.reduction = reduction
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, input_features: list[torch.Tensor], target_features: list[torch.Tensor]) -> torch.Tensor:
loss = 0.0
for i in range(len(input_features)):
loss += self.mse_loss(input_features[i], target_features[i])
return loss
batch_size = 256
feature_shapes = [(64, 64, 64), (128, 32, 32), (256, 16, 16)]
def get_inputs():
input_features = []
target_features = []
for c, h, w in feature_shapes:
input_features.append(torch.randn(batch_size, c, h, w, dtype=torch.float32))
target_features.append(torch.randn(batch_size, c, h, w, dtype=torch.float32))
return [input_features, target_features]
def get_init_inputs():
return ['mean']

63
S1/uucoco_#101/prompt.txt Normal file
View File

@ -0,0 +1,63 @@
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.
PyTorch C++/CUDA Extension: Inline compilation using torch.utils.cpp_extension.load_inline.
Vectorized CUDA Kernel: Uses float4 memory loads/stores for 4element SIMD-like processing to increase memory throughput.
Fused Multiply-Add (FMA) Control: Compilation flag -fmad=false disables automatic FMA to preserve numerical precision in subtractionsquared sequence.
TwoStage Processing:
Vectorized main loop processes aligned float4 chunks.
Scalar tail loop handles remaining elements not divisible by 4.
CUDA Intrinsics: Uses __fsub_rn and __fmul_rn for rounded singleprecision arithmetic.
BatchStyle Kernel Launch: Configures threads and blocks based on tensor size, capped at 65535 blocks.
PerFeatureMap MSE: Computes squared differences for each pair of feature maps in input_features and target_features.
Flexible Reduction: Supports 'mean' (default) and 'sum' reduction across feature maps, with automatic fallback to mean.
Automatic GPU Transfer: Moves tensors to CUDA if not already on GPU before kernel launch.
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
class Model(nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.reduction = reduction
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, input_features: list[torch.Tensor], target_features: list[torch.Tensor]) -> torch.Tensor:
loss = 0.0
for i in range(len(input_features)):
loss += self.mse_loss(input_features[i], target_features[i])
return loss
batch_size = 256
feature_shapes = [(64, 64, 64), (128, 32, 32), (256, 16, 16)]
def get_inputs():
input_features = []
target_features = []
for c, h, w in feature_shapes:
input_features.append(torch.randn(batch_size, c, h, w, dtype=torch.float32))
target_features.append(torch.randn(batch_size, c, h, w, dtype=torch.float32))
return [input_features, target_features]
def get_init_inputs():
return ['mean']

View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from PerceptualLoss_torch import Model, get_inputs, get_init_inputs
from PerceptualLoss_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()