finish Meanstdnormalizeclip #97

This commit is contained in:
uucoco 2025-12-10 19:22:46 +08:00
parent 10eed82956
commit ebe2201ff3
4 changed files with 373 additions and 0 deletions

View File

@ -0,0 +1,170 @@
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>
#define WARP_SIZE 32
__inline__ __device__ float warp_reduce_sum(float val) {
for (int offset = WARP_SIZE/2; offset > 0; offset /= 2) {
val += __shfl_down_sync(0xffffffff, val, offset);
}
return val;
}
__global__ void normalize_clamp_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int batch_size,
int dim,
float min_val,
float max_val,
float eps) {
int b = blockIdx.x;
if (b >= batch_size) return;
int tid = threadIdx.x;
int stride = blockDim.x;
const float* x_ptr = input + b * dim;
float* out_ptr = output + b * dim;
float sum = 0.0f;
for (int i = tid; i < dim; i += stride) {
sum += x_ptr[i];
}
sum = warp_reduce_sum(sum);
__shared__ float shared_sum[32];
int lane = tid % WARP_SIZE;
int wid = tid / WARP_SIZE;
if (lane == 0) {
shared_sum[wid] = sum;
}
__syncthreads();
if (tid < blockDim.x / WARP_SIZE) {
sum = shared_sum[tid];
} else {
sum = 0.0f;
}
if (wid == 0) {
sum = warp_reduce_sum(sum);
}
__shared__ float mean_shared;
if (tid == 0) {
mean_shared = sum / dim;
}
__syncthreads();
float mean = mean_shared;
float var_sum = 0.0f;
for (int i = tid; i < dim; i += stride) {
float diff = x_ptr[i] - mean;
var_sum += diff * diff;
}
var_sum = warp_reduce_sum(var_sum);
if (lane == 0) {
shared_sum[wid] = var_sum;
}
__syncthreads();
if (tid < blockDim.x / WARP_SIZE) {
var_sum = shared_sum[tid];
} else {
var_sum = 0.0f;
}
if (wid == 0) {
var_sum = warp_reduce_sum(var_sum);
}
__shared__ float std_shared;
if (tid == 0) {
float variance = var_sum / (dim - 1);
std_shared = sqrtf(variance);
}
__syncthreads();
float std = std_shared;
for (int i = tid; i < dim; i += stride) {
float norm = (x_ptr[i] - mean) / (std + eps);
float clamped;
if (norm < min_val) {
clamped = min_val;
} else if (norm > max_val) {
clamped = max_val;
} else {
clamped = norm;
}
out_ptr[i] = clamped;
}
}
torch::Tensor normalize_clamp_cuda(
torch::Tensor x,
float min_val,
float max_val,
float eps) {
int batch_size = x.size(0);
int dim = x.size(1);
auto output = torch::empty_like(x);
int threads = 256;
normalize_clamp_kernel<<<batch_size, threads>>>(
x.data_ptr<float>(),
output.data_ptr<float>(),
batch_size,
dim,
min_val,
max_val,
eps
);
return output;
}
"""
cpp_source = """
torch::Tensor normalize_clamp_cuda(
torch::Tensor x,
float min_val,
float max_val,
float eps);
"""
cuda_module = load_inline(
name="normalize_clamp_module",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["normalize_clamp_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self, min_val, max_val, eps=1e-5):
super(ModelNew, self).__init__()
self.min_val = min_val
self.max_val = max_val
self.eps = eps
def forward(self, x):
return cuda_module.normalize_clamp_cuda(x, self.min_val, self.max_val, self.eps)

View File

@ -0,0 +1,32 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, min_val, max_val, eps=1e-5):
super(Model, self).__init__()
self.min_val = min_val
self.max_val = max_val
self.eps = eps
def forward(self, x):
mean = x.mean(dim=-1, keepdim=True)
std = x.std(dim=-1, keepdim=True)
norm = (x - mean) / (std + self.eps)
return torch.clamp(norm, self.min_val, self.max_val)
batch_size = 16
dim = 256
min_val = -1.0
max_val = 1.0
def get_inputs():
x = torch.randn(batch_size, dim) * 10.0
return [x]
def get_init_inputs():
return [min_val, max_val]

94
S1/uucoco_#97/prompt.txt Normal file
View File

@ -0,0 +1,94 @@
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.
# Technologies Used in This Code
## Core Libraries
- **PyTorch**: Deep learning framework
- **CUDA**: NVIDIA GPU parallel computing
- **C++**: Kernel implementation
## Advanced CUDA Features
- **Warp reduction**: `__shfl_down_sync()` for efficient warp-level operations
- **Block-level parallelism**: One CUDA block per batch sample
- **Two-level reduction**: Warp shuffles + shared memory for statistics
- **Dynamic parallelism**: Threads process multiple elements per row
## Statistical Operations
- **Mean computation**: Calculate per-row average
- **Variance calculation**: Compute per-row variance
- **Standard deviation**: sqrt(variance) for normalization
- **Z-score normalization**: (x - mean) / (std + eps)
## Clipping/Normalization
- **Value clipping**: Hard limits with min_val and max_val
- **Batch normalization**: Per-sample standardization
- **Numerical stability**: Epsilon to prevent division by zero
- **Conditional clamping**: Branch-based clipping logic
## Parallel Patterns
- **Row-wise processing**: Each block processes one batch sample
- **Two-pass statistics**: First compute mean, then variance
- **Shared memory coordination**: Broadcast mean/std to all threads
- **Warp-level optimization**: Efficient reduction using warp shuffles
## Optimization Techniques
- **Fused operations**: Statistics + normalization + clipping in single kernel
- **Efficient reduction**: Custom warp/block reduction functions
- **Memory coalescing**: Row-major access patterns
- **Numerical safety**: Epsilon protection and Bessel's correction (dim-1)
## Performance Features
- **Massive parallelism**: Batch-level and element-level parallelism
- **Minimal synchronization**: Shared memory for statistic broadcasting
- **Statistical accuracy**: Proper variance calculation with Bessel's correction
- **Adaptive design**: Works for any batch size and dimension
## Unique Aspects
- **Complete pipeline**: Statistics → normalization → clipping
- **Per-sample normalization**: Independent normalization per batch element
- **Warp-aware reduction**: Optimized for GPU warp architecture (32 threads)
- **Robust statistics**: Handles edge cases with eps protection
## Numerical Considerations
- **Bessel's correction**: Uses (dim-1) for unbiased variance
- **Clipping range**: User-defined min_val and max_val
- **Epsilon selection**: Prevents division by near-zero std
- **Floating-point stability**: Careful order of operations
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, min_val, max_val, eps=1e-5):
super(Model, self).__init__()
self.min_val = min_val
self.max_val = max_val
self.eps = eps
def forward(self, x):
mean = x.mean(dim=-1, keepdim=True)
std = x.std(dim=-1, keepdim=True)
norm = (x - mean) / (std + self.eps)
return torch.clamp(norm, self.min_val, self.max_val)
batch_size = 16
dim = 256
min_val = -1.0
max_val = 1.0
def get_inputs():
x = torch.randn(batch_size, dim) * 10.0
return [x]
def get_init_inputs():
return [min_val, max_val]

77
S1/uucoco_#97/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from meanstdnormalizeclip_torch import Model, get_inputs, get_init_inputs
from meanstdnormalizeclip_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()