From 5f144659209132049857c163a96cfb78018dc6fa Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 11 Nov 2025 19:15:50 +0800 Subject: [PATCH] fixes kldivloss #29 --- S1/29/kldivloss_cuda.py | 210 +++++++++++++++++++++++++++++++++++++++ S1/29/kldivloss_torch.py | 26 +++++ S1/29/prompt.txt | 33 ++++++ S1/29/run_code.py | 88 ++++++++++++++++ 4 files changed, 357 insertions(+) create mode 100644 S1/29/kldivloss_cuda.py create mode 100644 S1/29/kldivloss_torch.py create mode 100644 S1/29/prompt.txt create mode 100644 S1/29/run_code.py diff --git a/S1/29/kldivloss_cuda.py b/S1/29/kldivloss_cuda.py new file mode 100644 index 0000000..e9234b9 --- /dev/null +++ b/S1/29/kldivloss_cuda.py @@ -0,0 +1,210 @@ +# kldivloss_cuda_ultra.py +import torch +from torch.utils.cpp_extension import load_inline +from kldivloss_torch import BATCH_SIZE, DIM + +class ModelNew(torch.nn.Module): + + def __init__(self): + super().__init__() + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor kldiv_forward_cuda(torch::Tensor input_logits, torch::Tensor target_prob); + """ + + cuda_source = """ + #include + #include + namespace cg = cooperative_groups; + + #define BLOCK_SIZE 256 + #define VEC_SIZE 4 + #define WARP_SIZE 32 + + // Ultra-fast warp reduction using cooperative groups + __device__ __forceinline__ double warp_reduce_sum_cg(double val) { + #pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + val += __shfl_down_sync(0xffffffff, val, offset); + } + return val; + } + + // Optimized block reduction + __device__ __forceinline__ double block_reduce_sum(double val) { + __shared__ double warp_sums[8]; + + int lane = threadIdx.x & 31; + int warp_id = threadIdx.x >> 5; + + val = warp_reduce_sum_cg(val); + + if (lane == 0) { + warp_sums[warp_id] = val; + } + __syncthreads(); + + if (warp_id == 0) { + val = (lane < 8) ? warp_sums[lane] : 0.0; + val = warp_reduce_sum_cg(val); + } + + return val; + } + + // Safe and fast KL term computation + __device__ __forceinline__ double safe_kl_term(float p, float log_q) { + // Avoid NaN: when p < eps, contribution is 0 + return (p > 1e-8f) ? ((double)p * (__logf(p) - log_q)) : 0.0; + } + + // Version 1: Maximally unrolled with 8x vectorization + __global__ void kldiv_kernel_v1( + const float* __restrict__ input_logits, + const float* __restrict__ target_prob, + double* __restrict__ output_sum, + int N_elements + ) { + double sum = 0.0; + + int N_vec = N_elements >> 2; // / 4 + int tid = (blockIdx.x * blockDim.x + threadIdx.x); + int stride = gridDim.x * blockDim.x; + + const float4* __restrict__ in4 = (const float4*)input_logits; + const float4* __restrict__ tgt4 = (const float4*)target_prob; + + // 8x unrolled loop + for (int i = tid; i < N_vec; i += stride << 3) { + #pragma unroll + for (int u = 0; u < 8; u++) { + int idx = i + (u * stride); + if (idx < N_vec) { + float4 lq = in4[idx]; + float4 p = tgt4[idx]; + + sum += safe_kl_term(p.x, lq.x); + sum += safe_kl_term(p.y, lq.y); + sum += safe_kl_term(p.z, lq.z); + sum += safe_kl_term(p.w, lq.w); + } + } + } + + sum = block_reduce_sum(sum); + + if (threadIdx.x == 0) { + output_sum[blockIdx.x] = sum; + } + } + + // Version 2: Register-tiled with manual prefetching + __global__ void kldiv_kernel_v2( + const float* __restrict__ input_logits, + const float* __restrict__ target_prob, + double* __restrict__ output_sum, + int N_elements + ) { + double sum = 0.0; + + int N_vec = N_elements >> 2; + int tid = blockIdx.x * blockDim.x + threadIdx.x; + int stride = gridDim.x * blockDim.x; + + const float4* __restrict__ in4 = (const float4*)input_logits; + const float4* __restrict__ tgt4 = (const float4*)target_prob; + + // Process 4 vectors per iteration (register tiling) + for (int i = tid; i < N_vec; i += stride * 4) { + float4 lq0, lq1, lq2, lq3; + float4 p0, p1, p2, p3; + + // Load 4 vectors + if (i < N_vec) { lq0 = in4[i]; p0 = tgt4[i]; } + if (i + stride < N_vec) { lq1 = in4[i + stride]; p1 = tgt4[i + stride]; } + if (i + stride*2 < N_vec) { lq2 = in4[i + stride*2]; p2 = tgt4[i + stride*2]; } + if (i + stride*3 < N_vec) { lq3 = in4[i + stride*3]; p3 = tgt4[i + stride*3]; } + + // Compute + if (i < N_vec) { + sum += safe_kl_term(p0.x, lq0.x) + safe_kl_term(p0.y, lq0.y); + sum += safe_kl_term(p0.z, lq0.z) + safe_kl_term(p0.w, lq0.w); + } + if (i + stride < N_vec) { + sum += safe_kl_term(p1.x, lq1.x) + safe_kl_term(p1.y, lq1.y); + sum += safe_kl_term(p1.z, lq1.z) + safe_kl_term(p1.w, lq1.w); + } + if (i + stride*2 < N_vec) { + sum += safe_kl_term(p2.x, lq2.x) + safe_kl_term(p2.y, lq2.y); + sum += safe_kl_term(p2.z, lq2.z) + safe_kl_term(p2.w, lq2.w); + } + if (i + stride*3 < N_vec) { + sum += safe_kl_term(p3.x, lq3.x) + safe_kl_term(p3.y, lq3.y); + sum += safe_kl_term(p3.z, lq3.z) + safe_kl_term(p3.w, lq3.w); + } + } + + sum = block_reduce_sum(sum); + + if (threadIdx.x == 0) { + output_sum[blockIdx.x] = sum; + } + } + + torch::Tensor kldiv_forward_cuda(torch::Tensor input_logits, torch::Tensor target_prob) { + TORCH_CHECK(input_logits.is_cuda() && target_prob.is_cuda(), "Inputs must be CUDA tensors"); + + input_logits = input_logits.contiguous(); + target_prob = target_prob.contiguous(); + + int N = input_logits.numel(); + + if (N % VEC_SIZE != 0) { + TORCH_CHECK(false, "Total elements must be divisible by 4"); + } + + const int block_size = BLOCK_SIZE; + // Optimal grid size: balance between parallelism and reduction overhead + const int grid_size = min(1024, (N / VEC_SIZE + block_size - 1) / block_size); + + auto partial_sum = torch::empty({grid_size}, input_logits.options().dtype(torch::kFloat64)); + + // Choose best kernel based on problem size + if (N >= 1048576) { // >= 1M elements, use v2 (register tiling) + kldiv_kernel_v2<<>>( + input_logits.data_ptr(), + target_prob.data_ptr(), + partial_sum.data_ptr(), + N + ); + } else { // Use v1 (maximally unrolled) + kldiv_kernel_v1<<>>( + input_logits.data_ptr(), + target_prob.data_ptr(), + partial_sum.data_ptr(), + N + ); + } + + // Final reduction on device + double total = partial_sum.sum().item(); + float result = (float)(total / N); + + return torch::tensor(result, input_logits.options()); + } + """ + + self.kldiv_op = load_inline( + name="kldiv_ultra_op", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["kldiv_forward_cuda"], + extra_cuda_cflags=["-O3", "--use_fast_math", "-lineinfo", "--maxrregcount=64"], + verbose=True + ) + + def forward(self, input_logits: torch.Tensor, target_prob: torch.Tensor) -> torch.Tensor: + return self.kldiv_op.kldiv_forward_cuda(input_logits, target_prob) \ No newline at end of file diff --git a/S1/29/kldivloss_torch.py b/S1/29/kldivloss_torch.py new file mode 100644 index 0000000..73810f4 --- /dev/null +++ b/S1/29/kldivloss_torch.py @@ -0,0 +1,26 @@ +# kldivloss_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + +BATCH_SIZE = 16 +DIM = 16384 * 16 + +class Model(nn.Module): + + def forward(self, input_logits: torch.Tensor, target_prob: torch.Tensor) -> torch.Tensor: + + + return F.kl_div(input_logits, target_prob, reduction='mean') + +def get_inputs(): + + target_prob = torch.rand(BATCH_SIZE, DIM, dtype=torch.float32) + target_prob = target_prob / target_prob.sum(dim=-1, keepdim=True) + + input_logits = F.log_softmax(torch.randn(BATCH_SIZE, DIM, dtype=torch.float32), dim=-1) + + return [input_logits, target_prob] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/29/prompt.txt b/S1/29/prompt.txt new file mode 100644 index 0000000..79bcedc --- /dev/null +++ b/S1/29/prompt.txt @@ -0,0 +1,33 @@ +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: + +```python +# kldivloss_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + +BATCH_SIZE = 16 +DIM = 16384 * 16 + +class Model(nn.Module): + + def forward(self, input_logits: torch.Tensor, target_prob: torch.Tensor) -> torch.Tensor: + + + return F.kl_div(input_logits, target_prob, reduction='mean') + +def get_inputs(): + + target_prob = torch.rand(BATCH_SIZE, DIM, dtype=torch.float32) + target_prob = target_prob / target_prob.sum(dim=-1, keepdim=True) + + input_logits = F.log_softmax(torch.randn(BATCH_SIZE, DIM, dtype=torch.float32), dim=-1) + + return [input_logits, target_prob] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/29/run_code.py b/S1/29/run_code.py new file mode 100644 index 0000000..9f589ab --- /dev/null +++ b/S1/29/run_code.py @@ -0,0 +1,88 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from kldivloss_torch import Model, get_inputs, get_init_inputs +from kldivloss_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) + + # 更严格的精度检查 + abs_diff = (output_torch - output_cuda).abs() + max_diff = abs_diff.max().item() + mean_diff = abs_diff.mean().item() + + print(f"最大差异: {max_diff:.6f}") + print(f"平均差异: {mean_diff:.6f}") + + precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05) + if precision_flag: + print("✅ 精度对齐:两个模型的输出结果非常接近。") + else: + print("❌ 精度不一致!") + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量 + + # Warm up + for _ in range(100): + _ = 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA ReLU 平均执行时间: {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