Compare commits
1 Commits
main
...
Correrlati
| Author | SHA1 | Date |
|---|---|---|
|
|
15d1baa1ce |
|
|
@ -0,0 +1,118 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
corr_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
|
||||
__global__ void correlation_kernel(
|
||||
const float* __restrict__ fmap1,
|
||||
const float* __restrict__ fmap2,
|
||||
float* __restrict__ output,
|
||||
int B, int C, int H, int W,
|
||||
int max_displacement)
|
||||
{
|
||||
// Grid X: Spatial (H*W)
|
||||
// Grid Y: Batch
|
||||
int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int b = blockIdx.y;
|
||||
|
||||
int area = H * W;
|
||||
if (spatial_idx >= area || b >= B) return;
|
||||
|
||||
// Decode coords
|
||||
int h = spatial_idx / W;
|
||||
int w = spatial_idx % W;
|
||||
|
||||
// Kernel params
|
||||
int k_size = 2 * max_displacement + 1;
|
||||
int out_channels = k_size * k_size;
|
||||
|
||||
long batch_offset = (long)b * C * H * W;
|
||||
const float* f1_ptr = fmap1 + batch_offset;
|
||||
const float* f2_ptr = fmap2 + batch_offset;
|
||||
|
||||
float* out_ptr = output + (long)b * out_channels * H * W;
|
||||
int out_c = 0;
|
||||
for (int dy = -max_displacement; dy <= max_displacement; ++dy) {
|
||||
for (int dx = -max_displacement; dx <= max_displacement; ++dx) {
|
||||
|
||||
int h2 = h + dy;
|
||||
int w2 = w + dx;
|
||||
|
||||
float dot_prod = 0.0f;
|
||||
|
||||
if (h2 >= 0 && h2 < H && w2 >= 0 && w2 < W) {
|
||||
// Compute Dot Product over C
|
||||
int offset1 = h * W + w;
|
||||
int offset2 = h2 * W + w2;
|
||||
|
||||
// Unroll loop manually
|
||||
for (int c = 0; c < C; ++c) {
|
||||
float v1 = f1_ptr[c * area + offset1];
|
||||
float v2 = f2_ptr[c * area + offset2];
|
||||
dot_prod += v1 * v2;
|
||||
}
|
||||
} else {
|
||||
// Padding (0)
|
||||
dot_prod = 0.0f;
|
||||
}
|
||||
|
||||
// Output Layout: [B, Out_C, H, W]
|
||||
// out_idx = out_c * (H*W) + spatial_idx
|
||||
long out_idx = (long)out_c * area + spatial_idx;
|
||||
out_ptr[out_idx] = dot_prod;
|
||||
|
||||
out_c++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor correlation_cuda(torch::Tensor fmap1, torch::Tensor fmap2, int max_displacement) {
|
||||
int B = fmap1.size(0);
|
||||
int C = fmap1.size(1);
|
||||
int H = fmap1.size(2);
|
||||
int W = fmap1.size(3);
|
||||
|
||||
int k_size = 2 * max_displacement + 1;
|
||||
int out_channels = k_size * k_size;
|
||||
|
||||
// Output: [B, out_channels, H, W]
|
||||
auto output = torch::empty({B, out_channels, H, W}, fmap1.options());
|
||||
|
||||
int spatial = H * W;
|
||||
const int block = 256;
|
||||
dim3 grid((spatial + block - 1) / block, B);
|
||||
|
||||
correlation_kernel<<<grid, block>>>(
|
||||
fmap1.data_ptr<float>(),
|
||||
fmap2.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
B, C, H, W,
|
||||
max_displacement
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor correlation_cuda(torch::Tensor fmap1, torch::Tensor fmap2, int max_displacement);"
|
||||
|
||||
corr_module = load_inline(
|
||||
name="correlation_extension",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=corr_source,
|
||||
functions=["correlation_cuda"],
|
||||
verbose=True,
|
||||
with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.max_disp = 4
|
||||
self.cuda_op = corr_module
|
||||
|
||||
def forward(self, f1, f2):
|
||||
return self.cuda_op.correlation_cuda(f1.contiguous(), f2.contiguous(), self.max_disp)
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.max_displacement = 4
|
||||
self.stride = 1
|
||||
|
||||
self.k_size = 2 * self.max_displacement + 1
|
||||
|
||||
def forward(self, fmap1: torch.Tensor, fmap2: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
B, C, H, W = fmap1.shape
|
||||
|
||||
fmap2_unfold = F.unfold(
|
||||
fmap2,
|
||||
kernel_size=self.k_size,
|
||||
padding=self.max_displacement,
|
||||
stride=self.stride
|
||||
)
|
||||
|
||||
fmap2_unfold = fmap2_unfold.view(B, C, self.k_size * self.k_size, H, W)
|
||||
|
||||
|
||||
cost_vol = (fmap1.unsqueeze(2) * fmap2_unfold).sum(dim=1)
|
||||
|
||||
return cost_vol
|
||||
|
||||
B = 4
|
||||
C = 64
|
||||
H = 64
|
||||
W = 64
|
||||
|
||||
def get_inputs():
|
||||
|
||||
f2 = torch.randint(-2, 3, (B, C, H, W), device='cuda').float()
|
||||
return [f1, f2]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
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
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.max_displacement = 4
|
||||
self.stride = 1
|
||||
|
||||
self.k_size = 2 * self.max_displacement + 1
|
||||
|
||||
def forward(self, fmap1: torch.Tensor, fmap2: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
B, C, H, W = fmap1.shape
|
||||
|
||||
fmap2_unfold = F.unfold(
|
||||
fmap2,
|
||||
kernel_size=self.k_size,
|
||||
padding=self.max_displacement,
|
||||
stride=self.stride
|
||||
)
|
||||
|
||||
fmap2_unfold = fmap2_unfold.view(B, C, self.k_size * self.k_size, H, W)
|
||||
|
||||
|
||||
cost_vol = (fmap1.unsqueeze(2) * fmap2_unfold).sum(dim=1)
|
||||
|
||||
return cost_vol
|
||||
|
||||
B = 4
|
||||
C = 64
|
||||
H = 64
|
||||
W = 64
|
||||
|
||||
def get_inputs():
|
||||
|
||||
f2 = torch.randint(-2, 3, (B, C, H, W), device='cuda').float()
|
||||
return [f1, f2]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from correlation_torch import Model,get_inputs,get_init_inputs
|
||||
from correlation_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