fixes DwDilated3d #59

This commit is contained in:
ZZZJ 2025-12-09 18:00:20 +08:00
parent cc73715277
commit e5d497d41e
4 changed files with 306 additions and 0 deletions

View File

@ -0,0 +1,144 @@
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.dilation = 2
self.padding = 2
self.stride = 1
self.channels = 32
self.weight = nn.Parameter(torch.full((self.channels, 1, self.kernel_size, self.kernel_size, self.kernel_size), 1.0, device='cuda'))
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor dw_dilated3d_cuda(torch::Tensor input, torch::Tensor weight, int kernel_size, int dilation, int padding, int stride);
"""
cuda_source = """
#include <cuda_runtime.h>
#define BLOCK_SIZE 256
// Depthwise Dilated Conv3d Kernel
__global__ void dw_dilated3d_f4_kernel(
const float* __restrict__ input,
const float* __restrict__ weight,
float* __restrict__ output,
int n_vec,
int batch,
int channels,
int depth,
int height,
int width,
int k_size,
int dilation,
int padding,
int stride
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= n_vec) return;
int w_vec_dim = width / 4;
int tmp = idx;
int w_vec = tmp % w_vec_dim; tmp /= w_vec_dim;
int h = tmp % height; tmp /= height;
int d = tmp % depth; tmp /= depth;
int c = tmp % channels;
int b = tmp / channels; // Batch Index
int w_start = w_vec * 4;
long long in_base_offset = (long long)b * (channels * depth * height * width) + c * (depth * height * width);
int w_base_offset = c * (k_size * k_size * k_size);
double sum0 = 0.0, sum1 = 0.0, sum2 = 0.0, sum3 = 0.0;
for (int kd = 0; kd < k_size; ++kd) {
int d_in = d * stride + kd * dilation - padding;
if (d_in < 0 || d_in >= depth) continue;
long long in_depth_offset = in_base_offset + d_in * (height * width);
for (int kh = 0; kh < k_size; ++kh) {
int h_in = h * stride + kh * dilation - padding;
if (h_in < 0 || h_in >= height) continue;
long long in_row_offset = in_depth_offset + h_in * width;
for (int kw = 0; kw < k_size; ++kw) {
double w = (double)weight[w_base_offset + kd*(k_size*k_size) + kh*k_size + kw];
int w_offset = kw * dilation - padding;
int w_in_0 = (w_start + 0) * stride + w_offset;
int w_in_1 = (w_start + 1) * stride + w_offset;
int w_in_2 = (w_start + 2) * stride + w_offset;
int w_in_3 = (w_start + 3) * stride + w_offset;
if (w_in_0 >= 0 && w_in_0 < width) sum0 += (double)input[in_row_offset + w_in_0] * w;
if (w_in_1 >= 0 && w_in_1 < width) sum1 += (double)input[in_row_offset + w_in_1] * w;
if (w_in_2 >= 0 && w_in_2 < width) sum2 += (double)input[in_row_offset + w_in_2] * w;
if (w_in_3 >= 0 && w_in_3 < width) sum3 += (double)input[in_row_offset + w_in_3] * w;
}
}
}
long long out_base = (long long)b * (channels * depth * height * width) +
c * (depth * height * width) +
d * (height * width) +
h * width +
w_start;
output[out_base + 0] = (float)sum0;
output[out_base + 1] = (float)sum1;
output[out_base + 2] = (float)sum2;
output[out_base + 3] = (float)sum3;
}
torch::Tensor dw_dilated3d_cuda(torch::Tensor input, torch::Tensor weight, int kernel_size, int dilation, int padding, int stride) {
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({batch, channels, depth, height, width}, input.options());
if (width % 4 != 0) return output;
int n_vec = output.numel() / 4;
const int block_size = 256;
const int grid_size = (n_vec + block_size - 1) / block_size;
dw_dilated3d_f4_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
weight.data_ptr<float>(),
output.data_ptr<float>(),
n_vec,
batch, channels, depth, height, width,
kernel_size, dilation, padding, stride
);
return output;
}
"""
self.op = load_inline(
name="dw_dilated3d_f4_safe",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["dw_dilated3d_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.dw_dilated3d_cuda(x, self.weight, self.kernel_size, self.dilation, self.padding, self.stride)

View File

@ -0,0 +1,40 @@
import torch
import torch.nn as nn
BATCH = 2
CHANNELS = 32
DEPTH = 32
HEIGHT = 32
WIDTH = 32
KERNEL_SIZE = 3
DILATION = 2
PADDING = 2
STRIDE = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
torch.backends.cudnn.enabled = False
self.conv = nn.Conv3d(
in_channels=CHANNELS,
out_channels=CHANNELS,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
padding=PADDING,
dilation=DILATION,
groups=CHANNELS,
bias=False
)
nn.init.constant_(self.conv.weight, 1.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.conv(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 []

48
S1/ZZZJ_#59/prompt.txt Normal file
View File

@ -0,0 +1,48 @@
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 = 2
CHANNELS = 32
DEPTH = 32
HEIGHT = 32
WIDTH = 32
KERNEL_SIZE = 3
DILATION = 2
PADDING = 2
STRIDE = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
torch.backends.cudnn.enabled = False
self.conv = nn.Conv3d(
in_channels=CHANNELS,
out_channels=CHANNELS,
kernel_size=KERNEL_SIZE,
stride=STRIDE,
padding=PADDING,
dilation=DILATION,
groups=CHANNELS,
bias=False
)
nn.init.constant_(self.conv.weight, 1.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.conv(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_#59/run_code.py Normal file
View File

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