Compare commits
1 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
d069615b87 |
|
|
@ -0,0 +1,58 @@
|
|||
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
|
||||
|
||||
Sparse matrix addition to dense bias (COO format)
|
||||
|
||||
Atomic addition (atomicAdd) for thread-safe sparse accumulation
|
||||
|
||||
Index boundary checking for safety
|
||||
|
||||
Fixed block size (256 threads) with dynamic grid sizing
|
||||
|
||||
Contiguous tensor handling for memory coalescing
|
||||
|
||||
Sparse tensor access via _indices() and _values() methods
|
||||
|
||||
In-place-like operation with bias cloning
|
||||
|
||||
Zero non-zero element handling guard
|
||||
|
||||
Two-dimensional indexing with row/col offset calculation
|
||||
|
||||
|
||||
|
||||
|
||||
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, bias):
|
||||
super(Model, self).__init__()
|
||||
self.bias = nn.Parameter(bias)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.bias + x
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 1024
|
||||
sparsity = 0.9
|
||||
|
||||
|
||||
def get_inputs():
|
||||
nnz = int(batch_size * dim * (1 - sparsity))
|
||||
row_indices = torch.randint(0, batch_size, (1, nnz))
|
||||
col_indices = torch.randint(0, dim, (1, nnz))
|
||||
indices = torch.cat([row_indices, col_indices], dim=0)
|
||||
values = torch.randn(nnz)
|
||||
x = torch.sparse_coo_tensor(indices, values, (batch_size, dim))
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
bias = torch.randn(batch_size, dim)
|
||||
return [bias]
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from sparseadd_torch import Model, get_inputs, get_init_inputs
|
||||
from sparseadd_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,78 @@
|
|||
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>
|
||||
|
||||
__global__ void sparse_add_kernel(
|
||||
const int64_t* __restrict__ indices,
|
||||
const float* __restrict__ values,
|
||||
float* __restrict__ output,
|
||||
int nnz,
|
||||
int rows,
|
||||
int cols
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx < nnz) {
|
||||
int row = indices[idx];
|
||||
int col = indices[nnz + idx];
|
||||
|
||||
if (row >= 0 && row < rows && col >= 0 && col < cols) {
|
||||
atomicAdd(&output[row * cols + col], values[idx]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor sparse_add_cuda(torch::Tensor indices, torch::Tensor values, torch::Tensor bias) {
|
||||
auto indices_c = indices.contiguous();
|
||||
auto values_c = values.contiguous();
|
||||
auto bias_c = bias.contiguous();
|
||||
|
||||
int nnz = values_c.size(0);
|
||||
int rows = bias_c.size(0);
|
||||
int cols = bias_c.size(1);
|
||||
|
||||
auto output = bias_c.clone();
|
||||
|
||||
if (nnz > 0) {
|
||||
const int block_size = 256;
|
||||
int num_blocks = (nnz + block_size - 1) / block_size;
|
||||
|
||||
sparse_add_kernel<<<num_blocks, block_size>>>(
|
||||
indices_c.data_ptr<int64_t>(),
|
||||
values_c.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
nnz,
|
||||
rows,
|
||||
cols
|
||||
);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor sparse_add_cuda(torch::Tensor indices, torch::Tensor values, torch::Tensor bias);
|
||||
"""
|
||||
|
||||
sparse_add_module = load_inline(
|
||||
name="sparse_add_safe",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["sparse_add_cuda"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, bias):
|
||||
super(ModelNew, self).__init__()
|
||||
self.bias = nn.Parameter(bias)
|
||||
|
||||
def forward(self, x):
|
||||
indices = x._indices()
|
||||
values = x._values()
|
||||
return sparse_add_module.sparse_add_cuda(indices, values, self.bias)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, bias):
|
||||
super(Model, self).__init__()
|
||||
self.bias = nn.Parameter(bias)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.bias + x
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 1024
|
||||
sparsity = 0.9
|
||||
|
||||
|
||||
def get_inputs():
|
||||
nnz = int(batch_size * dim * (1 - sparsity))
|
||||
row_indices = torch.randint(0, batch_size, (1, nnz))
|
||||
col_indices = torch.randint(0, dim, (1, nnz))
|
||||
indices = torch.cat([row_indices, col_indices], dim=0)
|
||||
values = torch.randn(nnz)
|
||||
x = torch.sparse_coo_tensor(indices, values, (batch_size, dim))
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
bias = torch.randn(batch_size, dim)
|
||||
return [bias]
|
||||
Loading…
Reference in New Issue