forked from ccf-ai-infra/GPUCodeForces
finish mahalanobis_groupnorm #158
This commit is contained in:
parent
e8d83740df
commit
22bba67f80
|
|
@ -0,0 +1,104 @@
|
|||
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>
|
||||
#include <math.h>
|
||||
|
||||
__inline__ __device__ float warp_reduce(float val) {
|
||||
for (int offset = 16; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
return val;
|
||||
}
|
||||
|
||||
__global__ void mahalanobis_log_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ mean,
|
||||
const float* __restrict__ precision,
|
||||
float* __restrict__ y,
|
||||
int batch_size,
|
||||
int width)
|
||||
{
|
||||
int row = blockIdx.x;
|
||||
int tid = threadIdx.x;
|
||||
|
||||
if (row >= batch_size) return;
|
||||
|
||||
extern __shared__ float s_mem[];
|
||||
float* s_diff = s_mem;
|
||||
float* s_prec = s_mem + width;
|
||||
|
||||
if (tid < width) {
|
||||
float val = x[row * width + tid];
|
||||
float m = mean[tid];
|
||||
s_diff[tid] = val - m;
|
||||
}
|
||||
|
||||
for (int i = 0; i < width; ++i) {
|
||||
s_prec[i * width + tid] = precision[i * width + tid];
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
float diff_val = s_diff[tid];
|
||||
float mat_vec_val = 0.0f;
|
||||
|
||||
for (int i = 0; i < width; ++i) {
|
||||
float p = s_prec[i * width + tid];
|
||||
mat_vec_val += s_diff[i] * p;
|
||||
}
|
||||
|
||||
float term = mat_vec_val * diff_val;
|
||||
float mah_sq = warp_reduce(term);
|
||||
|
||||
if (tid == 0) {
|
||||
float dist = sqrtf(fabsf(mah_sq));
|
||||
y[row] = logf(dist);
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor launch_mahalanobis_log(torch::Tensor x, torch::Tensor mean, torch::Tensor precision) {
|
||||
auto batch_size = x.size(0);
|
||||
auto width = x.size(1);
|
||||
auto y = torch::empty({batch_size}, x.options());
|
||||
|
||||
const int threads = 32;
|
||||
const int blocks = batch_size;
|
||||
int shared_mem_size = (width + width * width) * sizeof(float);
|
||||
|
||||
mahalanobis_log_kernel<<<blocks, threads, shared_mem_size>>>(
|
||||
x.data_ptr<float>(),
|
||||
mean.data_ptr<float>(),
|
||||
precision.data_ptr<float>(),
|
||||
y.data_ptr<float>(),
|
||||
batch_size,
|
||||
width
|
||||
);
|
||||
return y;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor launch_mahalanobis_log(torch::Tensor x, torch::Tensor mean, torch::Tensor precision);
|
||||
"""
|
||||
|
||||
mahalanobis_log_module = load_inline(
|
||||
name='mahalanobis_log_op',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['launch_mahalanobis_log'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, mean, precision):
|
||||
super(ModelNew, self).__init__()
|
||||
self.mean = nn.Parameter(mean)
|
||||
self.precision = nn.Parameter(precision)
|
||||
self.op = mahalanobis_log_module
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.op.launch_mahalanobis_log(x.contiguous(), self.mean.contiguous(), self.precision.contiguous())
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, mean, precision):
|
||||
super(Model, self).__init__()
|
||||
self.mean = nn.Parameter(mean)
|
||||
self.precision = nn.Parameter(precision)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
diff = x - self.mean
|
||||
temp = torch.matmul(diff, self.precision)
|
||||
mah_sq = torch.sum(temp * diff, dim=-1)
|
||||
dist = torch.sqrt(torch.abs(mah_sq))
|
||||
return torch.log(dist)
|
||||
|
||||
batch_size = 128
|
||||
input_dim = 32
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, input_dim)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
mean = torch.randn(input_dim)
|
||||
aux = torch.randn(input_dim, input_dim)
|
||||
precision = torch.matmul(aux.T, aux) + torch.eye(input_dim) * 0.1
|
||||
return [mean, precision]
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
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.
|
||||
CUDA C++ kernel for log‑transformed Mahalanobis distance
|
||||
|
||||
Shared‑memory caching of difference vector (s_diff) and precision matrix (s_prec)
|
||||
|
||||
Parallel matrix‑vector multiplication using shared memory (assumes width ≤ 32)
|
||||
|
||||
Mahalanobis distance squared computed as (x−μ)ᵀ·P·(x−μ) with warp‑level reduction (__shfl_down_sync)
|
||||
|
||||
Logarithmic transformation: log(dist) applied to the square‑root of the distance
|
||||
|
||||
Block‑per‑sample processing with 32 threads (optimized for small dimension width)
|
||||
|
||||
Dynamic shared memory sized to hold difference vector + full precision matrix
|
||||
|
||||
PyTorch inline C++/CUDA extension via load_inline
|
||||
|
||||
|
||||
|
||||
|
||||
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, mean, precision):
|
||||
super(Model, self).__init__()
|
||||
self.mean = nn.Parameter(mean)
|
||||
self.precision = nn.Parameter(precision)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
diff = x - self.mean
|
||||
temp = torch.matmul(diff, self.precision)
|
||||
mah_sq = torch.sum(temp * diff, dim=-1)
|
||||
dist = torch.sqrt(torch.abs(mah_sq))
|
||||
return torch.log(dist)
|
||||
|
||||
batch_size = 128
|
||||
input_dim = 32
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, input_dim)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
mean = torch.randn(input_dim)
|
||||
aux = torch.randn(input_dim, input_dim)
|
||||
precision = torch.matmul(aux.T, aux) + torch.eye(input_dim) * 0.1
|
||||
return [mean, precision]
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from mahalanobis_log_torch import Model, get_inputs, get_init_inputs
|
||||
from mahalanobis_log_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