forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish chebyshevDistance #29' (#233) from gsd123/GPUCodeForces:gsd29 into main
This commit is contained in:
commit
e506e4b2cd
|
|
@ -0,0 +1,121 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, feature_dim):
|
||||
super().__init__()
|
||||
self.register_buffer("center", torch.zeros(feature_dim))
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor chebyshev_cuda(torch::Tensor x, torch::Tensor center);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <math.h>
|
||||
|
||||
__device__ __forceinline__ float warp_reduce_max(float val) {
|
||||
#pragma unroll
|
||||
for (int offset = 16; offset > 0; offset /= 2) {
|
||||
float other = __shfl_down_sync(0xffffffff, val, offset);
|
||||
val = fmaxf(val, other);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float block_reduce_max(float val) {
|
||||
static __shared__ float shared[32];
|
||||
int lane = threadIdx.x % 32;
|
||||
int wid = threadIdx.x / 32;
|
||||
|
||||
val = warp_reduce_max(val);
|
||||
|
||||
if (lane == 0) shared[wid] = val;
|
||||
__syncthreads();
|
||||
|
||||
val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0f;
|
||||
|
||||
if (wid == 0) val = warp_reduce_max(val);
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
__global__ void chebyshev_kernel_vec4(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ center,
|
||||
float* __restrict__ output,
|
||||
int batch_size,
|
||||
int feature_dim)
|
||||
{
|
||||
int bid = blockIdx.x;
|
||||
if (bid >= batch_size) return;
|
||||
|
||||
const float* row_x = x + bid * feature_dim;
|
||||
|
||||
float max_val = 0.0f;
|
||||
int vec_loops = feature_dim / 4;
|
||||
int vec_remainder = feature_dim % 4;
|
||||
|
||||
for (int i = threadIdx.x; i < vec_loops; i += blockDim.x) {
|
||||
float4 vx = reinterpret_cast<const float4*>(row_x)[i];
|
||||
float4 vc = reinterpret_cast<const float4*>(center)[i];
|
||||
|
||||
max_val = fmaxf(max_val, fabsf(vx.x - vc.x));
|
||||
max_val = fmaxf(max_val, fabsf(vx.y - vc.y));
|
||||
max_val = fmaxf(max_val, fabsf(vx.z - vc.z));
|
||||
max_val = fmaxf(max_val, fabsf(vx.w - vc.w));
|
||||
}
|
||||
|
||||
int tail_start = vec_loops * 4;
|
||||
if (threadIdx.x < vec_remainder) {
|
||||
int idx = tail_start + threadIdx.x;
|
||||
max_val = fmaxf(max_val, fabsf(row_x[idx] - center[idx]));
|
||||
}
|
||||
|
||||
max_val = block_reduce_max(max_val);
|
||||
|
||||
if (threadIdx.x == 0) {
|
||||
output[bid] = max_val;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor chebyshev_cuda(torch::Tensor x, torch::Tensor center) {
|
||||
auto x_c = x.contiguous();
|
||||
auto c_c = center.contiguous();
|
||||
|
||||
int batch_size = x_c.size(0);
|
||||
int feature_dim = x_c.size(1);
|
||||
|
||||
auto output = torch::empty({batch_size}, x.options());
|
||||
|
||||
int threads = 256;
|
||||
int blocks = batch_size;
|
||||
|
||||
chebyshev_kernel_vec4<<<blocks, threads>>>(
|
||||
x_c.data_ptr<float>(),
|
||||
c_c.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch_size,
|
||||
feature_dim
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="chebyshev_opt_v1",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["chebyshev_cuda"],
|
||||
extra_cuda_cflags=["-O3"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
return self.op.chebyshev_cuda(x, self.center)
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, feature_dim):
|
||||
super().__init__()
|
||||
self.register_buffer("center", torch.zeros(feature_dim))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.max(torch.abs(x - self.center), dim=1).values
|
||||
|
||||
batch_size = 256
|
||||
feature_dim = 512
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return [feature_dim]
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
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 Optimization Strategies:
|
||||
|
||||
Memory Access
|
||||
|
||||
contiguous() for memory coalescing
|
||||
|
||||
Coalesced global memory reads
|
||||
|
||||
Data reuse via L2 cache
|
||||
|
||||
Computation
|
||||
|
||||
Online max/sum calculation in single pass
|
||||
|
||||
Use expf and reciprocal multiplication
|
||||
|
||||
Compiler flags: -O3, --use_fast_math
|
||||
|
||||
Parallelization
|
||||
|
||||
One thread per spatial position (N,H,W)
|
||||
|
||||
Fixed 256 threads, auto-calculated blocks
|
||||
|
||||
__restrict__ pointers for alias analysis
|
||||
|
||||
Numerical Stability
|
||||
|
||||
Online max updates with exponential scaling
|
||||
|
||||
Prevents overflow
|
||||
|
||||
Large Tensor Support
|
||||
|
||||
long long indexing prevents overflow
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
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
|
||||
import torch.nn.functional as F
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Input: (N, C, H, W)
|
||||
Output: (N, C, H, W), Softmax along dim=1 (C)
|
||||
"""
|
||||
return F.softmax(x, dim=1)
|
||||
|
||||
batch_size = 32
|
||||
channels = 64
|
||||
height = 128
|
||||
width = 128
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, channels, height, width, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import torch
|
||||
import time
|
||||
from ChebyshevDistance_torch import Model, get_inputs, get_init_inputs
|
||||
from ChebyshevDistance_cuda import ModelNew
|
||||
|
||||
|
||||
def run_benchmark():
|
||||
if not torch.cuda.is_available():
|
||||
print("CUDA 不可用")
|
||||
return
|
||||
|
||||
device = torch.device("cuda")
|
||||
|
||||
# 准备输入数据
|
||||
inputs = [x.cuda(device=device) for x in get_inputs()]
|
||||
init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()]
|
||||
|
||||
# 初始化模型
|
||||
torch_model = Model(*init_inputs).cuda()
|
||||
cuda_model = ModelNew(*init_inputs).cuda()
|
||||
|
||||
torch_model.eval()
|
||||
cuda_model.eval()
|
||||
|
||||
print("-------------------- 精度对齐验证 --------------------")
|
||||
with torch.no_grad():
|
||||
# 预热GPU
|
||||
_ = torch_model(*inputs)
|
||||
_ = cuda_model(*inputs)
|
||||
|
||||
# 正式测试
|
||||
output_torch = torch_model(*inputs)
|
||||
output_cuda = cuda_model(*inputs)
|
||||
|
||||
# 精度验证
|
||||
abs_diff = torch.abs(output_torch - output_cuda)
|
||||
max_diff = torch.max(abs_diff).item()
|
||||
mean_diff = torch.mean(abs_diff).item()
|
||||
|
||||
if max_diff < 1e-4 and mean_diff < 1e-5:
|
||||
print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
|
||||
precision_flag = True
|
||||
else:
|
||||
print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
|
||||
precision_flag = False
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 100
|
||||
|
||||
# 预热GPU
|
||||
for _ in range(10):
|
||||
_ = torch_model(*inputs)
|
||||
_ = cuda_model(*inputs)
|
||||
|
||||
# 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内置Swish平均执行时间: {torch_time:.6f}秒")
|
||||
print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}秒")
|
||||
speedup = torch_time / cuda_time if cuda_time > 0 else 0
|
||||
print(f"加速比 (Speedup): {speedup:.2f}x")
|
||||
|
||||
return precision_flag, speedup
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
precision_flag, speedup = run_benchmark()
|
||||
Loading…
Reference in New Issue