finish minmaxscaleshift #98

This commit is contained in:
uucoco 2025-12-10 19:24:47 +08:00
parent 10eed82956
commit 45be55fc91
4 changed files with 339 additions and 0 deletions

View File

@ -0,0 +1,133 @@
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>
__inline__ __device__ void warpReduceMinMax(float &min_val, float &max_val) {
for (int offset = 16; offset > 0; offset /= 2) {
min_val = fminf(min_val, __shfl_down_sync(0xffffffff, min_val, offset));
max_val = fmaxf(max_val, __shfl_down_sync(0xffffffff, max_val, offset));
}
}
__global__ void minmax_scale_shift_kernel(
const float* __restrict__ input,
float* __restrict__ output,
float scale,
float shift,
float eps,
int rows,
int cols
) {
__shared__ float s_min;
__shared__ float s_max;
int bid = blockIdx.x;
int tid = threadIdx.x;
const float* row_in = input + bid * cols;
float* row_out = output + bid * cols;
float local_min = INFINITY;
float local_max = -INFINITY;
for (int i = tid; i < cols; i += blockDim.x) {
float val = row_in[i];
local_min = fminf(local_min, val);
local_max = fmaxf(local_max, val);
}
// Warp Reduction
warpReduceMinMax(local_min, local_max);
// Block Reduction
int lane = tid % 32;
int wid = tid / 32;
__shared__ float shared_min[32];
__shared__ float shared_max[32];
if (lane == 0) {
shared_min[wid] = local_min;
shared_max[wid] = local_max;
}
__syncthreads();
if (wid == 0) {
local_min = (tid < (blockDim.x / 32)) ? shared_min[tid] : INFINITY;
local_max = (tid < (blockDim.x / 32)) ? shared_max[tid] : -INFINITY;
warpReduceMinMax(local_min, local_max);
if (tid == 0) {
s_min = local_min;
s_max = local_max;
}
}
__syncthreads();
float min_x = s_min;
float max_x = s_max;
float range_x_inv = rsqrtf(max_x - min_x + eps) * rsqrtf(max_x - min_x + eps); // 1 / (range + eps)
// Pass 2: Normalize, Scale, Shift
for (int i = tid; i < cols; i += blockDim.x) {
float val = row_in[i];
float norm = (val - min_x) * range_x_inv;
// Scale and Shift: fma(norm, scale, shift)
row_out[i] = fmaf(norm, scale, shift);
}
}
torch::Tensor minmax_scale_shift_cuda(torch::Tensor input, float scale, float shift, float eps) {
auto output = torch::empty_like(input);
int cols = input.size(input.dim() - 1);
int rows = input.numel() / cols;
int block_size = 256;
while (block_size < cols && block_size < 1024) {
block_size *= 2;
}
minmax_scale_shift_kernel<<<rows, block_size>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
scale,
shift,
eps,
rows,
cols
);
return output;
}
"""
cpp_source = """
torch::Tensor minmax_scale_shift_cuda(torch::Tensor input, float scale, float shift, float eps);
"""
module = load_inline(
name="minmax_scale_shift",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["minmax_scale_shift_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self, scale, shift, eps=1e-5):
super(ModelNew, self).__init__()
self.scale = scale
self.shift = shift
self.eps = eps
self.module = module
def forward(self, x):
return self.module.minmax_scale_shift_cuda(x, self.scale, self.shift, self.eps)

View File

@ -0,0 +1,35 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, scale, shift, eps=1e-5):
super(Model, self).__init__()
self.scale = scale
self.shift = shift
self.eps = eps
def forward(self, x):
min_x = x.min(dim=-1, keepdim=True).values
max_x = x.max(dim=-1, keepdim=True).values
range_x = max_x - min_x
# MinMax Normalization
norm = (x - min_x) / (range_x + self.eps)
# Scale and Shift
return norm * self.scale + self.shift
batch_size = 16
dim = 256
def get_inputs():
x = torch.randn(batch_size, dim) * 10.0
return [x]
def get_init_inputs():
return [2.0, 1.0]

94
S1/uucoco_#98/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**: Custom `warpReduceMinMax()` using `__shfl_down_sync()`
- **Dual reduction**: Simultaneous min and max computation
- **Block-level parallelism**: One CUDA block per row
- **Dynamic block sizing**: Adaptive thread block size
- **Fused multiply-add**: `fmaf()` for scale+shift operation
## Mathematical Operations
- **Min/Max detection**: Find per-row minimum and maximum
- **Min-Max normalization**: `(x - min) / (max - min + eps)`
- **Scaling**: Multiply by user-defined scale factor
- **Shifting**: Add user-defined shift value
- **Reciprocal computation**: `rsqrtf()²` trick for `1/(range+eps)`
## Parallel Patterns
- **Two-pass algorithm**: First find min/max, then normalize
- **Row-wise processing**: Each block processes one row
- **Dual-value reduction**: Efficient min and max reduction together
- **Grid-stride loops**: Threads process multiple columns per row
## Optimization Techniques
- **Fused operations**: Normalization + scaling + shifting in single kernel
- **Warp-aware reduction**: Optimized for 32-thread warps
- **Numerical stability**: Epsilon prevents division by zero
- **FMA usage**: `fmaf()` for precise scale+shift computation
- **Adaptive block size**: Dynamically adjusted for column count
## Performance Features
- **Massive parallelism**: Row-level and column-level parallelism
- **Efficient reduction**: Custom min/max reduction using warp shuffles
- **Memory coalescing**: Row-major access patterns
- **Numerical optimization**: Reciprocal via rsqrtf()² for speed
## Unique Aspects
- **Dual reduction**: Simultaneous min and max finding
- **Complete normalization pipeline**: Detect range → normalize → scale → shift
- **Parameterized transformation**: User-defined scale and shift
- **Row-wise adaptation**: Each row normalized based on its own statistics
## Numerical Considerations
- **Epsilon protection**: Prevents division by (max-min) ≈ 0
- **Range invariance**: Handles constant rows (max = min)
- **INFINITY constants**: Using CUDA's INFINITY for initial min/max
- **Reciprocal trick**: `rsqrtf(x)*rsqrtf(x)` ≈ `1/x` (fast approximation)
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, scale, shift, eps=1e-5):
super(Model, self).__init__()
self.scale = scale
self.shift = shift
self.eps = eps
def forward(self, x):
min_x = x.min(dim=-1, keepdim=True).values
max_x = x.max(dim=-1, keepdim=True).values
range_x = max_x - min_x
# MinMax Normalization
norm = (x - min_x) / (range_x + self.eps)
# Scale and Shift
return norm * self.scale + self.shift
batch_size = 16
dim = 256
def get_inputs():
x = torch.randn(batch_size, dim) * 10.0
return [x]
def get_init_inputs():
return [2.0, 1.0]

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

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