Merge pull request 'finish ransac_normalize_outlier_reject #123' (#483) from gsd123/GPUCodeForces:gsd123 into main

This commit is contained in:
wawahejun 2025-12-14 22:45:03 +08:00
commit b0fadeaa4e
4 changed files with 288 additions and 0 deletions

59
S1/gsd123_#123/prompt.txt Normal file
View File

@ -0,0 +1,59 @@
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 C++ kernel for RANSACstyle outlier rejection with twostage processing
PyTorch C++/CUDA extension via load_inline
Euclidean distance computation per point pair (L2 norm across feature dimension)
Parallel reduction in shared memory for sum of distances (treebased)
Global atomic addition (atomicAdd) to accumulate sum across blocks
Normalized distancebased thresholding: reject if dist / mean_dist < threshold
Dynamic shared memory allocation for reduction scratchpad
Gridstride launch with 256 threads per block
Output binary mask (1.0 = inlier, 0.0 = outlier)
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, threshold):
super(Model, self).__init__()
self.threshold = threshold
def forward(self, src, tgt):
diff = src - tgt
dist = torch.norm(diff, p=2, dim=1)
mean_dist = dist.mean()
norm_dist = dist / (mean_dist + 1e-8)
mask = (norm_dist < self.threshold).float()
return mask
batch_size = 4096
dim = 64
def get_inputs():
src = torch.randn(batch_size, dim, device='cuda')
tgt = torch.randn(batch_size, dim, device='cuda')
return [src, tgt]
def get_init_inputs():
threshold = 1.5
return [threshold]

View File

@ -0,0 +1,120 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cmath>
__global__ void calc_stats_kernel(
const float* __restrict__ src,
const float* __restrict__ tgt,
float* __restrict__ dists,
float* __restrict__ global_sum,
int n,
int dim
) {
extern __shared__ float sdata[];
int tid = threadIdx.x;
int idx = blockIdx.x * blockDim.x + threadIdx.x;
float val = 0.0f;
if (idx < n) {
float sum_sq = 0.0f;
int offset = idx * dim;
for (int j = 0; j < dim; ++j) {
float diff = src[offset + j] - tgt[offset + j];
sum_sq += diff * diff;
}
val = sqrtf(sum_sq);
dists[idx] = val;
}
sdata[tid] = val;
__syncthreads();
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid == 0) {
atomicAdd(global_sum, sdata[0]);
}
}
__global__ void reject_kernel(
const float* __restrict__ dists,
const float* __restrict__ global_sum,
float* __restrict__ output,
int n,
float threshold
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
float mean = global_sum[0] / n;
float dist = dists[idx];
float norm_dist = dist / (mean + 1e-8f);
output[idx] = (norm_dist < threshold) ? 1.0f : 0.0f;
}
}
torch::Tensor ransac_cuda(torch::Tensor src, torch::Tensor tgt, float threshold) {
auto src_c = src.contiguous();
auto tgt_c = tgt.contiguous();
int n = src_c.size(0);
int dim = src_c.size(1);
auto dists = torch::empty({n}, src.options());
auto output = torch::empty({n}, src.options());
auto global_sum = torch::zeros({1}, src.options());
const int block_size = 256;
int num_blocks = (n + block_size - 1) / block_size;
int shared_mem = block_size * sizeof(float);
calc_stats_kernel<<<num_blocks, block_size, shared_mem>>>(
src_c.data_ptr<float>(),
tgt_c.data_ptr<float>(),
dists.data_ptr<float>(),
global_sum.data_ptr<float>(),
n,
dim
);
reject_kernel<<<num_blocks, block_size>>>(
dists.data_ptr<float>(),
global_sum.data_ptr<float>(),
output.data_ptr<float>(),
n,
threshold
);
return output;
}
"""
cpp_source = """
torch::Tensor ransac_cuda(torch::Tensor src, torch::Tensor tgt, float threshold);
"""
ransac_module = load_inline(
name="ransac_norm_opt",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["ransac_cuda"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, threshold):
super(ModelNew, self).__init__()
self.threshold = threshold
def forward(self, src, tgt):
return ransac_module.ransac_cuda(src, tgt, self.threshold)

View File

@ -0,0 +1,32 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, threshold):
super(Model, self).__init__()
self.threshold = threshold
def forward(self, src, tgt):
diff = src - tgt
dist = torch.norm(diff, p=2, dim=1)
mean_dist = dist.mean()
norm_dist = dist / (mean_dist + 1e-8)
mask = (norm_dist < self.threshold).float()
return mask
batch_size = 4096
dim = 64
def get_inputs():
src = torch.randn(batch_size, dim, device='cuda')
tgt = torch.randn(batch_size, dim, device='cuda')
return [src, tgt]
def get_init_inputs():
threshold = 1.5
return [threshold]

View File

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