forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish CropResize #190' (#927) from ZZZJ/GPUCodeForces:CropResize into main
This commit is contained in:
commit
b9d4f34cb1
|
|
@ -0,0 +1,103 @@
|
|||
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._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor crop_resize_cuda(torch::Tensor input, int out_h, int out_w, int y1, int x1, int h_crop, int w_crop);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
__global__ void crop_resize_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int batch, int channels, int in_h, int in_w,
|
||||
int out_h, int out_w,
|
||||
float scale_y, float scale_x,
|
||||
int offset_y, int offset_x
|
||||
) {
|
||||
int ow = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int oh = blockIdx.y * blockDim.y + threadIdx.y;
|
||||
int bc = blockIdx.z;
|
||||
|
||||
if (ow >= out_w || oh >= out_h || bc >= batch * channels) return;
|
||||
|
||||
float real_y = (oh + 0.5f) * scale_y - 0.5f + offset_y;
|
||||
float real_x = (ow + 0.5f) * scale_x - 0.5f + offset_x;
|
||||
|
||||
int y_low = floorf(real_y);
|
||||
int x_low = floorf(real_x);
|
||||
int y_high = y_low + 1;
|
||||
int x_high = x_low + 1;
|
||||
|
||||
float ly = real_y - y_low;
|
||||
float lx = real_x - x_low;
|
||||
float hy = 1.0f - ly;
|
||||
float hx = 1.0f - lx;
|
||||
|
||||
y_low = max(0, min(y_low, in_h-1));
|
||||
y_high = max(0, min(y_high, in_h-1));
|
||||
x_low = max(0, min(x_low, in_w-1));
|
||||
x_high = max(0, min(x_high, in_w-1));
|
||||
|
||||
long long plane_offset = (long long)bc * in_h * in_w;
|
||||
float v00 = input[plane_offset + y_low * in_w + x_low];
|
||||
float v01 = input[plane_offset + y_low * in_w + x_high];
|
||||
float v10 = input[plane_offset + y_high * in_w + x_low];
|
||||
float v11 = input[plane_offset + y_high * in_w + x_high];
|
||||
|
||||
float val = v00 * hy * hx + v01 * hy * lx + v10 * ly * hx + v11 * ly * lx;
|
||||
|
||||
long long out_offset = (long long)bc * out_h * out_w + oh * out_w + ow;
|
||||
output[out_offset] = val;
|
||||
}
|
||||
|
||||
torch::Tensor crop_resize_cuda(torch::Tensor input, int out_h, int out_w, int y1, int x1, int h_crop, int w_crop) {
|
||||
int batch = input.size(0);
|
||||
int channels = input.size(1);
|
||||
int in_h = input.size(2);
|
||||
int in_w = input.size(3);
|
||||
|
||||
auto output = torch::empty({batch, channels, out_h, out_w}, input.options());
|
||||
|
||||
float scale_y = (float)h_crop / out_h;
|
||||
float scale_x = (float)w_crop / out_w;
|
||||
|
||||
dim3 block(16, 16);
|
||||
dim3 grid(
|
||||
(out_w + 15)/16,
|
||||
(out_h + 15)/16,
|
||||
batch * channels
|
||||
);
|
||||
|
||||
crop_resize_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch, channels, in_h, in_w, out_h, out_w,
|
||||
scale_y, scale_x, y1, x1
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="crop_resize_opt",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["crop_resize_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.crop_resize_cuda(x, 128, 128, 100, 100, 300, 300)
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
BATCH = 64
|
||||
CHANNELS = 3
|
||||
H_IN, W_IN = 512, 512
|
||||
H_OUT, W_OUT = 128, 128
|
||||
BOX = [100, 100, 400, 400] # y1, x1, y2, x2
|
||||
|
||||
class Model(nn.Module):
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return F.interpolate(x[..., BOX[0]:BOX[2], BOX[1]:BOX[3]], size=(H_OUT, W_OUT), mode='bilinear', align_corners=False)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.rand(BATCH, CHANNELS, H_IN, W_IN, device='cuda', dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
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
|
||||
import torch.nn.functional as F
|
||||
|
||||
BATCH = 64
|
||||
CHANNELS = 3
|
||||
H_IN, W_IN = 512, 512
|
||||
H_OUT, W_OUT = 128, 128
|
||||
BOX = [100, 100, 400, 400] # y1, x1, y2, x2
|
||||
|
||||
class Model(nn.Module):
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return F.interpolate(x[..., BOX[0]:BOX[2], BOX[1]:BOX[3]], size=(H_OUT, W_OUT), mode='bilinear', align_corners=False)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.rand(BATCH, CHANNELS, H_IN, W_IN, device='cuda', dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from crop_resize_torch import Model,get_inputs,get_init_inputs
|
||||
from crop_resize_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