forked from ccf-ai-infra/GPUCodeForces
delete 11
This commit is contained in:
parent
af453c19b0
commit
5dd881c63d
|
|
@ -1,137 +0,0 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
from frn_torch import N, C, H, W, EPS
|
||||
|
||||
assert (H * W) % 4 == 0, "Instance size (H * W) must be a multiple of 4 for float4 vectorization"
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(frn_weight.clone())
|
||||
self.bias = nn.Parameter(frn_bias.clone())
|
||||
|
||||
self.eps = EPS
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor frn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
float eps);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <float.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define WARP_SIZE 32
|
||||
|
||||
__device__ __forceinline__ 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 frn_fused_vectorized_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ weight,
|
||||
const float* __restrict__ bias,
|
||||
float* __restrict__ y,
|
||||
int N, int C, int H, int W, float eps
|
||||
) {
|
||||
__shared__ float s_warp_sum_sqs[BLOCK_SIZE / WARP_SIZE];
|
||||
|
||||
int nc_idx = blockIdx.x;
|
||||
if (nc_idx >= N * C) return;
|
||||
|
||||
int sample_idx = nc_idx / C;
|
||||
int channel_idx = nc_idx % C;
|
||||
int instance_size = H * W;
|
||||
const int instance_size_div4 = instance_size / 4;
|
||||
|
||||
int instance_offset = (sample_idx * C + channel_idx) * instance_size;
|
||||
|
||||
const float4* x4_ptr = reinterpret_cast<const float4*>(x + instance_offset);
|
||||
float4* y4_ptr = reinterpret_cast<float4*>(y + instance_offset);
|
||||
|
||||
float thread_sum_sq = 0.0f;
|
||||
for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) {
|
||||
float4 val4 = x4_ptr[i_vec];
|
||||
thread_sum_sq += val4.x * val4.x;
|
||||
thread_sum_sq += val4.y * val4.y;
|
||||
thread_sum_sq += val4.z * val4.z;
|
||||
thread_sum_sq += val4.w * val4.w;
|
||||
}
|
||||
|
||||
float warp_sum_sq = warp_reduce_sum(thread_sum_sq);
|
||||
|
||||
int warp_id = threadIdx.x / WARP_SIZE;
|
||||
int lane_id = threadIdx.x % WARP_SIZE;
|
||||
if (lane_id == 0) s_warp_sum_sqs[warp_id] = warp_sum_sq;
|
||||
__syncthreads();
|
||||
|
||||
warp_sum_sq = (threadIdx.x < BLOCK_SIZE / WARP_SIZE) ? s_warp_sum_sqs[lane_id] : 0.0f;
|
||||
if (warp_id == 0) warp_sum_sq = warp_reduce_sum(warp_sum_sq);
|
||||
|
||||
if (threadIdx.x == 0) {
|
||||
float mean_sq = warp_sum_sq / instance_size;
|
||||
s_warp_sum_sqs[0] = rsqrtf(mean_sq + eps);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float inv_stddev = s_warp_sum_sqs[0];
|
||||
|
||||
float w = weight[channel_idx];
|
||||
float b = bias[channel_idx];
|
||||
|
||||
for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) {
|
||||
float4 x_val4 = x4_ptr[i_vec];
|
||||
|
||||
// FRN: y = x * inv_stddev * gamma + beta
|
||||
x_val4.x = x_val4.x * inv_stddev * w + b;
|
||||
x_val4.y = x_val4.y * inv_stddev * w + b;
|
||||
x_val4.z = x_val4.z * inv_stddev * w + b;
|
||||
x_val4.w = x_val4.w * inv_stddev * w + b;
|
||||
|
||||
y4_ptr[i_vec] = x_val4;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor frn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
float eps) {
|
||||
|
||||
const int N = input.size(0);
|
||||
const int C = input.size(1);
|
||||
const int H = input.size(2);
|
||||
const int W = input.size(3);
|
||||
auto output = torch::empty_like(input);
|
||||
|
||||
const int blocks = N * C;
|
||||
const int threads = BLOCK_SIZE;
|
||||
size_t shared_mem_size = (threads / WARP_SIZE) * sizeof(float);
|
||||
|
||||
frn_fused_vectorized_kernel<<<blocks, threads, shared_mem_size>>>(
|
||||
input.data_ptr<float>(),
|
||||
weight.contiguous().view(-1).data_ptr<float>(),
|
||||
bias.contiguous().view(-1).data_ptr<float>(),
|
||||
output.data_ptr<float>(), N, C, H, W, eps);
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
self.frn_op = load_inline(
|
||||
name="frn_fused_op_vectorized_final",
|
||||
cpp_sources=cpp_source, cuda_sources=cuda_source,
|
||||
functions=["frn_forward_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn_op.frn_forward_cuda(
|
||||
x.contiguous(), self.weight, self.bias, self.eps
|
||||
)
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
# frn_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 定义维度常量
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-6
|
||||
|
||||
class FRN(nn.Module):
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1))
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True)
|
||||
x_normalized = x / torch.sqrt(nu2 + self.eps)
|
||||
return x_normalized * self.weight + self.bias
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.frn = FRN(C, EPS)
|
||||
with torch.no_grad():
|
||||
self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1))
|
||||
self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
frn_weight = torch.ones(1, C, 1, 1)
|
||||
frn_bias = torch.zeros(1, C, 1, 1)
|
||||
return [frn_weight, frn_bias]
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
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
|
||||
# frn_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 定义维度常量
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-6
|
||||
|
||||
class FRN(nn.Module):
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1))
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True)
|
||||
x_normalized = x / torch.sqrt(nu2 + self.eps)
|
||||
return x_normalized * self.weight + self.bias
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.frn = FRN(C, EPS)
|
||||
with torch.no_grad():
|
||||
self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1))
|
||||
self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
frn_weight = torch.ones(1, C, 1, 1)
|
||||
frn_bias = torch.zeros(1, C, 1, 1)
|
||||
return [frn_weight, frn_bias]
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from frn_torch import Model, get_inputs, get_init_inputs
|
||||
from frn_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)
|
||||
|
||||
# 更严格的精度检查
|
||||
abs_diff = (output_torch - output_cuda).abs()
|
||||
max_diff = abs_diff.max().item()
|
||||
mean_diff = abs_diff.mean().item()
|
||||
|
||||
print(f"最大差异: {max_diff:.6f}")
|
||||
print(f"平均差异: {mean_diff:.6f}")
|
||||
|
||||
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
|
||||
if precision_flag:
|
||||
print("✅ 精度对齐:两个模型的输出结果非常接近。")
|
||||
else:
|
||||
print("❌ 精度不一致!")
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
|
||||
|
||||
# Warm up
|
||||
for _ in range(100):
|
||||
_ = 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒")
|
||||
print(f"自定义 CUDA ReLU 平均执行时间: {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()
|
||||
Loading…
Reference in New Issue