forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish HungarianLoss #126' (#1042) from uucoco/GPUCodeForces:uucoco126 into main
This commit is contained in:
commit
044863f5ed
|
|
@ -0,0 +1,181 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
cuda_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <math.h>
|
||||
|
||||
__global__ void compute_cost_matrix_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ target,
|
||||
float* __restrict__ M,
|
||||
int batch_size,
|
||||
int dim,
|
||||
float epsilon)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int total_elements = batch_size * batch_size;
|
||||
|
||||
if (idx < total_elements) {
|
||||
int row = idx / batch_size;
|
||||
int col = idx % batch_size;
|
||||
|
||||
float dist_sq = 0.0f;
|
||||
const float* x_row = x + row * dim;
|
||||
const float* t_row = target + col * dim;
|
||||
|
||||
for (int k = 0; k < dim; ++k) {
|
||||
float diff = x_row[k] - t_row[k];
|
||||
dist_sq += diff * diff;
|
||||
}
|
||||
|
||||
M[idx] = -dist_sq / epsilon;
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void sinkhorn_solver_kernel(
|
||||
const float* __restrict__ M,
|
||||
float* __restrict__ out_loss,
|
||||
int batch_size,
|
||||
float epsilon,
|
||||
int iters)
|
||||
{
|
||||
extern __shared__ float s_mem[];
|
||||
float* s_f = s_mem;
|
||||
float* s_g = s_f + batch_size;
|
||||
float* s_red = s_g + batch_size;
|
||||
|
||||
int tid = threadIdx.x;
|
||||
int b = batch_size;
|
||||
|
||||
if (tid < b) {
|
||||
s_f[tid] = 0.0f;
|
||||
s_g[tid] = 0.0f;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
for (int iter = 0; iter < iters; ++iter) {
|
||||
if (tid < b) {
|
||||
float max_val = -3.402823466e+38F;
|
||||
for (int j = 0; j < b; ++j) {
|
||||
float val = M[tid * b + j] + s_g[j];
|
||||
if (val > max_val) max_val = val;
|
||||
}
|
||||
|
||||
float sum_exp = 0.0f;
|
||||
for (int j = 0; j < b; ++j) {
|
||||
sum_exp += expf(M[tid * b + j] + s_g[j] - max_val);
|
||||
}
|
||||
s_f[tid] = -(logf(sum_exp) + max_val);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (tid < b) {
|
||||
float max_val = -3.402823466e+38F;
|
||||
for (int i = 0; i < b; ++i) {
|
||||
float val = M[i * b + tid] + s_f[i];
|
||||
if (val > max_val) max_val = val;
|
||||
}
|
||||
|
||||
float sum_exp = 0.0f;
|
||||
for (int i = 0; i < b; ++i) {
|
||||
sum_exp += expf(M[i * b + tid] + s_f[i] - max_val);
|
||||
}
|
||||
s_g[tid] = -(logf(sum_exp) + max_val);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
float row_sum = 0.0f;
|
||||
if (tid < b) {
|
||||
float fi = s_f[tid];
|
||||
for (int j = 0; j < b; ++j) {
|
||||
float Mij = M[tid * b + j];
|
||||
float gj = s_g[j];
|
||||
|
||||
float log_P = Mij + fi + gj;
|
||||
float P = expf(log_P);
|
||||
float C = -Mij * epsilon;
|
||||
|
||||
row_sum += P * C;
|
||||
}
|
||||
}
|
||||
|
||||
float val = row_sum;
|
||||
for (int offset = 16; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
|
||||
if ((tid % 32) == 0) {
|
||||
s_red[tid / 32] = val;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (tid == 0) {
|
||||
float total_loss = 0.0f;
|
||||
int warps = (blockDim.x + 31) / 32;
|
||||
for (int i = 0; i < warps; ++i) {
|
||||
total_loss += s_red[i];
|
||||
}
|
||||
out_loss[0] = total_loss / (float)b;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor launch_sinkhorn_loss(torch::Tensor x, torch::Tensor target) {
|
||||
auto batch_size = x.size(0);
|
||||
auto dim = x.size(1);
|
||||
auto M = torch::empty({batch_size, batch_size}, x.options());
|
||||
auto out = torch::empty({1}, x.options());
|
||||
|
||||
|
||||
int total_elements = batch_size * batch_size;
|
||||
int threads_m = 256;
|
||||
int blocks_m = (total_elements + threads_m - 1) / threads_m;
|
||||
|
||||
compute_cost_matrix_kernel<<<blocks_m, threads_m>>>(
|
||||
x.data_ptr<float>(),
|
||||
target.data_ptr<float>(),
|
||||
M.data_ptr<float>(),
|
||||
batch_size,
|
||||
dim,
|
||||
0.1f
|
||||
);
|
||||
|
||||
|
||||
int threads_s = batch_size;
|
||||
int blocks_s = 1;
|
||||
int shared_mem = (2 * batch_size + 32) * sizeof(float);
|
||||
|
||||
sinkhorn_solver_kernel<<<blocks_s, threads_s, shared_mem>>>(
|
||||
M.data_ptr<float>(),
|
||||
out.data_ptr<float>(),
|
||||
batch_size,
|
||||
0.1f,
|
||||
5
|
||||
);
|
||||
|
||||
return out;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor launch_sinkhorn_loss(torch::Tensor x, torch::Tensor target);
|
||||
"""
|
||||
|
||||
sinkhorn_loss_module = load_inline(
|
||||
name='hungarian_loss_fast',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['launch_sinkhorn_loss'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.op = sinkhorn_loss_module
|
||||
|
||||
def forward(self, x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
return self.op.launch_sinkhorn_loss(x.contiguous(), target.contiguous())
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.epsilon = 0.1
|
||||
self.num_iters = 5
|
||||
|
||||
def forward(self, x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
x_sq = torch.sum(x ** 2, dim=1, keepdim=True)
|
||||
t_sq = torch.sum(target ** 2, dim=1, keepdim=True)
|
||||
dist_sq = x_sq + t_sq.t() - 2 * torch.matmul(x, target.t())
|
||||
|
||||
C = dist_sq
|
||||
M = -C / self.epsilon
|
||||
|
||||
f = torch.zeros(x.size(0), 1, device=x.device)
|
||||
g = torch.zeros(1, x.size(0), device=x.device)
|
||||
|
||||
for _ in range(self.num_iters):
|
||||
f = -torch.logsumexp(M + g, dim=1, keepdim=True)
|
||||
g = -torch.logsumexp(M + f, dim=0, keepdim=True)
|
||||
|
||||
log_P = f + M + g
|
||||
P = torch.exp(log_P)
|
||||
|
||||
loss = torch.sum(P * C) / x.size(0)
|
||||
return loss
|
||||
|
||||
|
||||
batch_size = 128
|
||||
input_dim = 1024
|
||||
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, input_dim)
|
||||
target = torch.randn(batch_size, input_dim)
|
||||
return [x, target]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
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.
|
||||
|
||||
This code implements Sinkhorn (Hungarian/OT) loss with CUDA optimizations:
|
||||
|
||||
Two-stage kernel design - Separate kernels for cost matrix computation and Sinkhorn iteration.
|
||||
|
||||
Cost matrix parallelism - Each thread computes one element of the N×N pairwise distance matrix.
|
||||
|
||||
Shared memory Sinkhorn solver - Stores dual potentials (f, g) in shared memory for fast iterative updates.
|
||||
|
||||
Log-domain Sinkhorn - Uses log-sum-exp with max subtraction for numerical stability in exponentiation.
|
||||
|
||||
Batch parallelism in solver - Each thread processes one row/column in alternating Sinkhorn updates.
|
||||
|
||||
Vectorized distance computation - Efficient Euclidean distance calculation.
|
||||
|
||||
Warp reduction - Uses warp shuffle for final loss accumulation.
|
||||
|
||||
Entropy-regularized optimal transport - Solves Sinkhorn iterations for differentiable assignment.
|
||||
|
||||
Fixed-point iteration - Alternates between row and column normalization updates (5 iterations).
|
||||
|
||||
Efficient memory layout - Shared memory allocated for dual vectors and reduction buffer.
|
||||
|
||||
Regularization parameter - Uses ε=0.1 for entropy regularization strength.
|
||||
|
||||
|
||||
|
||||
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):
|
||||
super(Model, self).__init__()
|
||||
self.epsilon = 0.1
|
||||
self.num_iters = 5
|
||||
|
||||
def forward(self, x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
x_sq = torch.sum(x ** 2, dim=1, keepdim=True)
|
||||
t_sq = torch.sum(target ** 2, dim=1, keepdim=True)
|
||||
dist_sq = x_sq + t_sq.t() - 2 * torch.matmul(x, target.t())
|
||||
|
||||
C = dist_sq
|
||||
M = -C / self.epsilon
|
||||
|
||||
f = torch.zeros(x.size(0), 1, device=x.device)
|
||||
g = torch.zeros(1, x.size(0), device=x.device)
|
||||
|
||||
for _ in range(self.num_iters):
|
||||
f = -torch.logsumexp(M + g, dim=1, keepdim=True)
|
||||
g = -torch.logsumexp(M + f, dim=0, keepdim=True)
|
||||
|
||||
log_P = f + M + g
|
||||
P = torch.exp(log_P)
|
||||
|
||||
loss = torch.sum(P * C) / x.size(0)
|
||||
return loss
|
||||
|
||||
|
||||
batch_size = 128
|
||||
input_dim = 1024
|
||||
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, input_dim)
|
||||
target = torch.randn(batch_size, input_dim)
|
||||
return [x, target]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from HungarianLoss_torch import Model, get_inputs, get_init_inputs
|
||||
from HungarianLoss_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()
|
||||
Loading…
Reference in New Issue