Merge pull request 'finish RoiPool #155' (#815) from ZZZJ/GPUCodeForces:RoiPool into main

This commit is contained in:
wawahejun 2025-12-14 22:05:04 +08:00
commit 6d7e6dc429
4 changed files with 297 additions and 0 deletions

49
S1/ZZZJ_#155/prompt.txt Normal file
View File

@ -0,0 +1,49 @@
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 torchvision
class Model(nn.Module):
def __init__(self, output_size=(7, 7), spatial_scale=1.0):
super().__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
def forward(self, input, rois):
return torchvision.ops.roi_pool(
input, rois,
output_size=self.output_size,
spatial_scale=self.spatial_scale
)
N = 4
C = 256
H = 128
W = 128
K = 1000
def get_inputs():
x = torch.randn(N, C, H, W, dtype=torch.float32)
rois = torch.zeros(K, 5, dtype=torch.float32)
rois[:, 0] = torch.randint(0, N, (K,)).float()
x1 = torch.rand(K) * (W // 2)
y1 = torch.rand(K) * (H // 2)
x2 = x1 + torch.rand(K) * (W // 2) + 2.0
y2 = y1 + torch.rand(K) * (H // 2) + 2.0
rois[:, 1] = x1
rois[:, 2] = y1
rois[:, 3] = x2
rois[:, 4] = y2
return [x, rois]
def get_init_inputs():
return [(7, 7), 1.0]

View File

@ -0,0 +1,132 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cpp_src = """
torch::Tensor roi_pool_cuda(torch::Tensor input, torch::Tensor rois, double spatial_scale, int pooled_height, int pooled_width);
"""
cuda_src = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cfloat>
__global__ void roi_pool_forward_kernel(
const int nthreads,
const float* input,
const float* rois,
float* output,
const float spatial_scale,
const int channels,
const int height,
const int width,
const int pooled_height,
const int pooled_width) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= nthreads) return;
int pw = index % pooled_width;
int ph = (index / pooled_width) % pooled_height;
int c = (index / pooled_width / pooled_height) % channels;
int n = index / pooled_width / pooled_height / channels;
const float* offset_rois = rois + n * 5;
int roi_batch_ind = offset_rois[0];
int roi_start_w = round(offset_rois[1] * spatial_scale);
int roi_start_h = round(offset_rois[2] * spatial_scale);
int roi_end_w = round(offset_rois[3] * spatial_scale);
int roi_end_h = round(offset_rois[4] * spatial_scale);
int roi_width = max(roi_end_w - roi_start_w + 1, 1);
int roi_height = max(roi_end_h - roi_start_h + 1, 1);
const float bin_size_h = (float)roi_height / (float)pooled_height;
const float bin_size_w = (float)roi_width / (float)pooled_width;
int hstart = (int)(floor((float)(ph) * bin_size_h));
int wstart = (int)(floor((float)(pw) * bin_size_w));
int hend = (int)(ceil((float)(ph + 1) * bin_size_h));
int wend = (int)(ceil((float)(pw + 1) * bin_size_w));
hstart = min(max(hstart + roi_start_h, 0), height);
hend = min(max(hend + roi_start_h, 0), height);
wstart = min(max(wstart + roi_start_w, 0), width);
wend = min(max(wend + roi_start_w, 0), width);
bool is_empty = (hend <= hstart) || (wend <= wstart);
const float* offset_input = input + (roi_batch_ind * channels + c) * height * width;
float max_val = is_empty ? 0 : -FLT_MAX;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
float val = offset_input[h * width + w];
if (val > max_val) {
max_val = val;
}
}
}
output[index] = max_val;
}
torch::Tensor roi_pool_cuda(torch::Tensor input, torch::Tensor rois, double spatial_scale, int pooled_height, int pooled_width) {
int num_rois = rois.size(0);
int channels = input.size(1);
int height = input.size(2);
int width = input.size(3);
auto output = torch::zeros({num_rois, channels, pooled_height, pooled_width}, input.options());
int output_size = num_rois * channels * pooled_height * pooled_width;
input = input.contiguous();
rois = rois.contiguous();
const int block_size = 512;
int grid_size = (output_size + block_size - 1) / block_size;
if (grid_size > 2147483647) grid_size = 2147483647;
roi_pool_forward_kernel<<<grid_size, block_size>>>(
output_size,
input.data_ptr<float>(),
rois.data_ptr<float>(),
output.data_ptr<float>(),
(float)spatial_scale,
channels,
height,
width,
pooled_height,
pooled_width
);
return output;
}
"""
class ModelNew(nn.Module):
def __init__(self, output_size=(7, 7), spatial_scale=1.0):
super().__init__()
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
self.output_size = output_size
self.spatial_scale = spatial_scale
self.module = load_inline(
name="roi_pool_opt",
cpp_sources=cpp_src,
cuda_sources=cuda_src,
functions=["roi_pool_cuda"],
verbose=False,
extra_cuda_cflags=["-O3"]
)
def forward(self, input, rois):
return self.module.roi_pool_cuda(
input, rois, self.spatial_scale,
self.output_size[0], self.output_size[1]
)

View File

@ -0,0 +1,42 @@
import torch
import torch.nn as nn
import torchvision
class Model(nn.Module):
def __init__(self, output_size=(7, 7), spatial_scale=1.0):
super().__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
def forward(self, input, rois):
return torchvision.ops.roi_pool(
input, rois,
output_size=self.output_size,
spatial_scale=self.spatial_scale
)
N = 4
C = 256
H = 128
W = 128
K = 1000
def get_inputs():
x = torch.randn(N, C, H, W, dtype=torch.float32)
rois = torch.zeros(K, 5, dtype=torch.float32)
rois[:, 0] = torch.randint(0, N, (K,)).float()
x1 = torch.rand(K) * (W // 2)
y1 = torch.rand(K) * (H // 2)
x2 = x1 + torch.rand(K) * (W // 2) + 2.0
y2 = y1 + torch.rand(K) * (H // 2) + 2.0
rois[:, 1] = x1
rois[:, 2] = y1
rois[:, 3] = x2
rois[:, 4] = y2
return [x, rois]
def get_init_inputs():
return [(7, 7), 1.0]

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

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