Merge pull request 'finish pairwisedistanc #38' (#66) from ZZZJ/GPUCodeForces:pairwisedistance into main

This commit is contained in:
Kuohais 2025-11-13 09:46:47 +08:00
commit 175d801494
4 changed files with 272 additions and 0 deletions

View File

@ -0,0 +1,125 @@
# pairwisedistance_cuda.py
import torch
from torch.utils.cpp_extension import load_inline
from pairwisedistance_torch import BATCH_SIZE, FEATURE_DIM, P_NORM # 导入维度常量
EPS = 1e-6
class ModelNew(torch.nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor pdist_forward_cuda(torch::Tensor x1, torch::Tensor x2, float eps_val);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <cmath>
#include <float.h>
#define BLOCK_SIZE 256
#define WARP_SIZE 32
#define FEATURE_DIM_VAL {FEATURE_DIM}
__device__ __forceinline__ float warp_reduce_sum(float val) {{
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {{
val += __shfl_down_sync(0xffffffff, val, offset);
}}
return val;
}}
__global__ void pdist_fused_kernel(
const float* __restrict__ x1,
const float* __restrict__ x2,
float* __restrict__ y_out,
int num_batches,
int feature_dim,
float eps_val
) {{
__shared__ float s_data[BLOCK_SIZE];
int batch_idx = blockIdx.x;
if (batch_idx >= num_batches) return;
const float* a_ptr = x1 + batch_idx * feature_dim;
const float* b_ptr = x2 + batch_idx * feature_dim;
float thread_diff_sq_sum = 0.0f;
for (int i = threadIdx.x; i < feature_dim; i += blockDim.x) {{
float a_val = a_ptr[i];
float b_val = b_ptr[i];
float diff = a_val - b_val;
// L2 Norm: |diff|^2
thread_diff_sq_sum += diff * diff;
}}
thread_diff_sq_sum = warp_reduce_sum(thread_diff_sq_sum);
int warp_id = threadIdx.x / WARP_SIZE;
int lane_id = threadIdx.x % WARP_SIZE;
int num_warps = blockDim.x / WARP_SIZE;
if (lane_id == 0) {{
s_data[warp_id] = thread_diff_sq_sum;
}}
__syncthreads();
if (threadIdx.x < num_warps) {
float total_diff_sq_sum = warp_reduce_sum(s_data[threadIdx.x]);
if (threadIdx.x == 0) {
float result = sqrtf(total_diff_sq_sum + eps_val);
y_out[batch_idx] = result;
}
}
}}
torch::Tensor pdist_forward_cuda(torch::Tensor x1, torch::Tensor x2, float eps_val) {
TORCH_CHECK(x1.is_cuda(), "Input must be a CUDA tensor");
x1 = x1.contiguous();
x2 = x2.contiguous();
int num_batches = x1.size(0);
int feature_dim = x1.size(1);
auto output = torch::empty({num_batches}, x1.options());
const int block_size = BLOCK_SIZE;
const int grid_size = num_batches;
size_t shared_mem_size = (block_size / WARP_SIZE) * sizeof(float);
pdist_fused_kernel<<<grid_size, block_size, shared_mem_size>>>(
x1.data_ptr<float>(),
x2.data_ptr<float>(),
output.data_ptr<float>(),
num_batches,
feature_dim,
eps_val
);
return output;
}
"""
self.pdist_op = load_inline(
name="pdist_fused_op_safest",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["pdist_forward_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=True
)
def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
return self.pdist_op.pdist_forward_cuda(x1, x2, EPS)

View File

@ -0,0 +1,26 @@
# pairwisedistance_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 4096
FEATURE_DIM = 1024
P_NORM = 2
class Model(nn.Module):
def __init__(self):
super().__init__()
self.criterion = nn.PairwiseDistance(p=P_NORM, eps=1e-6, keepdim=False)
def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
return self.criterion(x1, x2)
def get_inputs():
x1 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
x2 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
return [x1, x2]
def get_init_inputs():
return []

33
S1/38/prompt.txt Normal file
View File

@ -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
pairwisedistance.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 4096
FEATURE_DIM = 1024
P_NORM = 2
class Model(nn.Module):
def __init__(self):
super().__init__()
self.criterion = nn.PairwiseDistance(p=P_NORM, eps=1e-6, keepdim=False)
def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
return self.criterion(x1, x2)
def get_inputs():
x1 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
x2 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
return [x1, x2]
def get_init_inputs():
return []

88
S1/38/run_code.py Normal file
View File

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