finish SupConLoss #139

This commit is contained in:
gsd 2025-12-09 11:59:38 +08:00
parent e8d83740df
commit 8fbf1b2a44
4 changed files with 425 additions and 0 deletions

View File

@ -0,0 +1,227 @@
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 <cmath>
#define EPSILON 1e-12f
__inline__ __device__ float warpReduceSum(float val) {
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_down_sync(0xffffffff, val, offset);
return val;
}
__global__ void normalize_kernel(const float* __restrict__ input, float* output, int rows, int cols) {
int bid = blockIdx.x; // row index
if (bid >= rows) return;
int tid = threadIdx.x;
const float* row_in = input + bid * cols;
float* row_out = output + bid * cols;
// Sum squares
float sum_sq = 0.0f;
for (int i = tid; i < cols; i += blockDim.x) {
float val = row_in[i];
sum_sq += val * val;
}
// Block Reduction
__shared__ float s_sum[32];
int lane = tid % 32;
int wid = tid / 32;
sum_sq = warpReduceSum(sum_sq);
if (lane == 0) s_sum[wid] = sum_sq;
__syncthreads();
float total_sum_sq = (tid < (blockDim.x / 32)) ? s_sum[tid] : 0.0f;
if (tid < 32) total_sum_sq = warpReduceSum(total_sum_sq);
// Broadcast norm factor
__shared__ float norm_factor;
if (tid == 0) {
float norm = sqrtf(total_sum_sq);
norm_factor = 1.0f / fmaxf(norm, EPSILON);
}
__syncthreads();
// Write output
float scale = norm_factor;
for (int i = tid; i < cols; i += blockDim.x) {
row_out[i] = row_in[i] * scale;
}
}
__global__ void supcon_loss_kernel(
const float* __restrict__ scores, // [N, N]
const int64_t* __restrict__ labels,
float* loss_out,
int batch_size
) {
int row = blockIdx.x;
if (row >= batch_size) return;
int tid = threadIdx.x;
int64_t my_label = labels[row];
const float* row_ptr = scores + row * batch_size;
// -- Local Registers --
// Softmax stats: M (max), S (sum_exp)
// Init: max = -inf, sum = 0
float max_val = -1e38f;
float sum_exp = 0.0f;
// Positive stats
float sum_pos = 0.0f;
float cnt_pos = 0.0f;
// Loop over columns
for (int col = tid; col < batch_size; col += blockDim.x) {
float val = row_ptr[col];
// 1. Update LogSumExp stats (Denominator: j != i)
if (col != row) {
if (val > max_val) {
sum_exp = sum_exp * expf(max_val - val) + 1.0f;
max_val = val;
} else {
sum_exp += expf(val - max_val);
}
}
// 2. Update Positive stats (Numerator: label[j] == label[i])
if (labels[col] == my_label) {
sum_pos += val;
cnt_pos += 1.0f;
}
}
// -- Warp Reduction --
for (int offset = 16; offset > 0; offset /= 2) {
// Simple sum reduction
sum_pos += __shfl_down_sync(0xffffffff, sum_pos, offset);
cnt_pos += __shfl_down_sync(0xffffffff, cnt_pos, offset);
// Softmax reduction (merge two (M, S) pairs)
float other_max = __shfl_down_sync(0xffffffff, max_val, offset);
float other_sum = __shfl_down_sync(0xffffffff, sum_exp, offset);
float new_max = fmaxf(max_val, other_max);
float scale_self = expf(max_val - new_max);
float scale_other = expf(other_max - new_max);
sum_exp = sum_exp * scale_self + other_sum * scale_other;
max_val = new_max;
}
// -- Block Reduction via Shared Memory --
__shared__ float s_max[32];
__shared__ float s_sum_e[32];
__shared__ float s_sum_p[32];
__shared__ float s_cnt[32];
int lane = tid % 32;
int wid = tid / 32;
if (lane == 0) {
s_max[wid] = max_val;
s_sum_e[wid] = sum_exp;
s_sum_p[wid] = sum_pos;
s_cnt[wid] = cnt_pos;
}
__syncthreads();
// Final reduction by first warp
if (tid < 32) {
int num_warps = (blockDim.x + 31) / 32;
float l_max = (tid < num_warps) ? s_max[tid] : -1e38f;
float l_sum_e = (tid < num_warps) ? s_sum_e[tid] : 0.0f;
float l_sum_p = (tid < num_warps) ? s_sum_p[tid] : 0.0f;
float l_cnt = (tid < num_warps) ? s_cnt[tid] : 0.0f;
for (int offset = 16; offset > 0; offset /= 2) {
l_sum_p += __shfl_down_sync(0xffffffff, l_sum_p, offset);
l_cnt += __shfl_down_sync(0xffffffff, l_cnt, offset);
float other_max = __shfl_down_sync(0xffffffff, l_max, offset);
float other_sum = __shfl_down_sync(0xffffffff, l_sum_e, offset);
float new_max = fmaxf(l_max, other_max);
float scale_self = expf(l_max - new_max);
float scale_other = expf(other_max - new_max);
l_sum_e = l_sum_e * scale_self + other_sum * scale_other;
l_max = new_max;
}
if (tid == 0) {
// Formula: Loss = LogSumExp(logits_{j!=i}) - Mean(logits_{pos})
float log_sum_exp = l_max + logf(l_sum_e);
if (l_cnt > 0.5f) {
float mean_pos = l_sum_p / l_cnt;
loss_out[row] = log_sum_exp - mean_pos;
} else {
loss_out[row] = 0.0f; // Should not happen if i is in batch
}
}
}
}
torch::Tensor supcon_cuda_forward(torch::Tensor features, torch::Tensor labels, float temperature) {
auto f_c = features.contiguous();
auto l_c = labels.contiguous();
int batch_size = f_c.size(0);
int dim = f_c.size(1);
// 1. Normalize
auto f_norm = torch::empty_like(f_c);
normalize_kernel<<<batch_size, 256>>>(f_c.data_ptr<float>(), f_norm.data_ptr<float>(), batch_size, dim);
// 2. Similarity Matrix
auto scores = torch::matmul(f_norm, f_norm.transpose(0, 1));
scores.div_(temperature);
// 3. Loss Calculation
auto loss = torch::empty({batch_size}, f_c.options());
supcon_loss_kernel<<<batch_size, 256>>>(
scores.data_ptr<float>(),
l_c.data_ptr<int64_t>(),
loss.data_ptr<float>(),
batch_size
);
return loss.mean();
}
"""
cpp_source = """
torch::Tensor supcon_cuda_forward(torch::Tensor features, torch::Tensor labels, float temperature);
"""
supcon_loss_module = load_inline(
name="supcon_loss_opt_precise",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["supcon_cuda_forward"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, temperature):
super(ModelNew, self).__init__()
self.temperature = temperature
def forward(self, features, labels):
return supcon_loss_module.supcon_cuda_forward(features, labels, self.temperature)

View File

@ -0,0 +1,46 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, temperature):
super(Model, self).__init__()
self.temperature = temperature
def forward(self, features: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
batch_size = features.shape[0]
features = torch.nn.functional.normalize(features, dim=1)
similarity_matrix = torch.matmul(features, features.T) / self.temperature
mask = labels.unsqueeze(0) == labels.unsqueeze(1)
mask = mask.float()
logits_mask = torch.ones_like(mask)
logits_mask.fill_diagonal_(0)
exp_logits = torch.exp(similarity_matrix) * logits_mask
log_prob = similarity_matrix - torch.log(exp_logits.sum(1, keepdim=True))
mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
loss = -mean_log_prob_pos.mean()
return loss
batch_size = 16
dim = 128
num_classes = 10
def get_inputs():
features = torch.randn(batch_size, dim)
labels = torch.randint(0, num_classes, (batch_size,))
return [features, labels]
def get_init_inputs():
temperature = 0.07
return [temperature]

75
S1/gsd123_#139/prompt.txt Normal file
View File

@ -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.
Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline
Supervised Contrastive (SupCon) loss computation
Multi-kernel design: normalization + similarity + loss computation
Row-wise L2 normalization with warp-level reduction
Similarity matrix computation via torch::matmul with temperature scaling
Advanced log-sum-exp reduction with warp-shuffle merging
Label-based positive/negative separation for supervised contrastive learning
Warp-shuffle primitives (__shfl_down_sync) for efficient reductions
Two-phase reduction: warp-level → shared memory → final warp
Numerical stability with EPSILON protection
Contiguous tensor handling for memory coalescing
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, temperature):
super(Model, self).__init__()
self.temperature = temperature
def forward(self, features: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
batch_size = features.shape[0]
features = torch.nn.functional.normalize(features, dim=1)
similarity_matrix = torch.matmul(features, features.T) / self.temperature
mask = labels.unsqueeze(0) == labels.unsqueeze(1)
mask = mask.float()
logits_mask = torch.ones_like(mask)
logits_mask.fill_diagonal_(0)
exp_logits = torch.exp(similarity_matrix) * logits_mask
log_prob = similarity_matrix - torch.log(exp_logits.sum(1, keepdim=True))
mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
loss = -mean_log_prob_pos.mean()
return loss
batch_size = 16
dim = 128
num_classes = 10
def get_inputs():
features = torch.randn(batch_size, dim)
labels = torch.randint(0, num_classes, (batch_size,))
return [features, labels]
def get_init_inputs():
temperature = 0.07
return [temperature]

View File

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