Compare commits

...

1 Commits

Author SHA1 Message Date
uucoco e73b0a0bca finish DiversityLoss #60 2025-12-10 18:40:11 +08:00
4 changed files with 269 additions and 0 deletions

View File

@ -0,0 +1,90 @@
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 = """
torch::Tensor diversity_loss_cuda(torch::Tensor S);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__global__ void vectorized_matrix_square_kernel(
const float* __restrict__ S_in,
float* __restrict__ S_out,
const int n_elements)
{
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int stride = blockDim.x * gridDim.x;
const int vec_loops = n_elements >> 2;
const float4* S_in_vec = reinterpret_cast<const float4*>(S_in);
float4* S_out_vec = reinterpret_cast<float4*>(S_out);
for (int i = tid; i < vec_loops; i += stride) {
float4 v = __ldg(&S_in_vec[i]);
float4 r;
r.x = v.x * v.x;
r.y = v.y * v.y;
r.z = v.z * v.z;
r.w = v.w * v.w;
S_out_vec[i] = r;
}
const int tail_start = vec_loops << 2;
for (int i = tail_start + tid; i < n_elements; i += stride) {
float v = S_in[i];
S_out[i] = v * v;
}
}
torch::Tensor diversity_loss_cuda(torch::Tensor S) {
auto S_c = S.contiguous();
const int n_elements = S_c.numel();
auto S_sq = torch::empty_like(S_c);
const int threads = 256;
const int max_blocks = 65535;
const int blocks = std::min((n_elements + 4 * threads - 1) / (4 * threads), max_blocks);
vectorized_matrix_square_kernel<<<blocks, threads>>>(
S_c.data_ptr<float>(),
S_sq.data_ptr<float>(),
n_elements
);
return S_sq;
}
"""
self.op = load_inline(
name="diversity_loss_v2",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["diversity_loss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, embeddings):
S = torch.matmul(embeddings, embeddings.transpose(0, 1))
N = embeddings.size(0)
S_sq = self.op.diversity_loss_cuda(S)
M_diag = torch.eye(N, dtype=torch.bool, device=embeddings.device)
S_off_diag_sq = S_sq.masked_select(~M_diag)
return S_off_diag_sq.mean()

View File

@ -0,0 +1,34 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, embeddings: torch.Tensor) -> torch.Tensor:
S = torch.matmul(embeddings, embeddings.transpose(0, 1))
N = embeddings.size(0)
S_sq = S.pow(2)
M_diag = torch.eye(N, dtype=torch.bool, device=embeddings.device)
S_off_diag_sq = S_sq.masked_select(~M_diag)
return S_off_diag_sq.mean()
batch_size = 128
feature_dim = 512
def get_inputs():
embeddings = torch.randn(batch_size, feature_dim, dtype=torch.float32)
embeddings = F.normalize(embeddings, p=2, dim=1)
return [embeddings]
def get_init_inputs():
return []

68
S1/uucoco_#60/prompt.txt Normal file
View File

@ -0,0 +1,68 @@
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.
This CUDA kernel implements a Diversity Loss function with a hybrid CPU-GPU approach:
CUDA Kernel Optimizations:
Vectorized Elementwise Square: Uses float4 loads/stores to square 4 elements per instruction, improving memory bandwidth utilization for the similarity matrix S.
Coalesced Memory Access: Threads access contiguous memory locations via vectorized operations, enabling efficient memory coalescing.
Simple Computation: Just performs v * v per element - very lightweight operation.
Overall Pipeline (Hybrid):
CPU: Compute similarity matrix S = embeddings @ embeddings.T (matrix multiplication)
GPU: Square each element of S (S_sq[i] = S[i] * S[i]) using vectorized CUDA kernel
CPU: Extract off-diagonal elements using mask (~torch.eye(N, dtype=bool))
CPU: Compute mean of off-diagonal squared similarities
Performance Considerations:
Bottleneck: Matrix multiplication embeddings @ embeddings.T is likely more expensive than the elementwise squaring
Memory Usage: Creates full N × N similarity matrix (O(N²) memory)
CPU-GPU Transfers: Similarity matrix stays on GPU for squaring, then off-diagonal extraction happens on CPU
Loss Computation:
L = mean(S[i,j]²) for all i ≠ j (encourages orthogonality/uncorrelation between different embeddings)
Potential Improvement:
Could compute squared off-diagonal sum directly in CUDA to avoid creating full S_sq matrix and CPU masking operations.
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
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, embeddings: torch.Tensor) -> torch.Tensor:
S = torch.matmul(embeddings, embeddings.transpose(0, 1))
N = embeddings.size(0)
S_sq = S.pow(2)
M_diag = torch.eye(N, dtype=torch.bool, device=embeddings.device)
S_off_diag_sq = S_sq.masked_select(~M_diag)
return S_off_diag_sq.mean()
batch_size = 128
feature_dim = 512
def get_inputs():
embeddings = torch.randn(batch_size, feature_dim, dtype=torch.float32)
embeddings = F.normalize(embeddings, p=2, dim=1)
return [embeddings]
def get_init_inputs():
return []

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

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