forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish Lodget #167' (#890) from ZZZJ/GPUCodeForces:Lodget into main
This commit is contained in:
commit
c55e5ecb6a
|
|
@ -0,0 +1,129 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
logdet_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define N 8
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// Device Function: In-Register Cholesky Decomposition
|
||||
// Computes LogDet directly
|
||||
// ---------------------------------------------------------
|
||||
__device__ __forceinline__ float compute_logdet_8x8(const float* mat_in) {
|
||||
// 1. Load Matrix into Registers
|
||||
float A[N][N];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < N; ++i) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < N; ++j) {
|
||||
A[i][j] = mat_in[i * N + j];
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Cholesky Decomposition (L * L^T = A)
|
||||
// We only need diagonal elements L_ii to compute LogDet
|
||||
// In-place update: A will store L (lower triangular)
|
||||
|
||||
double logdet_sum = 0.0;
|
||||
|
||||
// Unrolled Cholesky
|
||||
#pragma unroll
|
||||
for (int k = 0; k < N; ++k) {
|
||||
|
||||
// Compute L_kk
|
||||
float diag_val = A[k][k];
|
||||
|
||||
// diag_val -= sum(L_kj ^ 2) for j < k
|
||||
for (int j = 0; j < k; ++j) {
|
||||
float val = A[k][j];
|
||||
diag_val -= val * val;
|
||||
}
|
||||
|
||||
// Check Positive Definite
|
||||
if (diag_val <= 0.0f) return -1e9f; // Error case (should not happen for SPD)
|
||||
|
||||
float L_kk = sqrtf(diag_val);
|
||||
A[k][k] = L_kk;
|
||||
|
||||
// Accumulate LogDet: 2 * sum(ln(L_ii))
|
||||
logdet_sum += log((double)L_kk);
|
||||
|
||||
// Compute L_ik for i > k
|
||||
float inv_Lkk = 1.0f / L_kk;
|
||||
|
||||
for (int i = k + 1; i < N; ++i) {
|
||||
float val = A[i][k];
|
||||
|
||||
// val -= sum(L_ij * L_kj) for j < k
|
||||
for (int j = 0; j < k; ++j) {
|
||||
val -= A[i][j] * A[k][j];
|
||||
}
|
||||
|
||||
A[i][k] = val * inv_Lkk;
|
||||
}
|
||||
}
|
||||
|
||||
return (float)(2.0 * logdet_sum);
|
||||
}
|
||||
|
||||
__global__ void batched_logdet_8x8_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int batch_size)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx < batch_size) {
|
||||
// Point to the current matrix
|
||||
const float* mat_ptr = input + idx * (N * N);
|
||||
|
||||
// Compute
|
||||
float res = compute_logdet_8x8(mat_ptr);
|
||||
|
||||
// Write Output
|
||||
output[idx] = res;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor logdet_cuda(torch::Tensor input) {
|
||||
int B = input.size(0);
|
||||
// Input check: input.size(1) == 8 && input.size(2) == 8
|
||||
|
||||
auto output = torch::empty({B}, input.options());
|
||||
|
||||
const int block = 256;
|
||||
const int grid = (B + block - 1) / block;
|
||||
|
||||
batched_logdet_8x8_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
B
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor logdet_cuda(torch::Tensor input);"
|
||||
|
||||
logdet_module = load_inline(
|
||||
name="logdet_extension",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=logdet_source,
|
||||
functions=["logdet_cuda"],
|
||||
verbose=True,
|
||||
with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.cuda_op = logdet_module
|
||||
|
||||
def forward(self, x):
|
||||
# 确保输入连续
|
||||
return self.cuda_op.logdet_cuda(x.contiguous())
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
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__()
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.logdet(x)
|
||||
|
||||
B = 1024 * 128
|
||||
N = 8
|
||||
|
||||
def get_inputs():
|
||||
Q = torch.randn(B, N, N, device='cuda', dtype=torch.float32)
|
||||
eye = torch.eye(N, device='cuda').unsqueeze(0)
|
||||
|
||||
x = torch.matmul(Q, Q.transpose(1, 2)) + eye * 0.1
|
||||
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
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__()
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.logdet(x)
|
||||
|
||||
B = 1024 * 128
|
||||
N = 8
|
||||
|
||||
def get_inputs():
|
||||
Q = torch.randn(B, N, N, device='cuda', dtype=torch.float32)
|
||||
eye = torch.eye(N, device='cuda').unsqueeze(0)
|
||||
|
||||
x = torch.matmul(Q, Q.transpose(1, 2)) + eye * 0.1
|
||||
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from logdet_torch import Model,get_inputs,get_init_inputs
|
||||
from logdet_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()
|
||||
Loading…
Reference in New Issue