forked from ccf-ai-infra/GPUCodeForces
fixes MinmaxObserver #103
This commit is contained in:
parent
cc73715277
commit
beb21dff07
|
|
@ -0,0 +1,139 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
minmax_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <cfloat>
|
||||
|
||||
__device__ __forceinline__ void atomicMinFloat(float* addr, float value) {
|
||||
int* addr_as_int = (int*)addr;
|
||||
int old = *addr_as_int, assumed;
|
||||
do {
|
||||
assumed = old;
|
||||
if (__int_as_float(assumed) <= value) break;
|
||||
old = atomicCAS(addr_as_int, assumed, __float_as_int(value));
|
||||
} while (assumed != old);
|
||||
}
|
||||
|
||||
|
||||
__device__ __forceinline__ void atomicMaxFloat(float* addr, float value) {
|
||||
int* addr_as_int = (int*)addr;
|
||||
int old = *addr_as_int, assumed;
|
||||
do {
|
||||
assumed = old;
|
||||
if (__int_as_float(assumed) >= value) break;
|
||||
old = atomicCAS(addr_as_int, assumed, __float_as_int(value));
|
||||
} while (assumed != old);
|
||||
}
|
||||
|
||||
__global__ void minmax_kernel(const float* __restrict__ input,
|
||||
float* __restrict__ out_min,
|
||||
float* __restrict__ out_max,
|
||||
int size) {
|
||||
int tid = threadIdx.x;
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int stride = blockDim.x * gridDim.x;
|
||||
|
||||
|
||||
float local_min = FLT_MAX;
|
||||
float local_max = -FLT_MAX;
|
||||
|
||||
|
||||
int vec_size = size / 4;
|
||||
const float4* vec_input = reinterpret_cast<const float4*>(input);
|
||||
|
||||
for (int i = idx; i < vec_size; i += stride) {
|
||||
float4 v = vec_input[i];
|
||||
|
||||
local_min = fminf(local_min, v.x);
|
||||
local_max = fmaxf(local_max, v.x);
|
||||
|
||||
local_min = fminf(local_min, v.y);
|
||||
local_max = fmaxf(local_max, v.y);
|
||||
|
||||
local_min = fminf(local_min, v.z);
|
||||
local_max = fmaxf(local_max, v.z);
|
||||
|
||||
local_min = fminf(local_min, v.w);
|
||||
local_max = fmaxf(local_max, v.w);
|
||||
}
|
||||
|
||||
int tail_start = vec_size * 4;
|
||||
for (int i = tail_start + idx; i < size; i += stride) {
|
||||
float val = input[i];
|
||||
local_min = fminf(local_min, val);
|
||||
local_max = fmaxf(local_max, val);
|
||||
}
|
||||
|
||||
extern __shared__ float shared_mem[];
|
||||
float* s_min = shared_mem;
|
||||
float* s_max = shared_mem + blockDim.x;
|
||||
|
||||
s_min[tid] = local_min;
|
||||
s_max[tid] = local_max;
|
||||
__syncthreads();
|
||||
|
||||
|
||||
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
|
||||
if (tid < s) {
|
||||
s_min[tid] = fminf(s_min[tid], s_min[tid + s]);
|
||||
s_max[tid] = fmaxf(s_max[tid], s_max[tid + s]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
|
||||
if (tid == 0) {
|
||||
atomicMinFloat(out_min, s_min[0]);
|
||||
atomicMaxFloat(out_max, s_max[0]);
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor minmax_cuda(torch::Tensor input) {
|
||||
int size = input.numel();
|
||||
|
||||
auto options = input.options();
|
||||
auto min_t = torch::full({1}, FLT_MAX, options);
|
||||
auto max_t = torch::full({1}, -FLT_MAX, options);
|
||||
|
||||
const int block_size = 256;
|
||||
|
||||
|
||||
int num_sms = 108;
|
||||
int grid_size = num_sms * 4;
|
||||
|
||||
|
||||
if (grid_size > 512) grid_size = 512;
|
||||
|
||||
int shared_mem_size = 2 * block_size * sizeof(float);
|
||||
|
||||
minmax_kernel<<<grid_size, block_size, shared_mem_size>>>(
|
||||
input.data_ptr<float>(),
|
||||
min_t.data_ptr<float>(),
|
||||
max_t.data_ptr<float>(),
|
||||
size
|
||||
);
|
||||
|
||||
return (max_t - min_t) / 255.0f;
|
||||
}
|
||||
"""
|
||||
|
||||
minmax_cpp_source = "torch::Tensor minmax_cuda(torch::Tensor input);"
|
||||
|
||||
module = load_inline(
|
||||
name="minmax_impl_v2",
|
||||
cpp_sources=minmax_cpp_source,
|
||||
cuda_sources=minmax_source,
|
||||
functions=["minmax_cuda"],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.module = module
|
||||
|
||||
def forward(self, x):
|
||||
return self.module.minmax_cuda(x)
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
min_val = x.min()
|
||||
max_val = x.max()
|
||||
|
||||
|
||||
scale = (max_val - min_val) / 255.0
|
||||
return scale
|
||||
|
||||
|
||||
shape = (16, 2048, 1024)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(shape, dtype=torch.float32).cuda()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
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
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
min_val = x.min()
|
||||
max_val = x.max()
|
||||
|
||||
|
||||
scale = (max_val - min_val) / 255.0
|
||||
return scale
|
||||
|
||||
|
||||
shape = (16, 2048, 1024)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(shape, dtype=torch.float32).cuda()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from minmax_observer_torch import Model,get_inputs,get_init_inputs
|
||||
from minmax_observer_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()
|
||||
Loading…
Reference in New Issue