Merge pull request 'finish Dilation3d #109' (#757) from ZZZJ/GPUCodeForces:Dilation3d into main

This commit is contained in:
wawahejun 2025-12-14 20:27:15 +08:00
commit 930cf5c8ff
4 changed files with 351 additions and 0 deletions

View File

@ -0,0 +1,183 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from Dilation3d_torch import K, N, C, D, H, W
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
BLOCK_W = 8
BLOCK_H = 8
BLOCK_D = 4
PAD = K // 2
macros = f"""
#define K {K}
#define PAD {PAD}
#define BLOCK_W {BLOCK_W}
#define BLOCK_H {BLOCK_H}
#define BLOCK_D {BLOCK_D}
// Shared Memory Dimensions (Block + Halo)
#define SMEM_W (BLOCK_W + 2 * PAD)
#define SMEM_H (BLOCK_H + 2 * PAD)
#define SMEM_D (BLOCK_D + 2 * PAD)
"""
cpp_source = """
#include <torch/extension.h>
torch::Tensor dilation3d_cuda(torch::Tensor input);
"""
cuda_source = f"""
#include <cuda_runtime.h>
{macros}
__global__ void dilation3d_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int depth, int height, int width
) {{
// 1. Setup Shared Memory
__shared__ float smem[SMEM_D][SMEM_H][SMEM_W];
// 2. Coordinates
int tx = threadIdx.x;
int ty = threadIdx.y;
int tz = threadIdx.z;
// Decode Grid Z to (batch_channel, block_z)
int num_blocks_d = (depth + BLOCK_D - 1) / BLOCK_D;
int bz = blockIdx.z;
int nc_idx = bz / num_blocks_d;
int block_z = bz % num_blocks_d;
int bx = blockIdx.x;
int by = blockIdx.y;
int base_x = bx * BLOCK_W;
int base_y = by * BLOCK_H;
int base_z = block_z * BLOCK_D;
// Pointer offsets
int volume_size = depth * height * width;
int plane_offset = nc_idx * volume_size;
const float* in_ptr = input + plane_offset;
float* out_ptr = output + plane_offset;
// 3. Collaborative Loading (Global -> Shared)
int tid = tz * (BLOCK_H * BLOCK_W) + ty * BLOCK_W + tx;
int num_threads = BLOCK_D * BLOCK_H * BLOCK_W;
int num_smem = SMEM_D * SMEM_H * SMEM_W;
for (int i = tid; i < num_smem; i += num_threads) {{
// Decode Shared Coords (3D Indexing)
int s_z = i / (SMEM_H * SMEM_W);
int rem = i % (SMEM_H * SMEM_W);
int s_y = rem / SMEM_W;
int s_x = rem % SMEM_W;
// Map to Global
int g_z = base_z + s_z - PAD;
int g_y = base_y + s_y - PAD;
int g_x = base_x + s_x - PAD;
// Replicate Padding Logic: Clamp to border
g_z = max(0, min(g_z, depth - 1));
g_y = max(0, min(g_y, height - 1));
g_x = max(0, min(g_x, width - 1));
// Linear 3D Indexing: z * H * W + y * W + x
int linear_idx = g_z * height * width + g_y * width + g_x;
smem[s_z][s_y][s_x] = __ldg(in_ptr + linear_idx);
}}
__syncthreads();
// 4. Compute Max Reduction
int out_x = base_x + tx;
int out_y = base_y + ty;
int out_z = base_z + tz;
if (out_x < width && out_y < height && out_z < depth) {{
// Initialize max to a very small value
float max_val = -1e30f;
// Read 3x3x3 Neighborhood from Shared Mem
#pragma unroll
for (int dz = 0; dz < K; ++dz) {{
#pragma unroll
for (int dy = 0; dy < K; ++dy) {{
#pragma unroll
for (int dx = 0; dx < K; ++dx) {{
max_val = fmaxf(max_val, smem[tz + dz][ty + dy][tx + dx]);
}}
}}
}}
// Write Output
int linear_out_idx = out_z * height * width + out_y * width + out_x;
out_ptr[linear_out_idx] = max_val;
}}
}}
torch::Tensor dilation3d_cuda(torch::Tensor input) {{
TORCH_CHECK(input.is_cuda(), "Input must be CUDA");
TORCH_CHECK(input.dim() == 5, "Input must be (N, C, D, H, W)");
input = input.contiguous();
int N = input.size(0);
int C = input.size(1);
int D = input.size(2);
int H = input.size(3);
int W = input.size(4);
auto output = torch::empty_like(input);
dim3 block(BLOCK_W, BLOCK_H, BLOCK_D);
// Grid Z = (Depth / Block_D) * N * C
int num_blocks_d = (D + BLOCK_D - 1) / BLOCK_D;
int grid_z = num_blocks_d * N * C;
dim3 grid(
(W + BLOCK_W - 1) / BLOCK_W,
(H + BLOCK_H - 1) / BLOCK_H,
grid_z
);
dilation3d_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
D, H, W
);
return output;
}}
"""
self.op = load_inline(
name='dilation3d_opt',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['dilation3d_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.dilation3d_cuda(x)

View File

@ -0,0 +1,43 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
N, C = 2, 1
D, H, W = 64, 128, 128
K = 3
class Dilation3d(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, D, H, W = x.shape
pad_tuple = (self.pad,) * 6
x_pad = F.pad(x, pad_tuple, mode='replicate')
windows = x_pad.unfold(2, self.k, 1).unfold(3, self.k, 1).unfold(4, self.k, 1)
windows = windows.contiguous().view(N, C, D, H, W, -1)
result, _ = torch.max(windows, dim=-1)
return result
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = Dilation3d(kernel_size=K)
def forward(self, x):
return self.op(x)
def get_inputs():
x = torch.rand(N, C, D, H, W, dtype=torch.float32) * 10.0
return [x]
def get_init_inputs():
return []

51
S1/ZZZJ_#109/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 = 2, 1
D, H, W = 64, 128, 128
K = 3
class Dilation3d(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, D, H, W = x.shape
pad_tuple = (self.pad,) * 6
x_pad = F.pad(x, pad_tuple, mode='replicate')
windows = x_pad.unfold(2, self.k, 1).unfold(3, self.k, 1).unfold(4, self.k, 1)
windows = windows.contiguous().view(N, C, D, H, W, -1)
result, _ = torch.max(windows, dim=-1)
return result
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = Dilation3d(kernel_size=K)
def forward(self, x):
return self.op(x)
def get_inputs():
x = torch.rand(N, C, D, H, W, dtype=torch.float32) * 10.0
return [x]
def get_init_inputs():
return []
```

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

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