forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish BayerToRgb #37' (#580) from ZZZJ/GPUCodeForces:BayerToRgb into main
This commit is contained in:
commit
bcbe74acec
|
|
@ -0,0 +1,121 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
bayer_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
// Helper with boundary clamp
|
||||
__device__ __forceinline__ float get_val(const float* src, int n, int h, int w, int N, int H, int W) {
|
||||
h = max(0, min(h, H - 1));
|
||||
w = max(0, min(w, W - 1));
|
||||
return src[n * (H * W) + h * W + w];
|
||||
}
|
||||
|
||||
__global__ void bayer_to_rgb_kernel(const float* __restrict__ input, float* __restrict__ output, int N, int H, int W) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int total_pixels = N * H * W;
|
||||
|
||||
if (idx < total_pixels) {
|
||||
int tmp = idx;
|
||||
int w = tmp % W;
|
||||
tmp /= W;
|
||||
int h = tmp % H;
|
||||
int n = tmp / H;
|
||||
|
||||
float val = input[idx];
|
||||
|
||||
// Pattern RGGB
|
||||
bool row_even = (h % 2 == 0);
|
||||
bool col_even = (w % 2 == 0);
|
||||
|
||||
float r_out, g_out, b_out;
|
||||
|
||||
if (row_even && col_even) { // R
|
||||
r_out = val;
|
||||
float u = get_val(input, n, h-1, w, N,H,W);
|
||||
float d = get_val(input, n, h+1, w, N,H,W);
|
||||
float l = get_val(input, n, h, w-1, N,H,W);
|
||||
float r = get_val(input, n, h, w+1, N,H,W);
|
||||
g_out = (u + d + l + r) * 0.25f;
|
||||
|
||||
float ul = get_val(input, n, h-1, w-1, N,H,W);
|
||||
float ur = get_val(input, n, h-1, w+1, N,H,W);
|
||||
float bl = get_val(input, n, h+1, w-1, N,H,W);
|
||||
float br = get_val(input, n, h+1, w+1, N,H,W);
|
||||
b_out = (ul + ur + bl + br) * 0.25f;
|
||||
|
||||
} else if (row_even && !col_even) { // G (R row)
|
||||
g_out = val;
|
||||
float l = get_val(input, n, h, w-1, N,H,W);
|
||||
float r = get_val(input, n, h, w+1, N,H,W);
|
||||
r_out = (l + r) * 0.5f;
|
||||
float u = get_val(input, n, h-1, w, N,H,W);
|
||||
float d = get_val(input, n, h+1, w, N,H,W);
|
||||
b_out = (u + d) * 0.5f;
|
||||
|
||||
} else if (!row_even && col_even) { // G (B row)
|
||||
g_out = val;
|
||||
float u = get_val(input, n, h-1, w, N,H,W);
|
||||
float d = get_val(input, n, h+1, w, N,H,W);
|
||||
r_out = (u + d) * 0.5f;
|
||||
float l = get_val(input, n, h, w-1, N,H,W);
|
||||
float r = get_val(input, n, h, w+1, N,H,W);
|
||||
b_out = (l + r) * 0.5f;
|
||||
|
||||
} else { // B
|
||||
b_out = val;
|
||||
float ul = get_val(input, n, h-1, w-1, N,H,W);
|
||||
float ur = get_val(input, n, h-1, w+1, N,H,W);
|
||||
float bl = get_val(input, n, h+1, w-1, N,H,W);
|
||||
float br = get_val(input, n, h+1, w+1, N,H,W);
|
||||
r_out = (ul + ur + bl + br) * 0.25f;
|
||||
|
||||
float u = get_val(input, n, h-1, w, N,H,W);
|
||||
float d = get_val(input, n, h+1, w, N,H,W);
|
||||
float l = get_val(input, n, h, w-1, N,H,W);
|
||||
float r = get_val(input, n, h, w+1, N,H,W);
|
||||
g_out = (u + d + l + r) * 0.25f;
|
||||
}
|
||||
|
||||
int out_base = idx * 3;
|
||||
output[out_base] = r_out;
|
||||
output[out_base + 1] = g_out;
|
||||
output[out_base + 2] = b_out;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor bayer_to_rgb_cuda(torch::Tensor input) {
|
||||
int N = input.size(0);
|
||||
int H = input.size(1);
|
||||
int W = input.size(2);
|
||||
auto output = torch::empty({N, H, W, 3}, input.options());
|
||||
|
||||
int total = N * H * W;
|
||||
const int block = 256;
|
||||
const int num_blocks = (total + block - 1) / block;
|
||||
|
||||
bayer_to_rgb_kernel<<<num_blocks, block>>>(
|
||||
input.data_ptr<float>(), output.data_ptr<float>(), N, H, W
|
||||
);
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor bayer_to_rgb_cuda(torch::Tensor input);"
|
||||
|
||||
bayer_to_rgb_module = load_inline(
|
||||
name="bayer_to_rgb_extension_v2",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=bayer_source,
|
||||
functions=["bayer_to_rgb_cuda"],
|
||||
verbose=True, with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.cuda_op = bayer_to_rgb_module
|
||||
|
||||
def forward(self, x):
|
||||
return self.cuda_op.bayer_to_rgb_cuda(x)
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
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__()
|
||||
|
||||
def forward(self, bayer: torch.Tensor) -> torch.Tensor:
|
||||
# Input: [N, H, W]
|
||||
# Output: [N, H, W, 3]
|
||||
|
||||
# [N, 1, H, W]
|
||||
x = bayer.unsqueeze(1).float()
|
||||
N, _, H, W = x.shape
|
||||
|
||||
# 1. Pad (Replicate to match CUDA clamp)
|
||||
x_pad = F.pad(x, (1, 1, 1, 1), mode='replicate')
|
||||
|
||||
# 2. Extract Neighbors
|
||||
val = x_pad[..., 1:-1, 1:-1]
|
||||
up = x_pad[..., 0:-2, 1:-1]
|
||||
down = x_pad[..., 2:, 1:-1]
|
||||
left = x_pad[..., 1:-1, 0:-2]
|
||||
right = x_pad[..., 1:-1, 2:]
|
||||
|
||||
ul = x_pad[..., 0:-2, 0:-2]
|
||||
ur = x_pad[..., 0:-2, 2:]
|
||||
bl = x_pad[..., 2:, 0:-2]
|
||||
br = x_pad[..., 2:, 2:]
|
||||
|
||||
# 3. Create Masks (Fix Shape Mismatch)
|
||||
rows = torch.arange(H, device=x.device).view(-1, 1)
|
||||
cols = torch.arange(W, device=x.device).view(1, -1)
|
||||
|
||||
row_even = (rows % 2 == 0)
|
||||
col_even = (cols % 2 == 0)
|
||||
|
||||
mask_r = (row_even & col_even).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_gr = (row_even & (~col_even)).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_gb = ((~row_even) & col_even).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_b = ((~row_even) & (~col_even)).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
|
||||
# 4. Interpolation
|
||||
r_out = torch.zeros_like(val)
|
||||
g_out = torch.zeros_like(val)
|
||||
b_out = torch.zeros_like(val)
|
||||
|
||||
# R Pixel locations
|
||||
r_out[mask_r] = val[mask_r]
|
||||
g_out[mask_r] = (up[mask_r] + down[mask_r] + left[mask_r] + right[mask_r]) * 0.25
|
||||
b_out[mask_r] = (ul[mask_r] + ur[mask_r] + bl[mask_r] + br[mask_r]) * 0.25
|
||||
|
||||
# GR Pixel locations
|
||||
r_out[mask_gr] = (left[mask_gr] + right[mask_gr]) * 0.5
|
||||
g_out[mask_gr] = val[mask_gr]
|
||||
b_out[mask_gr] = (up[mask_gr] + down[mask_gr]) * 0.5
|
||||
|
||||
# GB Pixel locations
|
||||
r_out[mask_gb] = (up[mask_gb] + down[mask_gb]) * 0.5
|
||||
g_out[mask_gb] = val[mask_gb]
|
||||
b_out[mask_gb] = (left[mask_gb] + right[mask_gb]) * 0.5
|
||||
|
||||
# B Pixel locations
|
||||
r_out[mask_b] = (ul[mask_b] + ur[mask_b] + bl[mask_b] + br[mask_b]) * 0.25
|
||||
g_out[mask_b] = (up[mask_b] + down[mask_b] + left[mask_b] + right[mask_b]) * 0.25
|
||||
b_out[mask_b] = val[mask_b]
|
||||
|
||||
# Stack to [N, H, W, 3]
|
||||
return torch.cat([r_out, g_out, b_out], dim=1).permute(0, 2, 3, 1).contiguous()
|
||||
|
||||
batch_size = 16
|
||||
H = 1024
|
||||
W = 1024
|
||||
def get_inputs():
|
||||
x = torch.rand(batch_size, H, W)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
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__()
|
||||
|
||||
def forward(self, bayer: torch.Tensor) -> torch.Tensor:
|
||||
# Input: [N, H, W]
|
||||
# Output: [N, H, W, 3]
|
||||
|
||||
# [N, 1, H, W]
|
||||
x = bayer.unsqueeze(1).float()
|
||||
N, _, H, W = x.shape
|
||||
|
||||
# 1. Pad (Replicate to match CUDA clamp)
|
||||
x_pad = F.pad(x, (1, 1, 1, 1), mode='replicate')
|
||||
|
||||
# 2. Extract Neighbors
|
||||
val = x_pad[..., 1:-1, 1:-1]
|
||||
up = x_pad[..., 0:-2, 1:-1]
|
||||
down = x_pad[..., 2:, 1:-1]
|
||||
left = x_pad[..., 1:-1, 0:-2]
|
||||
right = x_pad[..., 1:-1, 2:]
|
||||
|
||||
ul = x_pad[..., 0:-2, 0:-2]
|
||||
ur = x_pad[..., 0:-2, 2:]
|
||||
bl = x_pad[..., 2:, 0:-2]
|
||||
br = x_pad[..., 2:, 2:]
|
||||
|
||||
# 3. Create Masks (Fix Shape Mismatch)
|
||||
rows = torch.arange(H, device=x.device).view(-1, 1)
|
||||
cols = torch.arange(W, device=x.device).view(1, -1)
|
||||
|
||||
row_even = (rows % 2 == 0)
|
||||
col_even = (cols % 2 == 0)
|
||||
|
||||
mask_r = (row_even & col_even).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_gr = (row_even & (~col_even)).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_gb = ((~row_even) & col_even).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
mask_b = ((~row_even) & (~col_even)).view(1, 1, H, W).expand(N, -1, -1, -1)
|
||||
|
||||
# 4. Interpolation
|
||||
r_out = torch.zeros_like(val)
|
||||
g_out = torch.zeros_like(val)
|
||||
b_out = torch.zeros_like(val)
|
||||
|
||||
# R Pixel locations
|
||||
r_out[mask_r] = val[mask_r]
|
||||
g_out[mask_r] = (up[mask_r] + down[mask_r] + left[mask_r] + right[mask_r]) * 0.25
|
||||
b_out[mask_r] = (ul[mask_r] + ur[mask_r] + bl[mask_r] + br[mask_r]) * 0.25
|
||||
|
||||
# GR Pixel locations
|
||||
r_out[mask_gr] = (left[mask_gr] + right[mask_gr]) * 0.5
|
||||
g_out[mask_gr] = val[mask_gr]
|
||||
b_out[mask_gr] = (up[mask_gr] + down[mask_gr]) * 0.5
|
||||
|
||||
# GB Pixel locations
|
||||
r_out[mask_gb] = (up[mask_gb] + down[mask_gb]) * 0.5
|
||||
g_out[mask_gb] = val[mask_gb]
|
||||
b_out[mask_gb] = (left[mask_gb] + right[mask_gb]) * 0.5
|
||||
|
||||
# B Pixel locations
|
||||
r_out[mask_b] = (ul[mask_b] + ur[mask_b] + bl[mask_b] + br[mask_b]) * 0.25
|
||||
g_out[mask_b] = (up[mask_b] + down[mask_b] + left[mask_b] + right[mask_b]) * 0.25
|
||||
b_out[mask_b] = val[mask_b]
|
||||
|
||||
# Stack to [N, H, W, 3]
|
||||
return torch.cat([r_out, g_out, b_out], dim=1).permute(0, 2, 3, 1).contiguous()
|
||||
|
||||
batch_size = 16
|
||||
H = 1024
|
||||
W = 1024
|
||||
def get_inputs():
|
||||
x = torch.rand(batch_size, H, W)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from bayer_to_rgb_torch import Model,get_inputs,get_init_inputs
|
||||
from bayer_to_rgb_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