forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'fix TripletMarginWithDistanceLoss #14' (#121) from gsd123/GPUCodeForces:gsd14 into main
This commit is contained in:
commit
a8868ed0d5
|
|
@ -0,0 +1,197 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
N, D = 32, 128
|
||||
|
||||
assert D % 4 == 0, "Embedding dimension D must be a multiple of 4 for vectorization"
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
|
||||
def __init__(self, margin=1.0, swap=False):
|
||||
super().__init__()
|
||||
self.margin = float(margin)
|
||||
self.swap = swap
|
||||
self.block_size = 256
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
torch::Tensor triplet_forward_cuda(
|
||||
torch::Tensor anchor,
|
||||
torch::Tensor positive,
|
||||
torch::Tensor negative,
|
||||
float margin,
|
||||
bool swap,
|
||||
int N,
|
||||
int D);
|
||||
"""
|
||||
|
||||
cuda_source = f"""
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE {self.block_size}
|
||||
#define WARP_SIZE 32
|
||||
|
||||
// Warp 归约工具
|
||||
__inline__ __device__ float warp_reduce_sum(float val) {{
|
||||
#pragma unroll
|
||||
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {{
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
}}
|
||||
return val;
|
||||
}}
|
||||
|
||||
|
||||
__global__ void triplet_l2_kernel(
|
||||
const float* __restrict__ anchor,
|
||||
const float* __restrict__ positive,
|
||||
const float* __restrict__ negative,
|
||||
float* __restrict__ output,
|
||||
float margin,
|
||||
bool swap,
|
||||
int D_vec // D / 4
|
||||
) {{
|
||||
const int n_idx = blockIdx.x;
|
||||
const int tid = threadIdx.x;
|
||||
|
||||
|
||||
const int offset = n_idx * D_vec * 4;
|
||||
const float4* a_ptr = reinterpret_cast<const float4*>(anchor + offset);
|
||||
const float4* p_ptr = reinterpret_cast<const float4*>(positive + offset);
|
||||
const float4* n_ptr = reinterpret_cast<const float4*>(negative + offset);
|
||||
|
||||
|
||||
float sum_sq_ap = 0.0f;
|
||||
float sum_sq_an = 0.0f;
|
||||
float sum_sq_pn = 0.0f;
|
||||
|
||||
|
||||
for (int i = tid; i < D_vec; i += BLOCK_SIZE) {{
|
||||
float4 a = __ldg(&a_ptr[i]);
|
||||
float4 p = __ldg(&p_ptr[i]);
|
||||
float4 n = __ldg(&n_ptr[i]);
|
||||
|
||||
|
||||
float4 diff_ap, diff_an, diff_pn;
|
||||
|
||||
diff_ap.x = a.x - p.x; diff_ap.y = a.y - p.y; diff_ap.z = a.z - p.z; diff_ap.w = a.w - p.w;
|
||||
diff_an.x = a.x - n.x; diff_an.y = a.y - n.y; diff_an.z = a.z - n.z; diff_an.w = a.w - n.w;
|
||||
|
||||
|
||||
sum_sq_ap += diff_ap.x*diff_ap.x + diff_ap.y*diff_ap.y + diff_ap.z*diff_ap.z + diff_ap.w*diff_ap.w;
|
||||
sum_sq_an += diff_an.x*diff_an.x + diff_an.y*diff_an.y + diff_an.z*diff_an.z + diff_an.w*diff_an.w;
|
||||
|
||||
if (swap) {{
|
||||
diff_pn.x = p.x - n.x; diff_pn.y = p.y - n.y; diff_pn.z = p.z - n.z; diff_pn.w = p.w - n.w;
|
||||
sum_sq_pn += diff_pn.x*diff_pn.x + diff_pn.y*diff_pn.y + diff_pn.z*diff_pn.z + diff_pn.w*diff_pn.w;
|
||||
}}
|
||||
}}
|
||||
|
||||
|
||||
__shared__ float shared_data[32][3];
|
||||
|
||||
int lane = tid % WARP_SIZE;
|
||||
int wid = tid / WARP_SIZE;
|
||||
|
||||
|
||||
sum_sq_ap = warp_reduce_sum(sum_sq_ap);
|
||||
sum_sq_an = warp_reduce_sum(sum_sq_an);
|
||||
if (swap) sum_sq_pn = warp_reduce_sum(sum_sq_pn);
|
||||
|
||||
|
||||
if (lane == 0) {{
|
||||
shared_data[wid][0] = sum_sq_ap;
|
||||
shared_data[wid][1] = sum_sq_an;
|
||||
if (swap) shared_data[wid][2] = sum_sq_pn;
|
||||
}}
|
||||
__syncthreads();
|
||||
|
||||
|
||||
if (wid == 0) {{
|
||||
sum_sq_ap = (tid < blockDim.x / WARP_SIZE) ? shared_data[lane][0] : 0.0f;
|
||||
sum_sq_an = (tid < blockDim.x / WARP_SIZE) ? shared_data[lane][1] : 0.0f;
|
||||
sum_sq_pn = (tid < blockDim.x / WARP_SIZE && swap) ? shared_data[lane][2] : 0.0f;
|
||||
|
||||
sum_sq_ap = warp_reduce_sum(sum_sq_ap);
|
||||
sum_sq_an = warp_reduce_sum(sum_sq_an);
|
||||
if (swap) sum_sq_pn = warp_reduce_sum(sum_sq_pn);
|
||||
|
||||
|
||||
if (tid == 0) {{
|
||||
// 开根号得到 L2 距离 (加上 epsilon 防止梯度爆炸通常在backward处理,前向计算通常加个极小值)
|
||||
float dist_ap = sqrtf(sum_sq_ap + 1e-8f);
|
||||
float dist_an = sqrtf(sum_sq_an + 1e-8f);
|
||||
|
||||
if (swap) {{
|
||||
float dist_pn = sqrtf(sum_sq_pn + 1e-8f);
|
||||
if (dist_pn < dist_an) {{
|
||||
dist_an = dist_pn;
|
||||
}}
|
||||
}}
|
||||
|
||||
// loss = max(d_ap - d_an + margin, 0)
|
||||
float loss = fmaxf(dist_ap - dist_an + margin, 0.0f);
|
||||
output[n_idx] = loss;
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
|
||||
torch::Tensor triplet_forward_cuda(
|
||||
torch::Tensor anchor,
|
||||
torch::Tensor positive,
|
||||
torch::Tensor negative,
|
||||
float margin,
|
||||
bool swap,
|
||||
int N,
|
||||
int D)
|
||||
{{
|
||||
anchor = anchor.contiguous();
|
||||
positive = positive.contiguous();
|
||||
negative = negative.contiguous();
|
||||
|
||||
auto output = torch::empty({{N}}, anchor.options());
|
||||
|
||||
int D_vec = D / 4;
|
||||
|
||||
dim3 blocks(N);
|
||||
dim3 threads(BLOCK_SIZE);
|
||||
|
||||
triplet_l2_kernel<<<blocks, threads>>>(
|
||||
anchor.data_ptr<float>(),
|
||||
positive.data_ptr<float>(),
|
||||
negative.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
margin,
|
||||
swap,
|
||||
D_vec
|
||||
);
|
||||
|
||||
return output;
|
||||
}}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name='triplet_loss_cuda_v1',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['triplet_forward_cuda'],
|
||||
extra_cuda_cflags=['-O3', '--use_fast_math'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, a: torch.Tensor, p: torch.Tensor, n: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
if not a.is_cuda: a = a.cuda()
|
||||
if not p.is_cuda: p = p.cuda()
|
||||
if not n.is_cuda: n = n.cuda()
|
||||
|
||||
N, D = a.shape
|
||||
|
||||
losses = self.op.triplet_forward_cuda(a, p, n, self.margin, self.swap, N, D)
|
||||
|
||||
return losses.mean()
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
N, D = 32, 128
|
||||
|
||||
|
||||
class TripletMarginWithDistanceLoss(nn.Module):
|
||||
|
||||
def __init__(self, distance_function=None, margin=1.0, swap=False, reduction='mean'):
|
||||
super().__init__()
|
||||
self.distance_function = distance_function if distance_function is not None else nn.PairwiseDistance()
|
||||
self.margin = margin
|
||||
self.swap = swap
|
||||
self.reduction = reduction
|
||||
|
||||
def forward(self, anchor: torch.Tensor, positive: torch.Tensor, negative: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
d_ap = self.distance_function(anchor, positive)
|
||||
|
||||
d_an = self.distance_function(anchor, negative)
|
||||
|
||||
if self.swap:
|
||||
d_pn = self.distance_function(positive, negative)
|
||||
d_an = torch.min(d_an, d_pn)
|
||||
|
||||
loss = torch.clamp(d_ap - d_an + self.margin, min=0.0)
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else: # 'none'
|
||||
return loss
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, margin=1.0, swap=False):
|
||||
super().__init__()
|
||||
|
||||
self.op = TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance(), margin=margin, swap=swap)
|
||||
|
||||
def forward(self, a: torch.Tensor, p: torch.Tensor, n: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(a, p, n)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
anchor = torch.randn(N, D, dtype=torch.float32)
|
||||
positive = torch.randn(N, D, dtype=torch.float32)
|
||||
negative = torch.randn(N, D, dtype=torch.float32)
|
||||
return [anchor, positive, negative]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return [1.0, False]
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm 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 normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
|
||||
|
||||
Technical Overview: CUDA-Optimized Triplet Margin Loss with L2 Distance
|
||||
This implementation provides a high-performance CUDA kernel for computing triplet loss, designed for deep metric learning applications with optimized parallel computation and memory access patterns.
|
||||
Key Features:
|
||||
Architecture:
|
||||
Custom CUDA kernel with inline compilation using PyTorch C++ extensions
|
||||
Optimized for NVIDIA GPUs with warp-level parallelism and shared memory utilization
|
||||
Supports 4-element vectorization (float4) for memory coalescing
|
||||
Implements both standard and "swap" variants of triplet loss
|
||||
Performance Optimizations:
|
||||
Vectorized Memory Access: Uses float4 data type to load 4 elements per instruction
|
||||
Coalesced Memory Reads: Contiguous memory access through __ldgintrinsic
|
||||
Warp Reduction: Efficient warp-level reduction operations using __shfl_down_sync
|
||||
Shared Memory: Intermediate results stored in shared memory for block-level reduction
|
||||
Branch Optimization: Conditional swap computation handled efficiently
|
||||
Kernel Specifications:
|
||||
Block size: 256 threads
|
||||
Warp size: 32 threads
|
||||
Grid dimension: N (batch size)
|
||||
Input requirement: Embedding dimension D must be divisible by 4
|
||||
|
||||
|
||||
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
|
||||
|
||||
N, D = 32, 128
|
||||
|
||||
|
||||
class TripletMarginWithDistanceLoss(nn.Module):
|
||||
|
||||
def __init__(self, distance_function=None, margin=1.0, swap=False, reduction='mean'):
|
||||
super().__init__()
|
||||
self.distance_function = distance_function if distance_function is not None else nn.PairwiseDistance()
|
||||
self.margin = margin
|
||||
self.swap = swap
|
||||
self.reduction = reduction
|
||||
|
||||
def forward(self, anchor: torch.Tensor, positive: torch.Tensor, negative: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
d_ap = self.distance_function(anchor, positive)
|
||||
|
||||
d_an = self.distance_function(anchor, negative)
|
||||
|
||||
if self.swap:
|
||||
d_pn = self.distance_function(positive, negative)
|
||||
d_an = torch.min(d_an, d_pn)
|
||||
|
||||
loss = torch.clamp(d_ap - d_an + self.margin, min=0.0)
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else: # 'none'
|
||||
return loss
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, margin=1.0, swap=False):
|
||||
super().__init__()
|
||||
|
||||
self.op = TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance(), margin=margin, swap=swap)
|
||||
|
||||
def forward(self, a: torch.Tensor, p: torch.Tensor, n: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(a, p, n)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
anchor = torch.randn(N, D, dtype=torch.float32)
|
||||
positive = torch.randn(N, D, dtype=torch.float32)
|
||||
negative = torch.randn(N, D, dtype=torch.float32)
|
||||
return [anchor, positive, negative]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return [1.0, False] # margin, swap
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
import torch
|
||||
import time
|
||||
from TripletMarginWithDistanceLoss_torch import Model, get_inputs, get_init_inputs
|
||||
from TripletMarginWithDistanceLoss_cuda import ModelNew
|
||||
|
||||
def run_benchmark():
|
||||
if not torch.cuda.is_available():
|
||||
print("CUDA 不可用")
|
||||
return
|
||||
|
||||
device = torch.device("cuda")
|
||||
|
||||
# 准备输入数据
|
||||
inputs = [x.cuda(device=device) for x in get_inputs()]
|
||||
init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()]
|
||||
|
||||
# 初始化模型
|
||||
torch_model = Model(*init_inputs).cuda()
|
||||
cuda_model = ModelNew(*init_inputs).cuda()
|
||||
|
||||
torch_model.eval()
|
||||
cuda_model.eval()
|
||||
|
||||
print("-------------------- 精度对齐验证 --------------------")
|
||||
with torch.no_grad():
|
||||
# 预热GPU
|
||||
_ = torch_model(*inputs)
|
||||
_ = cuda_model(*inputs)
|
||||
|
||||
# 正式测试
|
||||
output_torch = torch_model(*inputs)
|
||||
output_cuda = cuda_model(*inputs)
|
||||
|
||||
# 精度验证
|
||||
abs_diff = torch.abs(output_torch - output_cuda)
|
||||
max_diff = torch.max(abs_diff).item()
|
||||
mean_diff = torch.mean(abs_diff).item()
|
||||
|
||||
if max_diff < 1e-4 and mean_diff < 1e-5:
|
||||
print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
|
||||
precision_flag = True
|
||||
else:
|
||||
print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
|
||||
precision_flag = False
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 100
|
||||
|
||||
# 预热GPU
|
||||
for _ in range(10):
|
||||
_ = torch_model(*inputs)
|
||||
_ = cuda_model(*inputs)
|
||||
|
||||
# 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内置Swish平均执行时间: {torch_time:.6f}秒")
|
||||
print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}秒")
|
||||
speedup = torch_time / cuda_time if cuda_time > 0 else 0
|
||||
print(f"加速比 (Speedup): {speedup:.2f}x")
|
||||
|
||||
return precision_flag, speedup
|
||||
|
||||
if __name__ == "__main__":
|
||||
precision_flag, speedup = run_benchmark()
|
||||
Loading…
Reference in New Issue