From 912c8a55407e2c442b1d085ad057e93ee87e446d Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Tue, 9 Dec 2025 11:30:02 +0800 Subject: [PATCH] finish MeshEdgeLoss #116 --- S1/gsd123_#116/MeshEdgeLoss_cuda.py | 86 ++++++++++++++++++++++++++++ S1/gsd123_#116/MeshEdgeLoss_torch.py | 23 ++++++++ S1/gsd123_#116/prompt.txt | 52 +++++++++++++++++ S1/gsd123_#116/run_code.py | 77 +++++++++++++++++++++++++ 4 files changed, 238 insertions(+) create mode 100644 S1/gsd123_#116/MeshEdgeLoss_cuda.py create mode 100644 S1/gsd123_#116/MeshEdgeLoss_torch.py create mode 100644 S1/gsd123_#116/prompt.txt create mode 100644 S1/gsd123_#116/run_code.py diff --git a/S1/gsd123_#116/MeshEdgeLoss_cuda.py b/S1/gsd123_#116/MeshEdgeLoss_cuda.py new file mode 100644 index 00000000..fe9183f9 --- /dev/null +++ b/S1/gsd123_#116/MeshEdgeLoss_cuda.py @@ -0,0 +1,86 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__global__ void edge_loss_kernel( + const float* __restrict__ vertices, + const int64_t* __restrict__ edges, + float* __restrict__ out, + int batch_size, + int num_vertices, + int num_edges +) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < batch_size * num_edges) { + int b = idx / num_edges; + int e = idx % num_edges; + + int64_t idx1 = edges[e * 2]; + int64_t idx2 = edges[e * 2 + 1]; + + int ptr1 = b * num_vertices * 3 + idx1 * 3; + int ptr2 = b * num_vertices * 3 + idx2 * 3; + + float x1 = vertices[ptr1]; + float y1 = vertices[ptr1 + 1]; + float z1 = vertices[ptr1 + 2]; + + float x2 = vertices[ptr2]; + float y2 = vertices[ptr2 + 1]; + float z2 = vertices[ptr2 + 2]; + + float dx = x1 - x2; + float dy = y1 - y2; + float dz = z1 - z2; + + out[idx] = dx * dx + dy * dy + dz * dz; + } +} + +torch::Tensor edge_loss_cuda(torch::Tensor vertices, torch::Tensor edges) { + int batch_size = vertices.size(0); + int num_vertices = vertices.size(1); + int num_edges = edges.size(0); + + auto out = at::empty({(long)batch_size, (long)num_edges}, vertices.options()); + + int total_threads = batch_size * num_edges; + int threads = 256; + int blocks = (total_threads + threads - 1) / threads; + + edge_loss_kernel<<>>( + vertices.data_ptr(), + edges.data_ptr(), + out.data_ptr(), + batch_size, + num_vertices, + num_edges + ); + + return out.mean(); +} +""" + +cpp_source = """ +torch::Tensor edge_loss_cuda(torch::Tensor vertices, torch::Tensor edges); +""" + +edge_loss = load_inline( + name="edge_loss", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["edge_loss_cuda"], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self): + super(ModelNew, self).__init__() + + def forward(self, vertices, edges): + return edge_loss.edge_loss_cuda(vertices, edges) \ No newline at end of file diff --git a/S1/gsd123_#116/MeshEdgeLoss_torch.py b/S1/gsd123_#116/MeshEdgeLoss_torch.py new file mode 100644 index 00000000..e8cea9dd --- /dev/null +++ b/S1/gsd123_#116/MeshEdgeLoss_torch.py @@ -0,0 +1,23 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, vertices, edges): + v1 = vertices[:, edges[:, 0], :] + v2 = vertices[:, edges[:, 1], :] + return torch.mean(torch.sum((v1 - v2) ** 2, dim=2)) + +batch_size = 16 +num_vertices = 1024 +num_edges = 3000 + +def get_inputs(): + vertices = torch.randn(batch_size, num_vertices, 3, requires_grad=True) + edges = torch.randint(0, num_vertices, (num_edges, 2)).long() + return [vertices, edges] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#116/prompt.txt b/S1/gsd123_#116/prompt.txt new file mode 100644 index 00000000..d6c93585 --- /dev/null +++ b/S1/gsd123_#116/prompt.txt @@ -0,0 +1,52 @@ +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. +Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline + +Mesh edge length loss computation (squared Euclidean distance between connected vertices) + +Edge list representation with pair-wise vertex indices + +3D coordinate difference calculation (x, y, z) + +Element-wise parallelization across batch×edges + +Fixed block size (256 threads) with dynamic grid sizing + +Contiguous tensor handling for memory coalescing + +Batch-aware indexing for vertex access + +Mean reduction across all edges and batches + +Geometry regularization for mesh smoothness + + + + + + +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 + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, vertices, edges): + v1 = vertices[:, edges[:, 0], :] + v2 = vertices[:, edges[:, 1], :] + return torch.mean(torch.sum((v1 - v2) ** 2, dim=2)) + +batch_size = 16 +num_vertices = 1024 +num_edges = 3000 + +def get_inputs(): + vertices = torch.randn(batch_size, num_vertices, 3, requires_grad=True) + edges = torch.randint(0, num_vertices, (num_edges, 2)).long() + return [vertices, edges] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#116/run_code.py b/S1/gsd123_#116/run_code.py new file mode 100644 index 00000000..d6365edd --- /dev/null +++ b/S1/gsd123_#116/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from MeshEdgeLoss_torch import Model, get_inputs, get_init_inputs +from MeshEdgeLoss_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