forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish SobelEdgeDetection #92' (#656) from ZZZJ/GPUCodeForces:SobelEdgeDetection into main
This commit is contained in:
commit
2c0bf6ffde
|
|
@ -0,0 +1,44 @@
|
|||
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 = 16
|
||||
CHANNELS = 1
|
||||
HEIGHT = 1024
|
||||
WIDTH = 1024
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.register_buffer('gx', torch.tensor([
|
||||
[-1, 0, 1],
|
||||
[-2, 0, 2],
|
||||
[-1, 0, 1]
|
||||
], dtype=torch.float32).view(1, 1, 3, 3))
|
||||
|
||||
self.register_buffer('gy', torch.tensor([
|
||||
[-1, -2, -1],
|
||||
[ 0, 0, 0],
|
||||
[ 1, 2, 1]
|
||||
], dtype=torch.float32).view(1, 1, 3, 3))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
g_x = F.conv2d(x, self.gx, padding=1)
|
||||
g_y = F.conv2d(x, self.gy, padding=1)
|
||||
|
||||
return g_x**2 + g_y**2
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randint(0, 256, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from sobel_edge_detection_torch import Model,get_inputs,get_init_inputs
|
||||
from sobel_edge_detection_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()
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
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 sobel_cuda(torch::Tensor input);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#define BLOCK_W 32
|
||||
#define BLOCK_H 8
|
||||
|
||||
|
||||
__global__ void sobel_squared_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int batch,
|
||||
int height,
|
||||
int width
|
||||
) {
|
||||
int w = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int h = blockIdx.y * blockDim.y + threadIdx.y;
|
||||
int b = blockIdx.z;
|
||||
|
||||
if (w >= width || h >= height || b >= batch) return;
|
||||
|
||||
long long offset = (long long)b * (height * width);
|
||||
const float* in_ptr = input + offset;
|
||||
float* out_ptr = output + offset;
|
||||
|
||||
|
||||
float val[3][3];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = -1; i <= 1; ++i) {
|
||||
#pragma unroll
|
||||
for (int j = -1; j <= 1; ++j) {
|
||||
int r = h + i;
|
||||
int c = w + j;
|
||||
|
||||
|
||||
if (r >= 0 && r < height && c >= 0 && c < width) {
|
||||
val[i+1][j+1] = in_ptr[r * width + c];
|
||||
} else {
|
||||
val[i+1][j+1] = 0.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
float gx = -val[0][0] + val[0][2]
|
||||
-val[1][0] - val[1][0] + val[1][2] + val[1][2] // 2*x -> x+x
|
||||
-val[2][0] + val[2][2];
|
||||
|
||||
|
||||
float gy = -val[0][0] - val[0][1] - val[0][1] - val[0][2]
|
||||
+val[2][0] + val[2][1] + val[2][1] + val[2][2];
|
||||
|
||||
|
||||
out_ptr[h * width + w] = gx * gx + gy * gy;
|
||||
}
|
||||
|
||||
torch::Tensor sobel_cuda(torch::Tensor input) {
|
||||
int batch = input.size(0);
|
||||
int height = input.size(2);
|
||||
int width = input.size(3);
|
||||
|
||||
auto output = torch::empty_like(input);
|
||||
|
||||
dim3 block(BLOCK_W, BLOCK_H);
|
||||
dim3 grid(
|
||||
(width + BLOCK_W - 1) / BLOCK_W,
|
||||
(height + BLOCK_H - 1) / BLOCK_H,
|
||||
batch
|
||||
);
|
||||
|
||||
sobel_squared_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch, height, width
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="sobel_squared_v3",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["sobel_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.sobel_cuda(x)
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
BATCH = 16
|
||||
CHANNELS = 1
|
||||
HEIGHT = 1024
|
||||
WIDTH = 1024
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.register_buffer('gx', torch.tensor([
|
||||
[-1, 0, 1],
|
||||
[-2, 0, 2],
|
||||
[-1, 0, 1]
|
||||
], dtype=torch.float32).view(1, 1, 3, 3))
|
||||
|
||||
self.register_buffer('gy', torch.tensor([
|
||||
[-1, -2, -1],
|
||||
[ 0, 0, 0],
|
||||
[ 1, 2, 1]
|
||||
], dtype=torch.float32).view(1, 1, 3, 3))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
g_x = F.conv2d(x, self.gx, padding=1)
|
||||
g_y = F.conv2d(x, self.gy, padding=1)
|
||||
|
||||
return g_x**2 + g_y**2
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randint(0, 256, size=(BATCH, CHANNELS, HEIGHT, WIDTH), device='cuda').float()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
Loading…
Reference in New Issue