diff --git a/S1/gsd123_#22/contrastiveloss_cuda.py b/S1/gsd123_#22/contrastiveloss_cuda.py new file mode 100644 index 00000000..692de2fd --- /dev/null +++ b/S1/gsd123_#22/contrastiveloss_cuda.py @@ -0,0 +1,124 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, margin=2.0): + super().__init__() + self.margin = margin + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor contrastive_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor y, float margin); + """ + + cuda_source = """ + #include + + __device__ __forceinline__ double warp_sum(double val) { + for (int offset = 16; offset > 0; offset /= 2) { + val += __shfl_down_sync(0xffffffff, val, offset); + } + return val; + } + + __device__ __forceinline__ double block_sum(double val) { + static __shared__ double shared[32]; + int lane = threadIdx.x % 32; + int wid = threadIdx.x / 32; + + val = warp_sum(val); + if (lane == 0) shared[wid] = val; + __syncthreads(); + + val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0; + if (wid == 0) val = warp_sum(val); + return val; + } + + __global__ void contrastive_kernel( + const float* __restrict__ x1, + const float* __restrict__ x2, + const float* __restrict__ y, + float* __restrict__ output, + int batch_size, + int feature_dim, + float margin) + { + int bid = blockIdx.x; + if (bid >= batch_size) return; + + const float* row_x1 = x1 + bid * feature_dim; + const float* row_x2 = x2 + bid * feature_dim; + + double sum_sq = 0.0; + + // Double precision accumulation for distance + for (int i = threadIdx.x; i < feature_dim; i += blockDim.x) { + double diff = (double)row_x1[i] - (double)row_x2[i]; + sum_sq += diff * diff; + } + + sum_sq = block_sum(sum_sq); + + if (threadIdx.x == 0) { + // dist = sqrt(sum_sq) + // term1 = (1-y) * dist^2 + // term2 = y * max(0, m - dist)^2 + // Note: dist^2 is just sum_sq, avoiding one sqrt call for term1 + + double dist = sqrt(sum_sq); + double label = (double)y[bid]; // Assuming y is [N, 1] stride is 1 if contiguous + + double loss_sim = (1.0 - label) * sum_sq; + + double margin_diff = (double)margin - dist; + if (margin_diff < 0.0) margin_diff = 0.0; + double loss_dis = label * (margin_diff * margin_diff); + + output[bid] = (float)(0.5 * (loss_sim + loss_dis)); + } + } + + torch::Tensor contrastive_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor y, float margin) { + auto x1_c = x1.contiguous(); + auto x2_c = x2.contiguous(); + auto y_c = y.contiguous(); + + int batch_size = x1_c.size(0); + int feature_dim = x1_c.size(1); + + auto output = torch::empty({batch_size}, x1.options()); + + int threads = 256; + int blocks = batch_size; + + contrastive_kernel<<>>( + x1_c.data_ptr(), + x2_c.data_ptr(), + y_c.data_ptr(), + output.data_ptr(), + batch_size, + feature_dim, + margin + ); + + // Reducing to scalar mean on PyTorch side is usually fast enough and cleaner + return output.mean(); + } + """ + + self.op = load_inline( + name="contrastive_opt_v1", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["contrastive_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x1, x2, y): + return self.op.contrastive_cuda(x1, x2, y, self.margin) \ No newline at end of file diff --git a/S1/gsd123_#22/contrastiveloss_torch.py b/S1/gsd123_#22/contrastiveloss_torch.py new file mode 100644 index 00000000..39bd8031 --- /dev/null +++ b/S1/gsd123_#22/contrastiveloss_torch.py @@ -0,0 +1,33 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Model(nn.Module): + def __init__(self, margin=2.0): + super().__init__() + self.margin = margin + + def forward(self, x1: torch.Tensor, x2: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + dist = F.pairwise_distance(x1, x2, keepdim=True) + + loss_con = (1 - y) * torch.pow(dist, 2) + loss_dis = y * torch.pow(torch.clamp(self.margin - dist, min=0.0), 2) + + loss = 0.5 * (loss_con + loss_dis) + return loss.mean() + + +batch_size = 128 +feature_dim = 512 + + +def get_inputs(): + x1 = torch.randn(batch_size, feature_dim, dtype=torch.float32) + x2 = torch.randn(batch_size, feature_dim, dtype=torch.float32) + y = torch.randint(0, 2, (batch_size, 1), dtype=torch.float32) + return [x1, x2, y] + + +def get_init_inputs(): + return [2.0] \ No newline at end of file diff --git a/S1/gsd123_#22/prompt.txt b/S1/gsd123_#22/prompt.txt new file mode 100644 index 00000000..7f053f25 --- /dev/null +++ b/S1/gsd123_#22/prompt.txt @@ -0,0 +1,81 @@ +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. + +CUDA Optimization Strategies: + +Parallel Reduction + +Warp shuffle operations (__shfl_down_sync) + +Shared memory for block-level reduction + +Double precision accumulation + +Memory Access + +contiguous() tensors for coalesced access + +__restrict__ pointers + +Sequential memory access per thread + +Computation Optimization + +Avoids redundant sqrt call by reusing squared distance + +Compiler flag: -O3 + +__forceinline__ for reduction functions + +Kernel Design + +One block per sample, 256 threads per block + +Threads process feature dimension with stride + +Final mean reduction on PyTorch side + +Numerical Stability + +Double precision for distance calculation + +Explicit bounds checking (max(0, margin-dist)) + + + + +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, margin=2.0): + super().__init__() + self.margin = margin + + def forward(self, x1: torch.Tensor, x2: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + dist = F.pairwise_distance(x1, x2, keepdim=True) + + loss_con = (1 - y) * torch.pow(dist, 2) + loss_dis = y * torch.pow(torch.clamp(self.margin - dist, min=0.0), 2) + + loss = 0.5 * (loss_con + loss_dis) + return loss.mean() + + +batch_size = 128 +feature_dim = 512 + + +def get_inputs(): + x1 = torch.randn(batch_size, feature_dim, dtype=torch.float32) + x2 = torch.randn(batch_size, feature_dim, dtype=torch.float32) + y = torch.randint(0, 2, (batch_size, 1), dtype=torch.float32) + return [x1, x2, y] + + +def get_init_inputs(): + return [2.0] \ No newline at end of file diff --git a/S1/gsd123_#22/run_code.py b/S1/gsd123_#22/run_code.py new file mode 100644 index 00000000..1cb7683b --- /dev/null +++ b/S1/gsd123_#22/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from contrastiveloss_torch import Model, get_inputs, get_init_inputs +from contrastiveloss_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