diff --git a/S1/wut0n_#19/cosine_cudacode.py b/S1/wut0n_#19/cosine_cudacode.py new file mode 100644 index 00000000..5fea0cf6 --- /dev/null +++ b/S1/wut0n_#19/cosine_cudacode.py @@ -0,0 +1,126 @@ +import torch +from torch.utils.cpp_extension import load_inline + +# CUDA 源代码字符串 +cosine_source = """ +#include +#include + +// 融合内核:余弦相似度 + 对比损失 +__global__ void cosine_contrastive_loss_kernel( + const float* __restrict__ x, + const float* __restrict__ y, + const float* __restrict__ labels, // 新增:标签 + float* __restrict__ losses, // 输出:每个样本的损失 + int batch_size, + int feature_dim, + float margin // 新增:margin值 +) { + int sample_idx = blockIdx.x; + if (sample_idx >= batch_size) return; + + int tid = threadIdx.x; + int base = sample_idx * feature_dim; + + // --- 1. 采样计算余弦相似度 (复用你之前的优秀代码) --- + const float SAMPLE_RATIO = 0.7f; + const int stride = max(1, (int)(1.0f / SAMPLE_RATIO)); + + float sampled_dot = 0.0f; + float sampled_norm_x = 0.0f; + float sampled_norm_y = 0.0f; + + for (int i = tid; i < feature_dim; i += blockDim.x * stride) { + float x_val = x[base + i]; + float y_val = y[base + i]; + + sampled_dot += x_val * y_val; + sampled_norm_x += x_val * x_val; + sampled_norm_y += y_val * y_val; + } + + for (int offset = 16; offset > 0; offset /= 2) { + sampled_dot += __shfl_down_sync(0xffffffff, sampled_dot, offset); + sampled_norm_x += __shfl_down_sync(0xffffffff, sampled_norm_x, offset); + sampled_norm_y += __shfl_down_sync(0xffffffff, sampled_norm_y, offset); + } + + float cosine_sim = 0.0f; + if (tid == 0) { + float scale_factor = 1.0f / SAMPLE_RATIO; + float total_dot = sampled_dot * scale_factor; + float total_norm_x = sampled_norm_x * scale_factor; + float total_norm_y = sampled_norm_y * scale_factor; + + float norm_x = sqrtf(total_norm_x); + float norm_y = sqrtf(total_norm_y); + cosine_sim = total_dot / (norm_x * norm_y + 1e-8f); + + // --- 2. 融合:直接计算对比损失 --- + float label = labels[sample_idx]; + float loss_val; + if (label > 0.5f) { // 假设标签为1表示相似 + loss_val = 1.0f - cosine_sim; + } else { + loss_val = fmaxf(0.0f, cosine_sim - margin); + } + losses[sample_idx] = loss_val; + } +} + +torch::Tensor cosine_contrastive_loss_cuda( + torch::Tensor x, + torch::Tensor y, + torch::Tensor labels, + float margin +) { + auto x_contig = x.contiguous(); + auto y_contig = y.contiguous(); + auto labels_contig = labels.contiguous(); + + int batch_size = x_contig.size(0); + int feature_dim = x_contig.size(1); + + // 输出每个样本的损失,最后在Python中求和 + auto losses = torch::zeros({batch_size}, x.options()); + + const int block_size = 32; + + cosine_contrastive_loss_kernel<<>>( + x_contig.data_ptr(), + y_contig.data_ptr(), + labels_contig.data_ptr(), + losses.data_ptr(), + batch_size, + feature_dim, + margin + ); + + return losses; +} +""" + +cosine_cpp_source = """ +torch::Tensor cosine_contrastive_loss_cuda(torch::Tensor x, torch::Tensor y, torch::Tensor labels, float margin); +""" + +# 编译CUDA代码 +cosine = load_inline( + name="cosine", + cpp_sources=cosine_cpp_source, + cuda_sources=cosine_source, + functions=["cosine_contrastive_loss_cuda"], + extra_cuda_cflags=["-O3", "--use_fast_math", "-std=c++17"], + verbose=True +) + +class ModelNew(torch.nn.Module): + def __init__(self, margin=0.5): + super(ModelNew, self).__init__() + self.cosine = cosine + self.margin = margin + + def forward(self, x, y, labels): + # 内核返回每个样本的loss,我们手动求和 + per_sample_loss = self.cosine.cosine_contrastive_loss_cuda(x, y, labels, self.margin) + return torch.sum(per_sample_loss) diff --git a/S1/wut0n_#19/cosine_torchcode.py b/S1/wut0n_#19/cosine_torchcode.py new file mode 100644 index 00000000..9afd86ce --- /dev/null +++ b/S1/wut0n_#19/cosine_torchcode.py @@ -0,0 +1,38 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + """ + Baseline: Cosine Similarity + Contrastive Loss + """ + def __init__(self, margin=0.5): + super(Model, self).__init__() + self.margin = margin + + def forward(self, x: torch.Tensor, y: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + # 1. 计算余弦相似度 + norm_x = torch.sqrt(torch.sum(x * x, dim=1, keepdim=True)) + norm_y = torch.sqrt(torch.sum(y * y, dim=1, keepdim=True)) + dot_product = torch.sum(x * y, dim=1, keepdim=True) + cosine_sim = dot_product / (norm_x * norm_y + 1e-8) + cosine_sim = cosine_sim.squeeze(1) + + # 2. 计算对比损失 + loss_positive = labels * (1 - cosine_sim) + loss_negative = (1 - labels) * torch.relu(cosine_sim - self.margin) + loss = loss_positive + loss_negative + + return torch.sum(loss) + +batch_size = 1024 +feature_dim = 512 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim) + y = torch.randn(batch_size, feature_dim) + # 生成0或1的标签 + labels = torch.randint(0, 2, (batch_size,)).float() + return [x, y, labels] + +def get_init_inputs(): + return [] diff --git a/S1/wut0n_#19/prompt.txt b/S1/wut0n_#19/prompt.txt new file mode 100644 index 00000000..3a3a0e82 --- /dev/null +++ b/S1/wut0n_#19/prompt.txt @@ -0,0 +1,95 @@ +You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination. + +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) -> None: + super().__init__() + + def forward(self, a, b): + return a + b + +def get_inputs(): + # randomly generate input tensors based on the model architecture + a = torch.randn(1, 128).cuda() + b = torch.randn(1, 128).cuda() + return [a, b] + +def get_init_inputs(): + # randomly generate tensors required for initialization based on the model architecture + return [] +The example new arch with custom CUDA kernels looks like this: + + + +import torch +import torch.nn as nn +import torch.nn.functional as F + +class Model(nn.Module): + def __init__(self) -> None: + super().__init__() + + def forward(self, a, b): + return a + b + +def get_inputs(): + # randomly generate input tensors based on the model architecture + a = torch.randn(1, 128).cuda() + b = torch.randn(1, 128).cuda() + return [a, b] + +def get_init_inputs(): + # randomly generate tensors required for initialization based on the model architecture + return [] +You are given the following architecture: + + + +import torch +import torch.nn as nn + +class Model(nn.Module): + """ + Baseline: Cosine Similarity + Contrastive Loss + """ + def __init__(self, margin=0.5): + super(Model, self).__init__() + self.margin = margin + + def forward(self, x: torch.Tensor, y: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + # 1. Compute cosine similarity + norm_x = torch.sqrt(torch.sum(x * x, dim=1, keepdim=True)) + norm_y = torch.sqrt(torch.sum(y * y, dim=1, keepdim=True)) + dot_product = torch.sum(x * y, dim=1, keepdim=True) + cosine_sim = dot_product / (norm_x * norm_y + 1e-8) + cosine_sim = cosine_sim.squeeze(1) + + # 2. Compute contrastive loss + loss_positive = labels * (1 - cosine_sim) + loss_negative = (1 - labels) * torch.relu(cosine_sim - self.margin) + loss = loss_positive + loss_negative + + return torch.sum(loss) + +batch_size = 1024 +feature_dim = 512 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim) + y = torch.randn(batch_size, feature_dim) + # Generate binary labels (0 or 1) + labels = torch.randint(0, 2, (batch_size,)).float() + return [x, y, labels] + +def get_init_inputs(): + return [] +IMPORTANT: The current architecture involves two distinct stages: a cosine similarity calculation followed by a contrastive loss computation. This creates an intermediate tensor (cosine_sim) that incurs memory overhead and multiple kernel launches. The primary optimization goal is operator fusion: combine the cosine similarity and contrastive loss into a single, highly efficient CUDA kernel. This fusion should eliminate the intermediate tensor, reduce memory traffic, and minimize kernel launch overhead. Furthermore, you are encouraged to integrate advanced algorithmic innovations, such as the sampling-based approximation with statistical correction, into the fused kernel to achieve substantial performance gains while maintaining numerical accuracy. Focus on creating a novel approach that is fundamentally different from simple element-wise or vectorized PyTorch operations. \ No newline at end of file diff --git a/S1/wut0n_#19/run_code.py b/S1/wut0n_#19/run_code.py new file mode 100644 index 00000000..9ae43938 --- /dev/null +++ b/S1/wut0n_#19/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from cosine_torchcode import Model, get_inputs, get_init_inputs +from cosine_cudacode 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 Cosine + Contrastive 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA Cosine + Contrastive 平均执行时间: {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