forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish winsorize_scale_normalize #143' (#811) from gsd123/GPUCodeForces:gsd143 into main
This commit is contained in:
commit
2da66e3cc3
|
|
@ -0,0 +1,61 @@
|
|||
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 Winsorized normalization with fixed dimension (1024)
|
||||
|
||||
Bitonic sort in shared memory for quantile computation
|
||||
|
||||
Linear interpolation to estimate 5th and 95th percentiles (Q_LOW=0.05, Q_HIGH=0.95)
|
||||
|
||||
Winsorizing (clipping): values below lower bound or above upper bound are clipped
|
||||
|
||||
Two‑pass statistics: mean and variance computed after clipping
|
||||
|
||||
Warp‑level reduction using __shfl_down_sync for sum and sum of squares
|
||||
|
||||
Shared‑memory broadcast for mean and standard deviation
|
||||
|
||||
Vectorized load/store via float4 for coalesced memory access
|
||||
|
||||
Block‑parallel processing: one block per batch element, 256 threads per block
|
||||
|
||||
Standard normalization with epsilon for numerical stability
|
||||
|
||||
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
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.limits = (0.05, 0.95)
|
||||
|
||||
def forward(self, x):
|
||||
lower = torch.quantile(x, self.limits[0], dim=-1, keepdim=True)
|
||||
upper = torch.quantile(x, self.limits[1], dim=-1, keepdim=True)
|
||||
x_clamped = torch.clamp(x, min=lower, max=upper)
|
||||
|
||||
mean = x_clamped.mean(dim=-1, keepdim=True)
|
||||
std = x_clamped.std(dim=-1, keepdim=True)
|
||||
|
||||
return (x_clamped - mean) / (std + 1e-8)
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 1024
|
||||
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, dim, device='cuda', dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from winsorize_scale_normalize_torch import Model, get_inputs, get_init_inputs
|
||||
from winsorize_scale_normalize_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,222 @@
|
|||
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 <cmath>
|
||||
|
||||
#define DIM 1024
|
||||
#define Q_LOW 0.05f
|
||||
#define Q_HIGH 0.95f
|
||||
#define EPS 1e-8f
|
||||
|
||||
__device__ __forceinline__ void swap(float& a, float& b) {
|
||||
float tmp = a;
|
||||
a = b;
|
||||
b = tmp;
|
||||
}
|
||||
|
||||
__global__ void winsorize_normalize_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int batch_size
|
||||
) {
|
||||
// Original data for output
|
||||
__shared__ float s_data[DIM];
|
||||
// Buffer for sorting
|
||||
__shared__ float s_sort[DIM];
|
||||
|
||||
int bid = blockIdx.x;
|
||||
int tid = threadIdx.x;
|
||||
|
||||
if (bid >= batch_size) return;
|
||||
|
||||
// 1. Vectorized Load (float4)
|
||||
// Each thread loads 4 elements
|
||||
int offset = bid * DIM;
|
||||
const float4* inp_ptr = reinterpret_cast<const float4*>(input + offset);
|
||||
float4 loaded = inp_ptr[tid];
|
||||
|
||||
// Store to shared memory
|
||||
int base = tid * 4;
|
||||
s_data[base + 0] = loaded.x;
|
||||
s_data[base + 1] = loaded.y;
|
||||
s_data[base + 2] = loaded.z;
|
||||
s_data[base + 3] = loaded.w;
|
||||
|
||||
s_sort[base + 0] = loaded.x;
|
||||
s_sort[base + 1] = loaded.y;
|
||||
s_sort[base + 2] = loaded.z;
|
||||
s_sort[base + 3] = loaded.w;
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// 2. Bitonic Sort on s_sort
|
||||
for (int k = 2; k <= DIM; k <<= 1) {
|
||||
for (int j = k >> 1; j > 0; j >>= 1) {
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 4; ++m) {
|
||||
int i = base + m;
|
||||
int ixj = i ^ j;
|
||||
if (ixj > i) {
|
||||
float a = s_sort[i];
|
||||
float b = s_sort[ixj];
|
||||
bool ascending = ((i & k) == 0);
|
||||
if ((ascending && a > b) || (!ascending && a < b)) {
|
||||
s_sort[i] = b;
|
||||
s_sort[ixj] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Determine Quantiles (Linear Interpolation)
|
||||
// N = 1024
|
||||
// Index = q * (N - 1)
|
||||
__shared__ float lower_bound;
|
||||
__shared__ float upper_bound;
|
||||
|
||||
if (tid == 0) {
|
||||
float idx_low = Q_LOW * (DIM - 1);
|
||||
int i_low = (int)idx_low;
|
||||
float f_low = idx_low - i_low;
|
||||
lower_bound = s_sort[i_low] * (1.0f - f_low) + s_sort[i_low + 1] * f_low;
|
||||
|
||||
float idx_high = Q_HIGH * (DIM - 1);
|
||||
int i_high = (int)idx_high;
|
||||
float f_high = idx_high - i_high;
|
||||
upper_bound = s_sort[i_high] * (1.0f - f_high) + s_sort[i_high + 1] * f_high;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float lb = lower_bound;
|
||||
float ub = upper_bound;
|
||||
|
||||
// 4. Clip (Winsorize) and Compute Mean (Pass 1)
|
||||
// Update s_data with clipped values to avoid re-clipping
|
||||
float sum_local = 0.0f;
|
||||
float vals[4];
|
||||
vals[0] = s_data[base + 0];
|
||||
vals[1] = s_data[base + 1];
|
||||
vals[2] = s_data[base + 2];
|
||||
vals[3] = s_data[base + 3];
|
||||
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 4; ++m) {
|
||||
float v = vals[m];
|
||||
if (v < lb) v = lb;
|
||||
if (v > ub) v = ub;
|
||||
vals[m] = v; // Update local register
|
||||
s_data[base + m] = v; // Update shared memory for consistency
|
||||
sum_local += v;
|
||||
}
|
||||
|
||||
// Warp Reduce Sum
|
||||
for (int offset = 16; offset > 0; offset >>= 1) {
|
||||
sum_local += __shfl_down_sync(0xffffffff, sum_local, offset);
|
||||
}
|
||||
|
||||
// Block Reduce Sum (Shared Memory)
|
||||
__shared__ float s_sums[32]; // 256 threads / 32 warps = 8 warps. Wait, blockdim 256. 256/32=8.
|
||||
int wid = tid / 32;
|
||||
int lane = tid % 32;
|
||||
if (lane == 0) {
|
||||
s_sums[wid] = sum_local;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float mean = 0.0f;
|
||||
if (tid == 0) {
|
||||
float total_sum = 0.0f;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
total_sum += s_sums[i];
|
||||
}
|
||||
mean = total_sum / DIM;
|
||||
s_sums[0] = mean; // Reuse s_sums[0] to broadcast mean
|
||||
}
|
||||
__syncthreads();
|
||||
mean = s_sums[0];
|
||||
|
||||
// 5. Compute Variance (Pass 2)
|
||||
float sum_sq_diff = 0.0f;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 4; ++m) {
|
||||
float diff = vals[m] - mean;
|
||||
sum_sq_diff += diff * diff;
|
||||
}
|
||||
|
||||
// Warp Reduce
|
||||
for (int offset = 16; offset > 0; offset >>= 1) {
|
||||
sum_sq_diff += __shfl_down_sync(0xffffffff, sum_sq_diff, offset);
|
||||
}
|
||||
|
||||
if (lane == 0) {
|
||||
s_sums[wid] = sum_sq_diff;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float std = 0.0f;
|
||||
if (tid == 0) {
|
||||
float total_ss = 0.0f;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
total_ss += s_sums[i];
|
||||
}
|
||||
// Unbiased standard deviation
|
||||
std = sqrtf(total_ss / (DIM - 1));
|
||||
s_sums[0] = std;
|
||||
}
|
||||
__syncthreads();
|
||||
std = s_sums[0];
|
||||
|
||||
// 6. Normalize and Store
|
||||
float inv_std = 1.0f / (std + EPS);
|
||||
float4 out_val;
|
||||
out_val.x = (vals[0] - mean) * inv_std;
|
||||
out_val.y = (vals[1] - mean) * inv_std;
|
||||
out_val.z = (vals[2] - mean) * inv_std;
|
||||
out_val.w = (vals[3] - mean) * inv_std;
|
||||
|
||||
float4* out_ptr = reinterpret_cast<float4*>(output + offset);
|
||||
out_ptr[tid] = out_val;
|
||||
}
|
||||
|
||||
torch::Tensor winsorize_scale_cuda(torch::Tensor input) {
|
||||
auto input_c = input.contiguous();
|
||||
int batch_size = input.size(0);
|
||||
// Assumes dim is 1024
|
||||
|
||||
auto output = torch::empty_like(input_c);
|
||||
|
||||
winsorize_normalize_kernel<<<batch_size, 256>>>(
|
||||
input_c.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch_size
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor winsorize_scale_cuda(torch::Tensor input);
|
||||
"""
|
||||
|
||||
module = load_inline(
|
||||
name="winsorize_opt",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["winsorize_scale_cuda"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
return module.winsorize_scale_cuda(x)
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.limits = (0.05, 0.95)
|
||||
|
||||
def forward(self, x):
|
||||
lower = torch.quantile(x, self.limits[0], dim=-1, keepdim=True)
|
||||
upper = torch.quantile(x, self.limits[1], dim=-1, keepdim=True)
|
||||
x_clamped = torch.clamp(x, min=lower, max=upper)
|
||||
|
||||
mean = x_clamped.mean(dim=-1, keepdim=True)
|
||||
std = x_clamped.std(dim=-1, keepdim=True)
|
||||
|
||||
return (x_clamped - mean) / (std + 1e-8)
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 1024
|
||||
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, dim, device='cuda', dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
Loading…
Reference in New Issue