forked from ccf-ai-infra/GPUCodeForces
fixes VoxelMean #159
This commit is contained in:
parent
cc73715277
commit
f5c6f21460
|
|
@ -0,0 +1,38 @@
|
|||
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
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.num_voxels = 40000
|
||||
|
||||
def forward(self, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
|
||||
N, C = features.shape
|
||||
|
||||
sum_features = torch.zeros((self.num_voxels, C), dtype=features.dtype, device=features.device)
|
||||
sum_features.index_add_(0, indices, features)
|
||||
|
||||
counts = torch.bincount(indices, minlength=self.num_voxels).float().unsqueeze(-1)
|
||||
counts = torch.clamp(counts, min=1.0)
|
||||
|
||||
return sum_features / counts
|
||||
|
||||
N = 200000
|
||||
C = 64
|
||||
|
||||
def get_inputs():
|
||||
features = torch.randint(-50, 50, (N, C), device='cuda').float()
|
||||
indices = torch.randint(0, 40000, (N,), device='cuda').long()
|
||||
return [features, indices]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from voxel_mean_torch import Model,get_inputs,get_init_inputs
|
||||
from voxel_mean_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()
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
__global__ void voxel_sum_kernel(
|
||||
const float* __restrict__ features,
|
||||
const long* __restrict__ indices,
|
||||
float* __restrict__ out_sum,
|
||||
int N, int C)
|
||||
{
|
||||
int vec_c = C / 4;
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int total_threads = N * vec_c;
|
||||
|
||||
if (idx < total_threads) {
|
||||
int n = idx / vec_c;
|
||||
int c = idx % vec_c;
|
||||
|
||||
long voxel_idx = indices[n];
|
||||
|
||||
const float4* in_ptr = reinterpret_cast<const float4*>(features);
|
||||
float4 val = in_ptr[idx];
|
||||
|
||||
long out_offset = voxel_idx * C + c * 4;
|
||||
|
||||
atomicAdd(&out_sum[out_offset + 0], val.x);
|
||||
atomicAdd(&out_sum[out_offset + 1], val.y);
|
||||
atomicAdd(&out_sum[out_offset + 2], val.z);
|
||||
atomicAdd(&out_sum[out_offset + 3], val.w);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void voxel_count_kernel(
|
||||
const long* __restrict__ indices,
|
||||
float* __restrict__ out_counts,
|
||||
int N)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx < N) {
|
||||
long voxel_idx = indices[idx];
|
||||
atomicAdd(&out_counts[voxel_idx], 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void voxel_div_kernel(
|
||||
float* __restrict__ out_sum,
|
||||
const float* __restrict__ out_counts,
|
||||
int total_elements,
|
||||
int C)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int vec_len = total_elements / 4;
|
||||
|
||||
if (idx < vec_len) {
|
||||
int voxel_idx = idx / (C / 4);
|
||||
|
||||
float cnt = out_counts[voxel_idx];
|
||||
if (cnt < 1.0f) cnt = 1.0f;
|
||||
float inv_cnt = 1.0f / cnt;
|
||||
|
||||
float4* out_ptr = reinterpret_cast<float4*>(out_sum);
|
||||
float4 val = out_ptr[idx];
|
||||
|
||||
val.x *= inv_cnt;
|
||||
val.y *= inv_cnt;
|
||||
val.z *= inv_cnt;
|
||||
val.w *= inv_cnt;
|
||||
|
||||
out_ptr[idx] = val;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor voxel_mean_cuda(torch::Tensor features, torch::Tensor indices, int num_voxels) {
|
||||
int N = features.size(0);
|
||||
int C = features.size(1);
|
||||
|
||||
auto out_sum = torch::zeros({num_voxels, C}, features.options());
|
||||
auto out_counts = torch::zeros({num_voxels}, features.options());
|
||||
|
||||
if (C % 4 == 0) {
|
||||
const int block = 256;
|
||||
|
||||
int vec_c = C / 4;
|
||||
int total_sum_threads = N * vec_c;
|
||||
int grid_sum = (total_sum_threads + block - 1) / block;
|
||||
|
||||
voxel_sum_kernel<<<grid_sum, block>>>(
|
||||
features.data_ptr<float>(),
|
||||
indices.data_ptr<long>(),
|
||||
out_sum.data_ptr<float>(),
|
||||
N, C
|
||||
);
|
||||
|
||||
int grid_count = (N + block - 1) / block;
|
||||
voxel_count_kernel<<<grid_count, block>>>(
|
||||
indices.data_ptr<long>(),
|
||||
out_counts.data_ptr<float>(),
|
||||
N
|
||||
);
|
||||
|
||||
int total_out = num_voxels * C;
|
||||
int vec_out = total_out / 4;
|
||||
int grid_div = (vec_out + block - 1) / block;
|
||||
|
||||
voxel_div_kernel<<<grid_div, block>>>(
|
||||
out_sum.data_ptr<float>(),
|
||||
out_counts.data_ptr<float>(),
|
||||
total_out, C
|
||||
);
|
||||
}
|
||||
|
||||
return out_sum;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor voxel_mean_cuda(torch::Tensor features, torch::Tensor indices, int num_voxels);"
|
||||
|
||||
module = load_inline(
|
||||
name="voxel_mean_extension",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=source,
|
||||
functions=["voxel_mean_cuda"],
|
||||
verbose=True,
|
||||
with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.num_voxels = 40000
|
||||
self.op = module
|
||||
|
||||
def forward(self, features, indices):
|
||||
return self.op.voxel_mean_cuda(features.contiguous(), indices.contiguous(), self.num_voxels)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.num_voxels = 40000
|
||||
|
||||
def forward(self, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
|
||||
N, C = features.shape
|
||||
|
||||
sum_features = torch.zeros((self.num_voxels, C), dtype=features.dtype, device=features.device)
|
||||
sum_features.index_add_(0, indices, features)
|
||||
|
||||
counts = torch.bincount(indices, minlength=self.num_voxels).float().unsqueeze(-1)
|
||||
counts = torch.clamp(counts, min=1.0)
|
||||
|
||||
return sum_features / counts
|
||||
|
||||
N = 200000
|
||||
C = 64
|
||||
|
||||
def get_inputs():
|
||||
features = torch.randint(-50, 50, (N, C), device='cuda').float()
|
||||
indices = torch.randint(0, 40000, (N,), device='cuda').long()
|
||||
return [features, indices]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
Loading…
Reference in New Issue