forked from ccf-ai-infra/GPUCodeForces
fixes AlphaIou #16
This commit is contained in:
parent
cc73715277
commit
bb0288dd3d
|
|
@ -0,0 +1,109 @@
|
|||
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.alpha = 3.0
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor pairwise_alpha_iou_cuda(torch::Tensor boxes1, torch::Tensor boxes2, float alpha);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_DIM 16
|
||||
|
||||
|
||||
__global__ void pairwise_alpha_iou_f4_kernel(
|
||||
const float* __restrict__ boxes1,
|
||||
const float* __restrict__ boxes2,
|
||||
float* __restrict__ output,
|
||||
int n, int m,
|
||||
float alpha
|
||||
) {
|
||||
// 2D Grid Mapping
|
||||
int col = blockIdx.x * blockDim.x + threadIdx.x; // M (box2)
|
||||
int row = blockIdx.y * blockDim.y + threadIdx.y; // N (box1)
|
||||
|
||||
if (row >= n || col >= m) return;
|
||||
|
||||
// 1. Float4 Load Box1 (Row)
|
||||
// boxes1: [N, 4]
|
||||
float4 b1 = reinterpret_cast<const float4*>(boxes1)[row];
|
||||
|
||||
// 2. Float4 Load Box2 (Col)
|
||||
// boxes2: [M, 4]
|
||||
float4 b2 = reinterpret_cast<const float4*>(boxes2)[col];
|
||||
|
||||
// b: x1, y1, x2, y2
|
||||
|
||||
// 3. Compute Area
|
||||
float area1 = (b1.z - b1.x) * (b1.w - b1.y);
|
||||
float area2 = (b2.z - b2.x) * (b2.w - b2.y);
|
||||
|
||||
// 4. Compute Intersection
|
||||
float inter_x1 = fmaxf(b1.x, b2.x);
|
||||
float inter_y1 = fmaxf(b1.y, b2.y);
|
||||
float inter_x2 = fminf(b1.z, b2.z);
|
||||
float inter_y2 = fminf(b1.w, b2.w);
|
||||
|
||||
float inter_w = fmaxf(0.0f, inter_x2 - inter_x1);
|
||||
float inter_h = fmaxf(0.0f, inter_y2 - inter_y1);
|
||||
float inter_area = inter_w * inter_h;
|
||||
|
||||
// 5. Compute Union & IoU
|
||||
float union_area = area1 + area2 - inter_area;
|
||||
|
||||
// 1e-7f epsilon
|
||||
float iou = inter_area / (union_area + 1e-7f);
|
||||
|
||||
// 6. Alpha-IoU: 1 - IoU^alpha
|
||||
float loss = 1.0f - powf(iou, alpha);
|
||||
|
||||
// 7. Write Output
|
||||
output[row * m + col] = loss;
|
||||
}
|
||||
|
||||
torch::Tensor pairwise_alpha_iou_cuda(torch::Tensor boxes1, torch::Tensor boxes2, float alpha) {
|
||||
int n = boxes1.size(0);
|
||||
int m = boxes2.size(0);
|
||||
|
||||
auto output = torch::empty({n, m}, boxes1.options());
|
||||
|
||||
dim3 block(BLOCK_DIM, BLOCK_DIM);
|
||||
dim3 grid(
|
||||
(m + BLOCK_DIM - 1) / BLOCK_DIM,
|
||||
(n + BLOCK_DIM - 1) / BLOCK_DIM
|
||||
);
|
||||
|
||||
pairwise_alpha_iou_f4_kernel<<<grid, block>>>(
|
||||
boxes1.data_ptr<float>(),
|
||||
boxes2.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
n, m, alpha
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="pairwise_alpha_iou_fast",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["pairwise_alpha_iou_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
|
||||
if not boxes1.is_contiguous(): boxes1 = boxes1.contiguous()
|
||||
if not boxes2.is_contiguous(): boxes2 = boxes2.contiguous()
|
||||
return self.op.pairwise_alpha_iou_cuda(boxes1, boxes2, self.alpha)
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
N = 4096
|
||||
M = 4096
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.alpha = 3.0
|
||||
|
||||
def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
|
||||
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
|
||||
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
|
||||
|
||||
lt = torch.max(boxes1[:, None, :2], boxes2[None, :, :2])
|
||||
rb = torch.min(boxes1[:, None, 2:], boxes2[None, :, 2:])
|
||||
|
||||
wh = (rb - lt).clamp(min=0)
|
||||
inter = wh[:, :, 0] * wh[:, :, 1]
|
||||
|
||||
union = area1[:, None] + area2[None, :] - inter
|
||||
|
||||
iou = inter / (union + 1e-7)
|
||||
|
||||
|
||||
loss = 1.0 - torch.pow(iou, self.alpha)
|
||||
|
||||
return loss
|
||||
|
||||
def get_inputs():
|
||||
|
||||
b1_raw = torch.randint(0, 100, (N, 4), device='cuda').float()
|
||||
b1_x1, _ = torch.min(b1_raw[:, [0, 2]], dim=1)
|
||||
b1_x2, _ = torch.max(b1_raw[:, [0, 2]], dim=1)
|
||||
b1_y1, _ = torch.min(b1_raw[:, [1, 3]], dim=1)
|
||||
b1_y2, _ = torch.max(b1_raw[:, [1, 3]], dim=1)
|
||||
b1_x2 = torch.max(b1_x2, b1_x1 + 1)
|
||||
b1_y2 = torch.max(b1_y2, b1_y1 + 1)
|
||||
boxes1 = torch.stack([b1_x1, b1_y1, b1_x2, b1_y2], dim=1)
|
||||
|
||||
b2_raw = torch.randint(0, 100, (M, 4), device='cuda').float()
|
||||
b2_x1, _ = torch.min(b2_raw[:, [0, 2]], dim=1)
|
||||
b2_x2, _ = torch.max(b2_raw[:, [0, 2]], dim=1)
|
||||
b2_y1, _ = torch.min(b2_raw[:, [1, 3]], dim=1)
|
||||
b2_y2, _ = torch.max(b2_raw[:, [1, 3]], dim=1)
|
||||
b2_x2 = torch.max(b2_x2, b2_x1 + 1)
|
||||
b2_y2 = torch.max(b2_y2, b2_y1 + 1)
|
||||
boxes2 = torch.stack([b2_x1, b2_y1, b2_x2, b2_y2], dim=1)
|
||||
|
||||
return [boxes1, boxes2]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
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
|
||||
|
||||
|
||||
N = 4096
|
||||
M = 4096
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.alpha = 3.0
|
||||
|
||||
def forward(self, boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
|
||||
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
|
||||
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
|
||||
|
||||
lt = torch.max(boxes1[:, None, :2], boxes2[None, :, :2])
|
||||
rb = torch.min(boxes1[:, None, 2:], boxes2[None, :, 2:])
|
||||
|
||||
wh = (rb - lt).clamp(min=0)
|
||||
inter = wh[:, :, 0] * wh[:, :, 1]
|
||||
|
||||
union = area1[:, None] + area2[None, :] - inter
|
||||
|
||||
iou = inter / (union + 1e-7)
|
||||
|
||||
|
||||
loss = 1.0 - torch.pow(iou, self.alpha)
|
||||
|
||||
return loss
|
||||
|
||||
def get_inputs():
|
||||
|
||||
b1_raw = torch.randint(0, 100, (N, 4), device='cuda').float()
|
||||
b1_x1, _ = torch.min(b1_raw[:, [0, 2]], dim=1)
|
||||
b1_x2, _ = torch.max(b1_raw[:, [0, 2]], dim=1)
|
||||
b1_y1, _ = torch.min(b1_raw[:, [1, 3]], dim=1)
|
||||
b1_y2, _ = torch.max(b1_raw[:, [1, 3]], dim=1)
|
||||
b1_x2 = torch.max(b1_x2, b1_x1 + 1)
|
||||
b1_y2 = torch.max(b1_y2, b1_y1 + 1)
|
||||
boxes1 = torch.stack([b1_x1, b1_y1, b1_x2, b1_y2], dim=1)
|
||||
|
||||
b2_raw = torch.randint(0, 100, (M, 4), device='cuda').float()
|
||||
b2_x1, _ = torch.min(b2_raw[:, [0, 2]], dim=1)
|
||||
b2_x2, _ = torch.max(b2_raw[:, [0, 2]], dim=1)
|
||||
b2_y1, _ = torch.min(b2_raw[:, [1, 3]], dim=1)
|
||||
b2_y2, _ = torch.max(b2_raw[:, [1, 3]], dim=1)
|
||||
b2_x2 = torch.max(b2_x2, b2_x1 + 1)
|
||||
b2_y2 = torch.max(b2_y2, b2_y1 + 1)
|
||||
boxes2 = torch.stack([b2_x1, b2_y1, b2_x2, b2_y2], dim=1)
|
||||
|
||||
return [boxes1, boxes2]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from alpha_iou_torch import Model,get_inputs,get_init_inputs
|
||||
from alpha_iou_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