diff --git a/S1/39/TripletMarginWithDistanceLoss_cuda.py b/S1/39/TripletMarginWithDistanceLoss_cuda.py new file mode 100644 index 0000000..9c89326 --- /dev/null +++ b/S1/39/TripletMarginWithDistanceLoss_cuda.py @@ -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::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 + #include + + #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(anchor + offset); + const float4* p_ptr = reinterpret_cast(positive + offset); + const float4* n_ptr = reinterpret_cast(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<<>>( + anchor.data_ptr(), + positive.data_ptr(), + negative.data_ptr(), + output.data_ptr(), + 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() \ No newline at end of file diff --git a/S1/39/TripletMarginWithDistanceLoss_torch.py b/S1/39/TripletMarginWithDistanceLoss_torch.py new file mode 100644 index 0000000..f03048c --- /dev/null +++ b/S1/39/TripletMarginWithDistanceLoss_torch.py @@ -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] \ No newline at end of file diff --git a/S1/39/prompt.txt b/S1/39/prompt.txt new file mode 100644 index 0000000..5fc02dc --- /dev/null +++ b/S1/39/prompt.txt @@ -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 \ No newline at end of file diff --git a/S1/39/run_code.py b/S1/39/run_code.py new file mode 100644 index 0000000..26a2389 --- /dev/null +++ b/S1/39/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from TripletMarginWithDistanceLoss_torch import Model, get_inputs, get_init_inputs +from TripletMarginWithDistanceLoss_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() \ No newline at end of file