forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish RgbToHsv Operator #45' (#588) from ZZZJ/GPUCodeForces:RgbToHsv into main
This commit is contained in:
commit
9bec085e9d
|
|
@ -0,0 +1,59 @@
|
|||
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
|
||||
|
||||
|
||||
BATCH = 64
|
||||
HEIGHT = 1024
|
||||
WIDTH = 1024
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.epsilon = 1e-6
|
||||
|
||||
def forward(self, image: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
r = image[:, 0, :, :]
|
||||
g = image[:, 1, :, :]
|
||||
b = image[:, 2, :, :]
|
||||
|
||||
max_c, _ = torch.max(image, dim=1)
|
||||
min_c, _ = torch.min(image, dim=1)
|
||||
|
||||
v = max_c
|
||||
delta = max_c - min_c
|
||||
|
||||
s = delta / (max_c + self.epsilon)
|
||||
s[max_c == 0] = 0.0
|
||||
|
||||
h = torch.zeros_like(max_c)
|
||||
|
||||
mask_r = (max_c == r)
|
||||
mask_g = (max_c == g) & (~mask_r)
|
||||
mask_b = (max_c == b) & (~mask_r) & (~mask_g)
|
||||
|
||||
h[mask_r] = (g[mask_r] - b[mask_r]) / (delta[mask_r] + self.epsilon)
|
||||
h[mask_g] = 2.0 + (b[mask_g] - r[mask_g]) / (delta[mask_g] + self.epsilon)
|
||||
h[mask_b] = 4.0 + (r[mask_b] - g[mask_b]) / (delta[mask_b] + self.epsilon)
|
||||
|
||||
h = (h / 6.0) % 1.0
|
||||
h[delta == 0] = 0.0
|
||||
|
||||
return torch.stack([h, s, v], dim=1)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randint(0, 256, size=(BATCH, 3, HEIGHT, WIDTH), device='cuda').float()
|
||||
x = x / 255.0
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
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 rgb_to_hsv_cuda(torch::Tensor input);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define EPSILON 1.0e-6f
|
||||
|
||||
__device__ __forceinline__ void rgb2hsv_pixel_precise(
|
||||
float r, float g, float b,
|
||||
float* h, float* s, float* v
|
||||
) {
|
||||
float max_c = fmaxf(r, fmaxf(g, b));
|
||||
float min_c = fminf(r, fminf(g, b));
|
||||
float delta = max_c - min_c;
|
||||
|
||||
*v = max_c;
|
||||
|
||||
if (max_c < EPSILON) {
|
||||
*s = 0.0f;
|
||||
} else {
|
||||
*s = delta / (max_c + EPSILON);
|
||||
}
|
||||
|
||||
|
||||
if (delta < EPSILON) {
|
||||
*h = 0.0f;
|
||||
} else {
|
||||
float hue;
|
||||
float div = delta + EPSILON;
|
||||
|
||||
if (max_c == r) {
|
||||
hue = (g - b) / div;
|
||||
} else if (max_c == g) {
|
||||
hue = 2.0f + (b - r) / div;
|
||||
} else {
|
||||
hue = 4.0f + (r - g) / div;
|
||||
}
|
||||
|
||||
hue /= 6.0f;
|
||||
// PyTorch % 1.0 logic: maps negative to [0, 1]
|
||||
if (hue < 0.0f) hue += 1.0f;
|
||||
|
||||
*h = hue;
|
||||
}
|
||||
}
|
||||
|
||||
// Float4 Vectorized Kernel
|
||||
__global__ void rgb2hsv_f4_precise_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int n_vecs,
|
||||
int plane_size
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx >= n_vecs) return;
|
||||
|
||||
int vec_per_batch = plane_size / 4;
|
||||
int b = idx / vec_per_batch;
|
||||
int spatial_vec_idx = idx % vec_per_batch;
|
||||
int spatial_offset = spatial_vec_idx * 4;
|
||||
|
||||
long long batch_offset = (long long)b * 3 * plane_size;
|
||||
|
||||
const float* r_ptr = input + batch_offset;
|
||||
const float* g_ptr = input + batch_offset + plane_size;
|
||||
const float* b_ptr = input + batch_offset + 2 * plane_size;
|
||||
|
||||
float4 r4 = reinterpret_cast<const float4*>(r_ptr)[spatial_offset / 4];
|
||||
float4 g4 = reinterpret_cast<const float4*>(g_ptr)[spatial_offset / 4];
|
||||
float4 b4 = reinterpret_cast<const float4*>(b_ptr)[spatial_offset / 4];
|
||||
|
||||
float4 h4, s4, v4;
|
||||
|
||||
// Pixel 0
|
||||
rgb2hsv_pixel_precise(r4.x, g4.x, b4.x, &h4.x, &s4.x, &v4.x);
|
||||
// Pixel 1
|
||||
rgb2hsv_pixel_precise(r4.y, g4.y, b4.y, &h4.y, &s4.y, &v4.y);
|
||||
// Pixel 2
|
||||
rgb2hsv_pixel_precise(r4.z, g4.z, b4.z, &h4.z, &s4.z, &v4.z);
|
||||
// Pixel 3
|
||||
rgb2hsv_pixel_precise(r4.w, g4.w, b4.w, &h4.w, &s4.w, &v4.w);
|
||||
|
||||
long long out_batch_offset = (long long)b * 3 * plane_size;
|
||||
float* h_out = output + out_batch_offset;
|
||||
float* s_out = output + out_batch_offset + plane_size;
|
||||
float* v_out = output + out_batch_offset + 2 * plane_size;
|
||||
|
||||
reinterpret_cast<float4*>(h_out)[spatial_offset / 4] = h4;
|
||||
reinterpret_cast<float4*>(s_out)[spatial_offset / 4] = s4;
|
||||
reinterpret_cast<float4*>(v_out)[spatial_offset / 4] = v4;
|
||||
}
|
||||
|
||||
torch::Tensor rgb_to_hsv_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);
|
||||
int plane_size = height * width;
|
||||
|
||||
if (plane_size % 4 != 0) return output;
|
||||
|
||||
long long total_vecs = (long long)batch * (plane_size / 4);
|
||||
const int grid_size = (total_vecs + BLOCK_SIZE - 1) / BLOCK_SIZE;
|
||||
|
||||
rgb2hsv_f4_precise_kernel<<<grid_size, BLOCK_SIZE>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
total_vecs,
|
||||
plane_size
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="rgb2hsv_precise_v3",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["rgb_to_hsv_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.rgb_to_hsv_cuda(x)
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
BATCH = 64
|
||||
HEIGHT = 1024
|
||||
WIDTH = 1024
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.epsilon = 1e-6
|
||||
|
||||
def forward(self, image: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
r = image[:, 0, :, :]
|
||||
g = image[:, 1, :, :]
|
||||
b = image[:, 2, :, :]
|
||||
|
||||
max_c, _ = torch.max(image, dim=1)
|
||||
min_c, _ = torch.min(image, dim=1)
|
||||
|
||||
v = max_c
|
||||
delta = max_c - min_c
|
||||
|
||||
s = delta / (max_c + self.epsilon)
|
||||
s[max_c == 0] = 0.0
|
||||
|
||||
h = torch.zeros_like(max_c)
|
||||
|
||||
mask_r = (max_c == r)
|
||||
mask_g = (max_c == g) & (~mask_r)
|
||||
mask_b = (max_c == b) & (~mask_r) & (~mask_g)
|
||||
|
||||
h[mask_r] = (g[mask_r] - b[mask_r]) / (delta[mask_r] + self.epsilon)
|
||||
h[mask_g] = 2.0 + (b[mask_g] - r[mask_g]) / (delta[mask_g] + self.epsilon)
|
||||
h[mask_b] = 4.0 + (r[mask_b] - g[mask_b]) / (delta[mask_b] + self.epsilon)
|
||||
|
||||
h = (h / 6.0) % 1.0
|
||||
h[delta == 0] = 0.0
|
||||
|
||||
return torch.stack([h, s, v], dim=1)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randint(0, 256, size=(BATCH, 3, HEIGHT, WIDTH), device='cuda').float()
|
||||
x = x / 255.0
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from rgb_to_hsv_torch import Model,get_inputs,get_init_inputs
|
||||
from rgb_to_hsv_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