forked from ccf-ai-infra/GPUCodeForces
fixes MedianFilter1d #104
This commit is contained in:
parent
cc73715277
commit
5ed88bb0e5
|
|
@ -0,0 +1,154 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
|
||||
from median_filter_1d_torch import KERNEL_SIZE, N, C, L
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.k = KERNEL_SIZE
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
|
||||
BLOCK_SIZE = 256
|
||||
PAD = self.k // 2
|
||||
|
||||
macros = f"""
|
||||
#define K {self.k}
|
||||
#define PAD {PAD}
|
||||
#define BLOCK_SIZE {BLOCK_SIZE}
|
||||
#define SMEM_SIZE (BLOCK_SIZE + 2 * PAD)
|
||||
#define MEDIAN_IDX (K / 2)
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor median_filter_1d_cuda(torch::Tensor input);
|
||||
"""
|
||||
|
||||
cuda_source = f"""
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
{macros}
|
||||
|
||||
|
||||
__device__ __forceinline__ void partial_sort(float* window) {{
|
||||
#pragma unroll
|
||||
for (int i = 0; i <= MEDIAN_IDX; ++i) {{
|
||||
#pragma unroll
|
||||
for (int j = i + 1; j < K; ++j) {{
|
||||
float a = window[i];
|
||||
float b = window[j];
|
||||
if (b < a) {{
|
||||
window[i] = b;
|
||||
window[j] = a;
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
|
||||
|
||||
__global__ void median_filter_1d_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int length
|
||||
) {{
|
||||
// Shared memory for tile + halo
|
||||
__shared__ float smem[SMEM_SIZE];
|
||||
|
||||
int bx = blockIdx.x; // Block along L
|
||||
int by = blockIdx.y; // Batch * Channel index
|
||||
int tx = threadIdx.x;
|
||||
|
||||
// Global Thread ID along L
|
||||
int out_idx = bx * BLOCK_SIZE + tx;
|
||||
|
||||
// Input Pointer Offset for current channel
|
||||
// input: (N, C, L)
|
||||
int plane_offset = by * length;
|
||||
const float* in_plane = input + plane_offset;
|
||||
float* out_plane = output + plane_offset;
|
||||
|
||||
// --- 1. Collaborative Loading (Global -> Shared) ---
|
||||
// Load BLOCK_SIZE + 2*PAD elements
|
||||
// Each thread loads potentially multiple elements
|
||||
|
||||
// Base index in global memory for this block's smem start (left halo)
|
||||
int base_idx = bx * BLOCK_SIZE - PAD;
|
||||
|
||||
for (int i = tx; i < SMEM_SIZE; i += BLOCK_SIZE) {{
|
||||
int global_load_idx = base_idx + i;
|
||||
|
||||
// Replicate Padding Logic
|
||||
// Clamp index to [0, length-1]
|
||||
int clamped_idx = min(max(global_load_idx, 0), length - 1);
|
||||
|
||||
smem[i] = in_plane[clamped_idx];
|
||||
}}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// --- 2. Compute Median ---
|
||||
|
||||
if (out_idx < length) {{
|
||||
float window[K];
|
||||
|
||||
// Read from Shared Memory
|
||||
// Center of window in smem is at index: tx + PAD
|
||||
// Window range: [tx, tx + K)
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < K; ++i) {{
|
||||
window[i] = smem[tx + i];
|
||||
}}
|
||||
|
||||
// Sort
|
||||
partial_sort(window);
|
||||
|
||||
// Write result
|
||||
out_plane[out_idx] = window[MEDIAN_IDX];
|
||||
}}
|
||||
}}
|
||||
|
||||
torch::Tensor median_filter_1d_cuda(torch::Tensor input) {{
|
||||
TORCH_CHECK(input.is_cuda(), "Input must be CUDA");
|
||||
TORCH_CHECK(input.dim() == 3, "Input must be (N, C, L)");
|
||||
|
||||
// Ensure contiguous for pointer arithmetic
|
||||
input = input.contiguous();
|
||||
|
||||
int N = input.size(0);
|
||||
int C = input.size(1);
|
||||
int L = input.size(2);
|
||||
|
||||
auto output = torch::empty_like(input);
|
||||
|
||||
dim3 block(BLOCK_SIZE);
|
||||
// Grid X covers L, Grid Y covers N*C
|
||||
dim3 grid((L + BLOCK_SIZE - 1) / BLOCK_SIZE, N * C);
|
||||
|
||||
median_filter_1d_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
L
|
||||
);
|
||||
|
||||
return output;
|
||||
}}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name='median_filter_1d_opt_v1',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['median_filter_1d_cuda'],
|
||||
extra_cuda_cflags=['-O3', '--use_fast_math'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
if not x.is_cuda: x = x.cuda()
|
||||
return self.op.median_filter_1d_cuda(x)
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
N = 32
|
||||
C = 64
|
||||
L = 32000
|
||||
KERNEL_SIZE = 7
|
||||
|
||||
class MedianFilter1d(nn.Module):
|
||||
def __init__(self, kernel_size=7):
|
||||
super().__init__()
|
||||
self.k = kernel_size
|
||||
self.pad = kernel_size // 2
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
x_pad = F.pad(x, (self.pad, self.pad), mode='replicate')
|
||||
|
||||
|
||||
patches = x_pad.unfold(dimension=-1, size=self.k, step=1)
|
||||
|
||||
patches = patches.contiguous()
|
||||
|
||||
values, _ = torch.sort(patches, dim=-1)
|
||||
result = values[..., self.k // 2]
|
||||
|
||||
return result
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.op = MedianFilter1d(kernel_size=KERNEL_SIZE)
|
||||
|
||||
def forward(self, x):
|
||||
return self.op(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, L, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
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
|
||||
|
||||
N = 32
|
||||
C = 64
|
||||
L = 32000
|
||||
KERNEL_SIZE = 7
|
||||
|
||||
class MedianFilter1d(nn.Module):
|
||||
def __init__(self, kernel_size=7):
|
||||
super().__init__()
|
||||
self.k = kernel_size
|
||||
self.pad = kernel_size // 2
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
x_pad = F.pad(x, (self.pad, self.pad), mode='replicate')
|
||||
|
||||
|
||||
patches = x_pad.unfold(dimension=-1, size=self.k, step=1)
|
||||
|
||||
patches = patches.contiguous()
|
||||
|
||||
values, _ = torch.sort(patches, dim=-1)
|
||||
result = values[..., self.k // 2]
|
||||
|
||||
return result
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.op = MedianFilter1d(kernel_size=KERNEL_SIZE)
|
||||
|
||||
def forward(self, x):
|
||||
return self.op(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, L, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from median_filter_1d_torch import Model,get_inputs,get_init_inputs
|
||||
from median_filter_1d_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