Merge pull request 'finish SeparableConv3d #142' (#764) from ZZZJ/GPUCodeForces:SeparableConv3d into main

This commit is contained in:
wawahejun 2025-12-14 20:28:18 +08:00
commit 4fd56412e9
4 changed files with 368 additions and 0 deletions

57
S1/ZZZJ_#142/prompt.txt Normal file
View File

@ -0,0 +1,57 @@
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 = 4
CHANNELS = 32
DEPTH = 64
HEIGHT = 64
WIDTH = 64
KERNEL_SIZE = 3
PADDING = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv_d = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(KERNEL_SIZE, 1, 1),
padding=(PADDING, 0, 0), groups=CHANNELS, bias=False
)
self.conv_h = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(1, KERNEL_SIZE, 1),
padding=(0, PADDING, 0), groups=CHANNELS, bias=False
)
self.conv_w = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(1, 1, KERNEL_SIZE),
padding=(0, 0, PADDING), groups=CHANNELS, bias=False
)
nn.init.constant_(self.conv_d.weight, 1.0)
nn.init.constant_(self.conv_h.weight, 1.0)
nn.init.constant_(self.conv_w.weight, 1.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv_d(x)
x = self.conv_h(x)
return self.conv_w(x)
def get_inputs():
x = torch.randint(low=-2, high=3, size=(BATCH, CHANNELS, DEPTH, HEIGHT, WIDTH), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

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

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

View File

@ -0,0 +1,188 @@
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.kernel_size = 3
self.padding = 1
self.channels = 32
self.weight = nn.Parameter(torch.full((self.channels, 1, 3, 3, 3), 1.0, device='cuda'))
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor separable_conv3d_cuda(torch::Tensor input, torch::Tensor weight, int k_size, int padding);
"""
cuda_source = """
#include <cuda_runtime.h>
#define K 3
// Block Size: 16x8x4 = 512 threads
#define TILE_W 16
#define TILE_H 8
#define TILE_D 4
// Smem Size (Output + Halo)
#define SMEM_W (TILE_W + K - 1) // 18
#define SMEM_H (TILE_H + K - 1) // 10
#define SMEM_D (TILE_D + K - 1) // 6
__global__ void separable_direct3d_kernel(
const float* __restrict__ input,
const float* __restrict__ weight,
float* __restrict__ output,
int batch,
int channels,
int depth,
int height,
int width,
int padding
) {
// Grid Mapping
// bx -> Spatial Block Index
// by -> Channel
// bz -> Batch
int tiles_w = (width + TILE_W - 1) / TILE_W;
int tiles_h = (height + TILE_H - 1) / TILE_H;
int tiles_d = (depth + TILE_D - 1) / TILE_D;
int bx = blockIdx.x;
int td = bx / (tiles_w * tiles_h);
int rem = bx % (tiles_w * tiles_h);
int th = rem / tiles_w;
int tw = rem % tiles_w;
int out_d_start = td * TILE_D;
int out_h_start = th * TILE_H;
int out_w_start = tw * TILE_W;
int c = blockIdx.y;
int b = blockIdx.z;
__shared__ float smem[SMEM_D][SMEM_H][SMEM_W];
int tid = threadIdx.z * (blockDim.y * blockDim.x) + threadIdx.y * blockDim.x + threadIdx.x;
int num_threads = blockDim.x * blockDim.y * blockDim.z;
int smem_numel = SMEM_D * SMEM_H * SMEM_W; // 6*10*18 = 1080
// Input Base Offset
long long input_plane_offset = (long long)b * (channels * depth * height * width) + c * (depth * height * width);
// Top-Left of Input Tile
int in_d_start = out_d_start - padding;
int in_h_start = out_h_start - padding;
int in_w_start = out_w_start - padding;
// Cooperative Load
for (int i = tid; i < smem_numel; i += num_threads) {
int sd = i / (SMEM_H * SMEM_W);
int rem_s = i % (SMEM_H * SMEM_W);
int sh = rem_s / SMEM_W;
int sw = rem_s % SMEM_W;
int gd = in_d_start + sd;
int gh = in_h_start + sh;
int gw = in_w_start + sw;
float val = 0.0f;
if (gd >= 0 && gd < depth && gh >= 0 && gh < height && gw >= 0 && gw < width) {
val = input[input_plane_offset + gd * (height * width) + gh * width + gw];
}
smem[sd][sh][sw] = val;
}
__syncthreads();
int tx = threadIdx.x;
int ty = threadIdx.y;
int tz = threadIdx.z;
int od = out_d_start + tz;
int oh = out_h_start + ty;
int ow = out_w_start + tx;
if (od < depth && oh < height && ow < width) {
// Weight Offset Base
int w_base = c * (K * K * K);
double sum = 0.0; // Double accumulator
// 3D Loop Unroll
#pragma unroll
for (int kd = 0; kd < K; ++kd) {
#pragma unroll
for (int kh = 0; kh < K; ++kh) {
#pragma unroll
for (int kw = 0; kw < K; ++kw) {
// Smem index: local_thread + k
// input window starts at padding 1 relative to smem 0?
// No, smem[0][0][0] is input[out-pad], so out corresponds to smem[tz+pad-pad]??
// Let's verify:
// smem[0] -> in[out-pad]
// we want in[out-pad+k]
// so smem index is simply threadIdx + k
float val = smem[tz + kd][ty + kh][tx + kw];
float w = weight[w_base + kd*9 + kh*3 + kw];
sum += (double)val * (double)w;
}
}
}
long long out_idx = (long long)b * (channels * depth * height * width) +
c * (depth * height * width) +
od * (height * width) +
oh * width +
ow;
output[out_idx] = (float)sum;
}
}
torch::Tensor separable_conv3d_cuda(torch::Tensor input, torch::Tensor weight, int k_size, int padding) {
int batch = input.size(0);
int channels = input.size(1);
int depth = input.size(2);
int height = input.size(3);
int width = input.size(4);
auto output = torch::empty_like(input);
// Spatial Blocks
int tiles_w = (width + TILE_W - 1) / TILE_W;
int tiles_h = (height + TILE_H - 1) / TILE_H;
int tiles_d = (depth + TILE_D - 1) / TILE_D;
dim3 block(TILE_W, TILE_H, TILE_D);
dim3 grid(tiles_w * tiles_h * tiles_d, channels, batch);
separable_direct3d_kernel<<<grid, block>>>(
input.data_ptr<float>(),
weight.data_ptr<float>(),
output.data_ptr<float>(),
batch, channels, depth, height, width, padding
);
return output;
}
"""
self.op = load_inline(
name="separable_direct3d_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["separable_conv3d_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.separable_conv3d_cuda(x, self.weight, self.kernel_size, self.padding)

View File

@ -0,0 +1,49 @@
import torch
import torch.nn as nn
BATCH = 4
CHANNELS = 32
DEPTH = 64
HEIGHT = 64
WIDTH = 64
KERNEL_SIZE = 3
PADDING = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv_d = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(KERNEL_SIZE, 1, 1),
padding=(PADDING, 0, 0), groups=CHANNELS, bias=False
)
self.conv_h = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(1, KERNEL_SIZE, 1),
padding=(0, PADDING, 0), groups=CHANNELS, bias=False
)
self.conv_w = nn.Conv3d(
CHANNELS, CHANNELS, kernel_size=(1, 1, KERNEL_SIZE),
padding=(0, 0, PADDING), groups=CHANNELS, bias=False
)
nn.init.constant_(self.conv_d.weight, 1.0)
nn.init.constant_(self.conv_h.weight, 1.0)
nn.init.constant_(self.conv_w.weight, 1.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv_d(x)
x = self.conv_h(x)
return self.conv_w(x)
def get_inputs():
x = torch.randint(low=-2, high=3, size=(BATCH, CHANNELS, DEPTH, HEIGHT, WIDTH), device='cuda').float()
return [x]
def get_init_inputs():
return []