diff --git a/S1/ZZZJ_#95/pairwise_kld_loss_cuda.py b/S1/ZZZJ_#95/pairwise_kld_loss_cuda.py new file mode 100644 index 00000000..3cb599fc --- /dev/null +++ b/S1/ZZZJ_#95/pairwise_kld_loss_cuda.py @@ -0,0 +1,94 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor pairwise_kld_cuda(torch::Tensor boxes1, torch::Tensor boxes2); + """ + + cuda_source = """ + #include + #include + #define BLOCK_DIM 16 + + __global__ void pairwise_kld_kernel( + const float* __restrict__ boxes1, + const float* __restrict__ boxes2, + float* __restrict__ output, + int n, int m + ) { + int col = blockIdx.x * blockDim.x + threadIdx.x; + int row = blockIdx.y * blockDim.y + threadIdx.y; + if (row >= n || col >= m) return; + + // Manual Load (5 elements) + const float* p1 = boxes1 + row * 5; + const float* p2 = boxes2 + col * 5; + + double mu1_x = p1[0], mu1_y = p1[1], w1 = p1[2], h1 = p1[3], t1 = p1[4]; + double mu2_x = p2[0], mu2_y = p2[1], w2 = p2[2], h2 = p2[3], t2 = p2[4]; + + auto get_sigma = [&](double w, double h, double t, double& xx, double& yy, double& xy) { + double c = cos(t), s = sin(t); + double w2 = w*w/4.0, h2 = h*h/4.0; + xx = c*c*w2 + s*s*h2; + yy = s*s*w2 + c*c*h2; + xy = c*s*(w2 - h2); + }; + + double s1_xx, s1_yy, s1_xy; get_sigma(w1, h1, t1, s1_xx, s1_yy, s1_xy); + double s2_xx, s2_yy, s2_xy; get_sigma(w2, h2, t2, s2_xx, s2_yy, s2_xy); + + // Inverse S2 + double det2 = s2_xx * s2_yy - s2_xy * s2_xy + 1e-7; + double inv_xx = s2_yy / det2; + double inv_yy = s2_xx / det2; + double inv_xy = -s2_xy / det2; + + // Trace(S2_inv @ S1) + double tr = (inv_xx * s1_xx + inv_xy * s1_xy) + (inv_xy * s1_xy + inv_yy * s1_yy); + + // Mahalanobis + double dx = mu2_x - mu1_x; + double dy = mu2_y - mu1_y; + double maha = dx * (inv_xx * dx + inv_xy * dy) + dy * (inv_xy * dx + inv_yy * dy); + + // Log Det + double det1 = s1_xx * s1_yy - s1_xy * s1_xy + 1e-7; + double log_det = log(det2 / det1); + + double kld = 0.5 * (tr + maha + log_det - 2.0); + output[row * m + col] = (float)(1.0 / (1.0 + kld)); + } + + torch::Tensor pairwise_kld_cuda(torch::Tensor boxes1, torch::Tensor boxes2) { + int n = boxes1.size(0); + int m = boxes2.size(0); + auto output = torch::empty({n, m}, boxes1.options()); + + dim3 block(BLOCK_DIM, BLOCK_DIM); + dim3 grid((m + BLOCK_DIM - 1) / BLOCK_DIM, (n + BLOCK_DIM - 1) / BLOCK_DIM); + + pairwise_kld_kernel<<>>(boxes1.data_ptr(), boxes2.data_ptr(), output.data_ptr(), n, m); + return output; + } + """ + + self.op = load_inline( + name="pairwise_kld_opt", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["pairwise_kld_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor: + return self.op.pairwise_kld_cuda(boxes1, boxes2) \ No newline at end of file diff --git a/S1/ZZZJ_#95/pairwise_kld_loss_torch.py b/S1/ZZZJ_#95/pairwise_kld_loss_torch.py new file mode 100644 index 00000000..9142f4f8 --- /dev/null +++ b/S1/ZZZJ_#95/pairwise_kld_loss_torch.py @@ -0,0 +1,67 @@ +import torch +import torch.nn as nn + +N = 2048 +M = 2048 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor: + # KL Divergence between two Gaussians + b1 = boxes1.unsqueeze(1) # [N, 1, 5] + b2 = boxes2.unsqueeze(0) # [1, M, 5] + + def get_params(b): + x, y, w, h, theta = b.unbind(dim=-1) + c = torch.cos(theta) + s = torch.sin(theta) + w2 = w.pow(2) / 4.0 + h2 = h.pow(2) / 4.0 + sigma_xx = c*c*w2 + s*s*h2 + sigma_yy = s*s*w2 + c*c*h2 + sigma_xy = c*s*(w2 - h2) + return x, y, sigma_xx, sigma_yy, sigma_xy + + mu1_x, mu1_y, s1_xx, s1_yy, s1_xy = get_params(b1) + mu2_x, mu2_y, s2_xx, s2_yy, s2_xy = get_params(b2) + + # KLD = 0.5 * (Tr(S2_inv @ S1) + (mu2-mu1)^T @ S2_inv @ (mu2-mu1) + ln(|S2|/|S1|) - 2) + + # 1. Inverse of S2 + det2 = s2_xx * s2_yy - s2_xy.pow(2) + 1e-7 + s2_inv_xx = s2_yy / det2 + s2_inv_yy = s2_xx / det2 + s2_inv_xy = -s2_xy / det2 + + # 2. Trace term: Tr(S2_inv @ S1) + # (inv_xx * xx + inv_xy * xy) + (inv_xy * xy + inv_yy * yy) + tr_term = (s2_inv_xx * s1_xx + s2_inv_xy * s1_xy) + (s2_inv_xy * s1_xy + s2_inv_yy * s1_yy) + + # 3. Mahalanobis term + dx = mu2_x - mu1_x + dy = mu2_y - mu1_y + mahalanobis = dx * (s2_inv_xx * dx + s2_inv_xy * dy) + dy * (s2_inv_xy * dx + s2_inv_yy * dy) + + # 4. Log Det term + det1 = s1_xx * s1_yy - s1_xy.pow(2) + 1e-7 + log_det = torch.log(det2 / det1) + + kld = 0.5 * (tr_term + mahalanobis + log_det - 2.0) + return 1 / (1 + kld) # Normalize to 0-1 + +def get_inputs(): + xy = torch.randint(0, 100, (N, 2), device='cuda').float() + wh = torch.randint(10, 50, (N, 2), device='cuda').float() + theta = torch.zeros((N, 1), device='cuda').float() + b1 = torch.cat([xy, wh, theta], dim=1) + + xy2 = torch.randint(0, 100, (M, 2), device='cuda').float() + wh2 = torch.randint(10, 50, (M, 2), device='cuda').float() + theta2 = torch.zeros((M, 1), device='cuda').float() + b2 = torch.cat([xy2, wh2, theta2], dim=1) + return [b1, b2] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#95/prompt.txt b/S1/ZZZJ_#95/prompt.txt new file mode 100644 index 00000000..66bbe5eb --- /dev/null +++ b/S1/ZZZJ_#95/prompt.txt @@ -0,0 +1,75 @@ +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 +import torch +import torch.nn as nn + +N = 2048 +M = 2048 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor: + # KL Divergence between two Gaussians + b1 = boxes1.unsqueeze(1) # [N, 1, 5] + b2 = boxes2.unsqueeze(0) # [1, M, 5] + + def get_params(b): + x, y, w, h, theta = b.unbind(dim=-1) + c = torch.cos(theta) + s = torch.sin(theta) + w2 = w.pow(2) / 4.0 + h2 = h.pow(2) / 4.0 + sigma_xx = c*c*w2 + s*s*h2 + sigma_yy = s*s*w2 + c*c*h2 + sigma_xy = c*s*(w2 - h2) + return x, y, sigma_xx, sigma_yy, sigma_xy + + mu1_x, mu1_y, s1_xx, s1_yy, s1_xy = get_params(b1) + mu2_x, mu2_y, s2_xx, s2_yy, s2_xy = get_params(b2) + + # KLD = 0.5 * (Tr(S2_inv @ S1) + (mu2-mu1)^T @ S2_inv @ (mu2-mu1) + ln(|S2|/|S1|) - 2) + + # 1. Inverse of S2 + det2 = s2_xx * s2_yy - s2_xy.pow(2) + 1e-7 + s2_inv_xx = s2_yy / det2 + s2_inv_yy = s2_xx / det2 + s2_inv_xy = -s2_xy / det2 + + # 2. Trace term: Tr(S2_inv @ S1) + # (inv_xx * xx + inv_xy * xy) + (inv_xy * xy + inv_yy * yy) + tr_term = (s2_inv_xx * s1_xx + s2_inv_xy * s1_xy) + (s2_inv_xy * s1_xy + s2_inv_yy * s1_yy) + + # 3. Mahalanobis term + dx = mu2_x - mu1_x + dy = mu2_y - mu1_y + mahalanobis = dx * (s2_inv_xx * dx + s2_inv_xy * dy) + dy * (s2_inv_xy * dx + s2_inv_yy * dy) + + # 4. Log Det term + det1 = s1_xx * s1_yy - s1_xy.pow(2) + 1e-7 + log_det = torch.log(det2 / det1) + + kld = 0.5 * (tr_term + mahalanobis + log_det - 2.0) + return 1 / (1 + kld) # Normalize to 0-1 + +def get_inputs(): + xy = torch.randint(0, 100, (N, 2), device='cuda').float() + wh = torch.randint(10, 50, (N, 2), device='cuda').float() + theta = torch.zeros((N, 1), device='cuda').float() + b1 = torch.cat([xy, wh, theta], dim=1) + + xy2 = torch.randint(0, 100, (M, 2), device='cuda').float() + wh2 = torch.randint(10, 50, (M, 2), device='cuda').float() + theta2 = torch.zeros((M, 1), device='cuda').float() + b2 = torch.cat([xy2, wh2, theta2], dim=1) + return [b1, b2] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#95/run_code.py b/S1/ZZZJ_#95/run_code.py new file mode 100644 index 00000000..eff03ec2 --- /dev/null +++ b/S1/ZZZJ_#95/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from pairwise_kld_loss_torch import Model,get_inputs,get_init_inputs +from pairwise_kld_loss_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