forked from ccf-ai-infra/GPUCodeForces
fixes ScatterMin #28
This commit is contained in:
parent
cc73715277
commit
aaee488b50
|
|
@ -0,0 +1,54 @@
|
|||
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.dim_size = 10000
|
||||
|
||||
def forward(self, src: torch.Tensor, index: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
src: [N, C]
|
||||
index: [N]
|
||||
Output: [dim_size, C]
|
||||
"""
|
||||
src = src.float()
|
||||
N, C = src.shape
|
||||
|
||||
# 1. 初始化为正无穷 (+inf)
|
||||
# 这样任何有效值都会比初始值小,从而更新成功
|
||||
out = torch.full((self.dim_size, C), float('inf'), dtype=src.dtype, device=src.device)
|
||||
|
||||
# 2. PyTorch 的 index_reduce_ ('amin')
|
||||
# out[index[i]] = min(out[index[i]], src[i])
|
||||
out.index_reduce_(0, index, src, reduce='amin', include_self=True)
|
||||
|
||||
# 3. 处理未命中的位置
|
||||
# 为了与 CUDA 逻辑一致,我们保留 inf,或者你可以 mask 掉
|
||||
# 实际使用中通常会把 inf 替换为一个极大值或者 0 (如果逻辑允许)
|
||||
# 这里为了验证精度,保持 inf 不变
|
||||
return out
|
||||
|
||||
# 模拟大规模数据
|
||||
N = 1024 * 128
|
||||
C = 128
|
||||
dim_size = 10000
|
||||
|
||||
def get_inputs():
|
||||
# Min 操作数值稳定,直接用 randn
|
||||
src = torch.randn(N, C).cuda()
|
||||
index = torch.randint(0, dim_size, (N,)).cuda().long()
|
||||
return [src, index]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from scatter_min_torch import Model,get_inputs,get_init_inputs
|
||||
from scatter_min_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,145 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
scatter_min_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
|
||||
__device__ __forceinline__ unsigned int float_to_ordered_uint(float f) {
|
||||
unsigned int u = __float_as_uint(f);
|
||||
unsigned int mask = -((int)(u >> 31)) | 0x80000000;
|
||||
return u ^ mask;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float ordered_uint_to_float(unsigned int u) {
|
||||
unsigned int mask = ((u & 0x80000000) == 0) ? 0xFFFFFFFF : 0x80000000;
|
||||
return __uint_as_float(u ^ mask);
|
||||
}
|
||||
|
||||
|
||||
__global__ void scatter_min_uint_kernel(
|
||||
const float* __restrict__ src,
|
||||
const long* __restrict__ index,
|
||||
unsigned int* __restrict__ out_int,
|
||||
int N,
|
||||
int C)
|
||||
{
|
||||
int vec_C = C / 4;
|
||||
int total_vecs = N * vec_C;
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx < total_vecs) {
|
||||
int n = idx / vec_C;
|
||||
int c_vec = idx % vec_C;
|
||||
|
||||
long target_row = index[n];
|
||||
|
||||
const float4* src_ptr = reinterpret_cast<const float4*>(src);
|
||||
float4 val = src_ptr[idx];
|
||||
|
||||
int out_offset = target_row * C + c_vec * 4;
|
||||
|
||||
atomicMin(&out_int[out_offset + 0], float_to_ordered_uint(val.x));
|
||||
atomicMin(&out_int[out_offset + 1], float_to_ordered_uint(val.y));
|
||||
atomicMin(&out_int[out_offset + 2], float_to_ordered_uint(val.z));
|
||||
atomicMin(&out_int[out_offset + 3], float_to_ordered_uint(val.w));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
__global__ void decode_uint_to_float_kernel(
|
||||
unsigned int* __restrict__ data,
|
||||
int total_elements)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int vec_len = total_elements / 4;
|
||||
|
||||
if (idx < vec_len) {
|
||||
uint4* ptr = reinterpret_cast<uint4*>(data);
|
||||
uint4 u_val = ptr[idx];
|
||||
|
||||
float4 f_val;
|
||||
|
||||
|
||||
|
||||
if (u_val.x == 0xFFFFFFFF) f_val.x = __int_as_float(0x7F800000);
|
||||
else f_val.x = ordered_uint_to_float(u_val.x);
|
||||
|
||||
if (u_val.y == 0xFFFFFFFF) f_val.y = __int_as_float(0x7F800000);
|
||||
else f_val.y = ordered_uint_to_float(u_val.y);
|
||||
|
||||
if (u_val.z == 0xFFFFFFFF) f_val.z = __int_as_float(0x7F800000);
|
||||
else f_val.z = ordered_uint_to_float(u_val.z);
|
||||
|
||||
if (u_val.w == 0xFFFFFFFF) f_val.w = __int_as_float(0x7F800000);
|
||||
else f_val.w = ordered_uint_to_float(u_val.w);
|
||||
|
||||
float4* f_ptr = reinterpret_cast<float4*>(data);
|
||||
f_ptr[idx] = f_val;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor scatter_min_cuda(torch::Tensor src, torch::Tensor index, int dim_size) {
|
||||
int N = src.size(0);
|
||||
int C = src.size(1);
|
||||
|
||||
|
||||
auto out_int = torch::full({dim_size, C}, -1, torch::dtype(torch::kInt32).device(src.device()));
|
||||
|
||||
if (C % 4 == 0) {
|
||||
int vec_C = C / 4;
|
||||
int total_threads = N * vec_C;
|
||||
const int block = 256;
|
||||
const int grid = (total_threads + block - 1) / block;
|
||||
|
||||
scatter_min_uint_kernel<<<grid, block>>>(
|
||||
src.data_ptr<float>(),
|
||||
index.data_ptr<long>(),
|
||||
reinterpret_cast<unsigned int*>(out_int.data_ptr<int>()),
|
||||
N, C
|
||||
);
|
||||
|
||||
// Decode
|
||||
int total_out_elements = dim_size * C;
|
||||
int decode_vecs = total_out_elements / 4;
|
||||
const int grid_decode = (decode_vecs + block - 1) / block;
|
||||
|
||||
decode_uint_to_float_kernel<<<grid_decode, block>>>(
|
||||
reinterpret_cast<unsigned int*>(out_int.data_ptr<int>()),
|
||||
total_out_elements
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return out_int;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor scatter_min_cuda(torch::Tensor src, torch::Tensor index, int dim_size);"
|
||||
|
||||
scatter_min_module = load_inline(
|
||||
name="scatter_min_extension_v2",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=scatter_min_source,
|
||||
functions=["scatter_min_cuda"],
|
||||
verbose=True,
|
||||
with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.dim_size = 10000
|
||||
self.cuda_op = scatter_min_module
|
||||
|
||||
def forward(self, src, index):
|
||||
# 1. 确保输入连续
|
||||
src_contig = src.contiguous()
|
||||
index_contig = index.contiguous()
|
||||
|
||||
# 2. 调用 CUDA
|
||||
out_int = self.cuda_op.scatter_min_cuda(src_contig, index_contig, self.dim_size)
|
||||
|
||||
# 3. Python 端 View 回 Float32
|
||||
return out_int.view(torch.float32)
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
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.dim_size = 10000
|
||||
|
||||
def forward(self, src: torch.Tensor, index: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
src: [N, C]
|
||||
index: [N]
|
||||
Output: [dim_size, C]
|
||||
"""
|
||||
src = src.float()
|
||||
N, C = src.shape
|
||||
|
||||
# 1. 初始化为正无穷 (+inf)
|
||||
# 这样任何有效值都会比初始值小,从而更新成功
|
||||
out = torch.full((self.dim_size, C), float('inf'), dtype=src.dtype, device=src.device)
|
||||
|
||||
# 2. PyTorch 的 index_reduce_ ('amin')
|
||||
# out[index[i]] = min(out[index[i]], src[i])
|
||||
out.index_reduce_(0, index, src, reduce='amin', include_self=True)
|
||||
|
||||
# 3. 处理未命中的位置
|
||||
# 为了与 CUDA 逻辑一致,我们保留 inf,或者你可以 mask 掉
|
||||
# 实际使用中通常会把 inf 替换为一个极大值或者 0 (如果逻辑允许)
|
||||
# 这里为了验证精度,保持 inf 不变
|
||||
return out
|
||||
|
||||
# 模拟大规模数据
|
||||
N = 1024 * 128
|
||||
C = 128
|
||||
dim_size = 10000
|
||||
|
||||
def get_inputs():
|
||||
# Min 操作数值稳定,直接用 randn
|
||||
src = torch.randn(N, C).cuda()
|
||||
index = torch.randint(0, dim_size, (N,)).cuda().long()
|
||||
return [src, index]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
Loading…
Reference in New Issue