Compare commits
1 Commits
main
...
AffineGrid
| Author | SHA1 | Date |
|---|---|---|
|
|
7ba8e2e027 |
|
|
@ -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 affine_grid_cuda(torch::Tensor theta, int N, int H, int W);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
|
||||
|
||||
__global__ void affine_grid_f4_kernel(
|
||||
const float* __restrict__ theta,
|
||||
float* __restrict__ grid,
|
||||
int n_vecs,
|
||||
int N, int H, int W
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx >= n_vecs) return;
|
||||
|
||||
|
||||
int vec_dim = W / 2;
|
||||
|
||||
int w_pair = idx % vec_dim;
|
||||
int tmp = idx / vec_dim;
|
||||
int h = tmp % H;
|
||||
int n = tmp / H;
|
||||
|
||||
int w0 = w_pair * 2;
|
||||
int w1 = w0 + 1;
|
||||
|
||||
double t00 = (double)t_ptr[0];
|
||||
double t01 = (double)t_ptr[1];
|
||||
double t02 = (double)t_ptr[2];
|
||||
double t10 = (double)t_ptr[3];
|
||||
double t11 = (double)t_ptr[4];
|
||||
double t12 = (double)t_ptr[5];
|
||||
|
||||
|
||||
// align_corners=True: -1 + 2*i/(size-1)
|
||||
double inv_h = 2.0 / (H - 1.0);
|
||||
double inv_w = 2.0 / (W - 1.0);
|
||||
|
||||
double y = h * inv_h - 1.0;
|
||||
double x0 = w0 * inv_w - 1.0;
|
||||
double x1 = w1 * inv_w - 1.0;
|
||||
|
||||
// Pixel 0
|
||||
float px0 = (float)(t00 * x0 + t01 * y + t02);
|
||||
float py0 = (float)(t10 * x0 + t11 * y + t12);
|
||||
|
||||
// Pixel 1
|
||||
float px1 = (float)(t00 * x1 + t01 * y + t02);
|
||||
float py1 = (float)(t10 * x1 + t11 * y + t12);
|
||||
|
||||
float4 out_val;
|
||||
out_val.x = px0;
|
||||
out_val.y = py0;
|
||||
out_val.z = px1;
|
||||
out_val.w = py1;
|
||||
|
||||
reinterpret_cast<float4*>(grid)[idx] = out_val;
|
||||
}
|
||||
|
||||
torch::Tensor affine_grid_cuda(torch::Tensor theta, int N, int H, int W) {
|
||||
auto output = torch::empty({N, H, W, 2}, theta.options());
|
||||
|
||||
if (W % 2 != 0) return output;
|
||||
|
||||
int n_vecs = N * H * (W / 2);
|
||||
|
||||
const int block_size = 256;
|
||||
const int grid_size = (n_vecs + block_size - 1) / block_size;
|
||||
|
||||
affine_grid_f4_kernel<<<grid_size, block_size>>>(
|
||||
theta.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
n_vecs,
|
||||
N, H, W
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="affine_grid_f4_identity",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["affine_grid_cuda"],
|
||||
extra_cuda_cflags=["-O3"], # No fast_math
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, theta: torch.Tensor) -> torch.Tensor:
|
||||
N, _, _ = theta.shape
|
||||
return self.op.affine_grid_cuda(theta, N, 512, 512)
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
BATCH = 64
|
||||
HEIGHT = 512
|
||||
WIDTH = 512
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, theta: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return F.affine_grid(theta, size=(BATCH, 1, HEIGHT, WIDTH), align_corners=True)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
theta = torch.tensor([
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0]
|
||||
], dtype=torch.float32, device='cuda')
|
||||
|
||||
theta = theta.unsqueeze(0).repeat(BATCH, 1, 1)
|
||||
|
||||
return [theta]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
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
|
||||
HEIGHT = 512
|
||||
WIDTH = 512
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, theta: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return F.affine_grid(theta, size=(BATCH, 1, HEIGHT, WIDTH), align_corners=True)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
theta = torch.tensor([
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0]
|
||||
], dtype=torch.float32, device='cuda')
|
||||
|
||||
theta = theta.unsqueeze(0).repeat(BATCH, 1, 1)
|
||||
|
||||
return [theta]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from affine_grid2d_torch import Model,get_inputs,get_init_inputs
|
||||
from affine_grid2d_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