fixes MedianFilter2d #105

This commit is contained in:
ZZZJ 2025-12-09 20:40:43 +08:00
parent cc73715277
commit e0cd2f0cb0
4 changed files with 342 additions and 0 deletions

View File

@ -0,0 +1,174 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from MedianFilter2d_torch import KERNEL_SIZE, N, C, H, W
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.k = KERNEL_SIZE
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
BLOCK_W = 32
BLOCK_H = 8
PAD = self.k // 2
macros = f"""
#define K {self.k}
#define PAD {PAD}
#define BLOCK_W {BLOCK_W}
#define BLOCK_H {BLOCK_H}
#define SMEM_W (BLOCK_W + 2 * PAD)
#define SMEM_H (BLOCK_H + 2 * PAD)
#define WINDOW_SIZE (K * K)
#define MEDIAN_IDX (WINDOW_SIZE / 2)
"""
cpp_source = """
#include <torch/extension.h>
torch::Tensor median_filter_cuda(torch::Tensor input);
"""
cuda_source = f"""
#include <cuda_runtime.h>
{macros}
__device__ __forceinline__ void partial_sort(float* window) {{
// Outer loop: only needs to run until we find the median element
#pragma unroll
for (int i = 0; i <= MEDIAN_IDX; ++i) {{
// Find min in window[i...WINDOW_SIZE-1]
#pragma unroll
for (int j = i + 1; j < WINDOW_SIZE; ++j) {{
float a = window[i];
float b = window[j];
// Swap if b is smaller, bubbling the min to position i
if (b < a) {{
window[i] = b;
window[j] = a;
}}
}}
}}
}}
__global__ void median_filter_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int height, int width
) {{
// Shared memory for tile + halo
__shared__ float smem[SMEM_H][SMEM_W];
// 1. Coordinates
int bx = blockIdx.x;
int by = blockIdx.y;
int bz = blockIdx.z; // Batch * Channel
int tx = threadIdx.x;
int ty = threadIdx.y;
// Base coordinates in global memory (output pixel coords)
int base_x = bx * BLOCK_W;
int base_y = by * BLOCK_H;
// Plane offset for (n, c)
int plane_offset = bz * height * width;
const float* in_plane = input + plane_offset;
float* out_plane = output + plane_offset;
// 2. Collaborative Loading (Global -> Shared)
// Load a (BLOCK_H + 2*PAD) x (BLOCK_W + 2*PAD) block
int tid = ty * BLOCK_W + tx;
int num_threads = BLOCK_H * BLOCK_W;
int num_smem_elements = SMEM_H * SMEM_W;
for (int i = tid; i < num_smem_elements; i += num_threads) {{
int s_y = i / SMEM_W;
int s_x = i % SMEM_W;
// Map shared memory coord to global coord (applying halo offset)
int g_y = base_y + s_y - PAD;
int g_x = base_x + s_x - PAD;
// Replicate Padding Logic: Clamp to border
g_y = max(0, min(g_y, height - 1));
g_x = max(0, min(g_x, width - 1));
smem[s_y][s_x] = in_plane[g_y * width + g_x];
}}
__syncthreads();
// 3. Compute Median
int out_x = base_x + tx;
int out_y = base_y + ty;
// Only compute if valid output pixel
if (out_x < width && out_y < height) {{
float window[WINDOW_SIZE];
// Read from Shared Memory
// Center of window in smem is at [ty + PAD][tx + PAD]
int w_idx = 0;
#pragma unroll
for (int dy = 0; dy < K; ++dy) {{
#pragma unroll
for (int dx = 0; dx < K; ++dx) {{
window[w_idx++] = smem[ty + dy][tx + dx];
}}
}}
// Sort partially to find median
partial_sort(window);
// Write result
out_plane[out_y * width + out_x] = window[MEDIAN_IDX];
}}
}}
torch::Tensor median_filter_cuda(torch::Tensor input) {{
TORCH_CHECK(input.is_cuda(), "Input must be CUDA");
TORCH_CHECK(input.dim() == 4, "Input must be (N, C, H, W)");
// Ensure contiguous memory for correct pointer arithmetic
input = input.contiguous();
int N = input.size(0);
int C = input.size(1);
int H = input.size(2);
int W = input.size(3);
auto output = torch::empty_like(input);
dim3 block(BLOCK_W, BLOCK_H);
dim3 grid((W + BLOCK_W - 1) / BLOCK_W, (H + BLOCK_H - 1) / BLOCK_H, N * C);
median_filter_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
H, W
);
return output;
}}
"""
self.op = load_inline(
name='median_filter_opt_fixed_sort_v3',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['median_filter_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_cuda(x)

View File

@ -0,0 +1,43 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
N, C, H, W = 4, 3, 512, 512
KERNEL_SIZE = 3
class MedianFilter2d(nn.Module):
def __init__(self, kernel_size=3):
super().__init__()
self.k = kernel_size
self.pad = kernel_size // 2
def forward(self, x):
N, C, H, W = x.shape
x_pad = F.pad(x, (self.pad, self.pad, self.pad, self.pad), mode='replicate')
patches = F.unfold(x_pad, kernel_size=self.k)
patches = patches.view(N, C, self.k * self.k, -1)
median_val, _ = torch.median(patches, dim=2)
return median_val.view(N, C, H, W)
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = MedianFilter2d(kernel_size=KERNEL_SIZE)
def forward(self, x):
return self.op(x)
def get_inputs():
x = torch.randn(N, C, H, W, dtype=torch.float32)
return [x]
def get_init_inputs():
return []

51
S1/ZZZJ_#105/prompt.txt Normal file
View File

@ -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, C, H, W = 4, 3, 512, 512
KERNEL_SIZE = 3
class MedianFilter2d(nn.Module):
def __init__(self, kernel_size=3):
super().__init__()
self.k = kernel_size
self.pad = kernel_size // 2
def forward(self, x):
N, C, H, W = x.shape
x_pad = F.pad(x, (self.pad, self.pad, self.pad, self.pad), mode='replicate')
patches = F.unfold(x_pad, kernel_size=self.k)
patches = patches.view(N, C, self.k * self.k, -1)
median_val, _ = torch.median(patches, dim=2)
return median_val.view(N, C, H, W)
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = MedianFilter2d(kernel_size=KERNEL_SIZE)
def forward(self, x):
return self.op(x)
def get_inputs():
x = torch.randn(N, C, H, W, dtype=torch.float32)
return [x]
def get_init_inputs():
return []
```

74
S1/ZZZJ_#105/run_code.py Normal file
View File

@ -0,0 +1,74 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from MedianFilter2d_torch import Model,get_inputs,get_init_inputs
from MedianFilter2d_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()