finish ModeSeekingLoss #99

This commit is contained in:
uucoco 2025-12-10 19:25:44 +08:00
parent 10eed82956
commit 1dcc7921bc
4 changed files with 277 additions and 0 deletions

View File

@ -0,0 +1,115 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, eps=1e-5):
super().__init__()
self.eps = eps
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor modeseekingloss_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor z1, torch::Tensor z2, float eps);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void reduce_l1_diff_kernel(
const float* __restrict__ a,
const float* __restrict__ b,
float* __restrict__ out,
const int dim)
{
extern __shared__ float sdata[];
int tid = threadIdx.x;
int bid = blockIdx.x;
float sum = 0.0f;
for (int i = tid; i < dim; i += blockDim.x) {
float diff = a[bid * dim + i] - b[bid * dim + i];
sum += fabsf(diff);
}
sdata[tid] = sum;
__syncthreads();
for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid == 0) {
out[bid] = sdata[0] / (float)dim;
}
}
__global__ void compute_ratio_kernel(
const float* __restrict__ img_diff,
const float* __restrict__ z_diff,
float* __restrict__ output,
const int n,
const float eps)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
output[i] = z_diff[i] / (img_diff[i] + eps);
}
}
torch::Tensor modeseekingloss_cuda(torch::Tensor img1, torch::Tensor img2, torch::Tensor z1, torch::Tensor z2, float eps) {
int batch_size = img1.size(0);
int img_dim = img1.numel() / batch_size;
int z_dim = z1.numel() / batch_size;
auto img_diff = torch::empty({batch_size}, img1.options());
auto z_diff = torch::empty({batch_size}, z1.options());
auto output = torch::empty({batch_size}, img1.options());
int threads = 256;
int blocks = batch_size;
int shared_mem = threads * sizeof(float);
reduce_l1_diff_kernel<<<blocks, threads, shared_mem>>>(
img1.data_ptr<float>(),
img2.data_ptr<float>(),
img_diff.data_ptr<float>(),
img_dim
);
reduce_l1_diff_kernel<<<blocks, threads, shared_mem>>>(
z1.data_ptr<float>(),
z2.data_ptr<float>(),
z_diff.data_ptr<float>(),
z_dim
);
int ratio_blocks = (batch_size + threads - 1) / threads;
compute_ratio_kernel<<<ratio_blocks, threads>>>(
img_diff.data_ptr<float>(),
z_diff.data_ptr<float>(),
output.data_ptr<float>(),
batch_size,
eps
);
return output.mean();
}
"""
self.op = load_inline(
name="modeseekingloss_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["modeseekingloss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, img1, img2, z1, z2):
return self.op.modeseekingloss_cuda(img1, img2, z1, z2, self.eps)

View File

@ -0,0 +1,32 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, eps=1e-5):
super().__init__()
self.eps = eps
def forward(self, img1: torch.Tensor, img2: torch.Tensor, z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:
img_diff = torch.abs(img1 - img2).view(img1.size(0), -1).mean(dim=1)
z_diff = torch.abs(z1 - z2).view(z1.size(0), -1).mean(dim=1)
loss = z_diff / (img_diff + self.eps)
return loss.mean()
batch_size = 32
c, h, w = 3, 64, 64
z_dim = 128
def get_inputs():
img1 = torch.randn(batch_size, c, h, w, dtype=torch.float32)
img2 = torch.randn(batch_size, c, h, w, dtype=torch.float32)
z1 = torch.randn(batch_size, z_dim, dtype=torch.float32)
z2 = torch.randn(batch_size, z_dim, dtype=torch.float32)
return [img1, img2, z1, z2]
def get_init_inputs():
return [1e-5]

53
S1/uucoco_#99/prompt.txt Normal file
View File

@ -0,0 +1,53 @@
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.
TwoStage Custom CUDA Kernel:
Parallel L1 Difference Reduction: Computes perbatch L1 distance between two tensors (img1/img2 and z1/z2) using sharedmemory reduction.
Ratio Computation Kernel: Calculates z_diff / (img_diff + eps) elementwise.
SharedMemory Parallel Reduction: Uses blocklevel reduction with __shared__ memory and a treebased sum pattern.
BatchLevel Parallelism: Each batch processed by a separate CUDA block in the reduction step.
Automatic Mean Reduction: Returns the mean of the perbatch ratio values directly from the CUDA wrapper.
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, eps=1e-5):
super().__init__()
self.eps = eps
def forward(self, img1: torch.Tensor, img2: torch.Tensor, z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:
img_diff = torch.abs(img1 - img2).view(img1.size(0), -1).mean(dim=1)
z_diff = torch.abs(z1 - z2).view(z1.size(0), -1).mean(dim=1)
loss = z_diff / (img_diff + self.eps)
return loss.mean()
batch_size = 32
c, h, w = 3, 64, 64
z_dim = 128
def get_inputs():
img1 = torch.randn(batch_size, c, h, w, dtype=torch.float32)
img2 = torch.randn(batch_size, c, h, w, dtype=torch.float32)
z1 = torch.randn(batch_size, z_dim, dtype=torch.float32)
z2 = torch.randn(batch_size, z_dim, dtype=torch.float32)
return [img1, img2, z1, z2]
def get_init_inputs():
return [1e-5]

77
S1/uucoco_#99/run_code.py Normal file
View File

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