Merge pull request 'finish GlobalResponseNormalization #119' (#767) from ZZZJ/GPUCodeForces:GlobalResponseNormalization into main

This commit is contained in:
wawahejun 2025-12-14 20:28:45 +08:00
commit d54e7dec01
4 changed files with 328 additions and 0 deletions

View File

@ -0,0 +1,184 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(384, device='cuda'))
self.beta = nn.Parameter(torch.zeros(384, device='cuda'))
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor grn_cuda(torch::Tensor input, torch::Tensor gamma, torch::Tensor beta, float eps);
"""
cuda_source = """
#include <cuda_runtime.h>
#define BLOCK_SIZE 256
__device__ __forceinline__ double warpReduceSum(double val) {
#pragma unroll
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_down_sync(0xffffffff, val, offset);
return val;
}
__device__ __forceinline__ double blockReduceSum(double val) {
static __shared__ double shared[32];
int lane = threadIdx.x % 32;
int wid = threadIdx.x / 32;
val = warpReduceSum(val);
if (lane == 0) shared[wid] = val;
__syncthreads();
val = (threadIdx.x < (BLOCK_SIZE / 32)) ? shared[lane] : 0.0;
if (wid == 0) val = warpReduceSum(val);
return val;
}
__global__ void grn_stats_kernel(
const float* __restrict__ input,
double* __restrict__ norms, // Output: [N, C] stored in double
int spatial_size, // H * W
int n_vec_spatial // H * W / 4
) {
int nc = blockIdx.x; // Batch * Channel index
int tid = threadIdx.x;
// Input pointer for this channel
const float* in_ptr = input + (long long)nc * spatial_size;
double sum_sq = 0.0;
// Grid-Stride Loop over Spatial (Float4)
for (int i = tid; i < n_vec_spatial; i += BLOCK_SIZE) {
float4 v = reinterpret_cast<const float4*>(in_ptr)[i];
sum_sq += (double)v.x * v.x + (double)v.y * v.y +
(double)v.z * v.z + (double)v.w * v.w;
}
// Reduction
sum_sq = blockReduceSum(sum_sq);
if (tid == 0) {
norms[nc] = sqrt(sum_sq);
}
}
__global__ void grn_apply_kernel(
const float* __restrict__ input,
const double* __restrict__ norms, // [N, C]
const float* __restrict__ gamma, // [C]
const float* __restrict__ beta, // [C]
float* __restrict__ output,
int channels,
int spatial_size,
int n_vec_spatial,
float eps
) {
int n = blockIdx.x;
int c = blockIdx.y;
int tid = threadIdx.x;
const double* norms_n = norms + n * channels;
double local_norm_sum = 0.0;
for (int i = tid; i < channels; i += BLOCK_SIZE) {
local_norm_sum += norms_n[i];
}
double total_norm_sum = blockReduceSum(local_norm_sum);
__shared__ float s_nx; // Scaling factor for this channel
if (tid == 0) {
double mean_norm = total_norm_sum / channels;
double my_norm = norms_n[c];
// nx = gx / (mean + eps)
s_nx = (float)(my_norm / (mean_norm + (double)eps));
}
__syncthreads();
float nx = s_nx;
float g = gamma[c];
float b = beta[c];
long long offset = (long long)n * (channels * spatial_size) + c * spatial_size;
const float* in_ptr = input + offset;
float* out_ptr = output + offset;
for (int i = tid; i < n_vec_spatial; i += BLOCK_SIZE) {
float4 v = reinterpret_cast<const float4*>(in_ptr)[i];
float4 out_v;
// Fused computation
out_v.x = g * (v.x * nx) + b + v.x;
out_v.y = g * (v.y * nx) + b + v.y;
out_v.z = g * (v.z * nx) + b + v.z;
out_v.w = g * (v.w * nx) + b + v.w;
reinterpret_cast<float4*>(out_ptr)[i] = out_v;
}
}
torch::Tensor grn_cuda(torch::Tensor input, torch::Tensor gamma, torch::Tensor beta, float eps) {
int batch = input.size(0);
int channels = input.size(1);
int height = input.size(2);
int width = input.size(3);
int spatial = height * width;
auto output = torch::empty_like(input);
if (spatial % 4 != 0) return output;
int n_vec_spatial = spatial / 4;
auto norms = torch::empty({batch, channels}, input.options().dtype(torch::kFloat64));
dim3 grid_stats(batch * channels);
dim3 block(BLOCK_SIZE);
grn_stats_kernel<<<grid_stats, block>>>(
input.data_ptr<float>(),
norms.data_ptr<double>(),
spatial,
n_vec_spatial
);
dim3 grid_apply(batch, channels);
grn_apply_kernel<<<grid_apply, block>>>(
input.data_ptr<float>(),
norms.data_ptr<double>(),
gamma.data_ptr<float>(),
beta.data_ptr<float>(),
output.data_ptr<float>(),
channels,
spatial,
n_vec_spatial,
eps
);
return output;
}
"""
self.op = load_inline(
name="grn_cuda_opt_v2",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["grn_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not x.is_contiguous(): x = x.contiguous()
return self.op.grn_cuda(x, self.gamma, self.beta, 1e-6)

View File

@ -0,0 +1,31 @@
import torch
import torch.nn as nn
BATCH = 32
CHANNELS = 384
HEIGHT = 56
WIDTH = 56
EPS = 1e-6
class Model(nn.Module):
def __init__(self):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(CHANNELS))
self.beta = nn.Parameter(torch.zeros(CHANNELS))
def forward(self, x: torch.Tensor) -> torch.Tensor:
gx = torch.norm(x, p=2, dim=(2, 3), keepdim=True)
nx = gx / (gx.mean(dim=1, keepdim=True) + EPS)
return self.gamma.view(1, -1, 1, 1) * (x * nx) + self.beta.view(1, -1, 1, 1) + x
def get_inputs():
x = torch.randint(low=-2, high=3, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float()
return [x]
def get_init_inputs():
return []

39
S1/ZZZJ_#119/prompt.txt Normal file
View File

@ -0,0 +1,39 @@
You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
python
import torch
import torch.nn as nn
BATCH = 32
CHANNELS = 384
HEIGHT = 56
WIDTH = 56
EPS = 1e-6
class Model(nn.Module):
def __init__(self):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(CHANNELS))
self.beta = nn.Parameter(torch.zeros(CHANNELS))
def forward(self, x: torch.Tensor) -> torch.Tensor:
gx = torch.norm(x, p=2, dim=(2, 3), keepdim=True)
nx = gx / (gx.mean(dim=1, keepdim=True) + EPS)
return self.gamma.view(1, -1, 1, 1) * (x * nx) + self.beta.view(1, -1, 1, 1) + x
def get_inputs():
x = torch.randint(low=-2, high=3, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

74
S1/ZZZJ_#119/run_code.py Normal file
View File

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