fixes SobelFilter3d #91

This commit is contained in:
ZZZJ 2025-12-09 20:10:34 +08:00
parent cc73715277
commit 55b341fdae
4 changed files with 314 additions and 0 deletions

58
S1/ZZZJ_#91/prompt.txt Normal file
View File

@ -0,0 +1,58 @@
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
torch.backends.cuda.matmul.allow_tf32 = False
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
smooth = torch.tensor([1., 2., 1.], dtype=torch.float32)
diff = torch.tensor([-1., 0., 1.], dtype=torch.float32)
k_x = (smooth.view(3, 1, 1) * smooth.view(1, 3, 1) * diff.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
k_y = (smooth.view(3, 1, 1) * diff.view(1, 3, 1) * smooth.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
k_z = (diff.view(3, 1, 1) * smooth.view(1, 3, 1) * smooth.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
self.register_buffer('k_x', k_x)
self.register_buffer('k_y', k_y)
self.register_buffer('k_z', k_z)
def forward(self, x: torch.Tensor) -> torch.Tensor:
N, C, D, H, W = x.shape
weight_x = self.k_x.expand(C, 1, 3, 3, 3)
weight_y = self.k_y.expand(C, 1, 3, 3, 3)
weight_z = self.k_z.expand(C, 1, 3, 3, 3)
gx = F.conv3d(x, weight_x, padding=1, groups=C)
gy = F.conv3d(x, weight_y, padding=1, groups=C)
gz = F.conv3d(x, weight_z, padding=1, groups=C)
return gx*gx + gy*gy + gz*gz
N = 4
C = 4
D = 64
H = 128
W = 128
def get_inputs():
x = torch.randint(0, 10, (N, C, D, H, W), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

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

@ -0,0 +1,74 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from sobel_filter_3d_torch import Model,get_inputs,get_init_inputs
from sobel_filter_3d_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,132 @@
import torch
from torch.utils.cpp_extension import load_inline
sobel_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void sobel_3d_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int D, int H, int W,
long spatial_size, // H * W
long volume_size // D * H * W
) {
int nc_idx = blockIdx.z; // Index of the (n, c) volume
int d = blockIdx.y;
int spatial_idx = blockIdx.x * blockDim.x + threadIdx.x;
if (spatial_idx < spatial_size) {
int h = spatial_idx / W;
int w = spatial_idx % W;
const float* vol_in = input + nc_idx * volume_size;
float* vol_out = output + nc_idx * volume_size;
float gx = 0.0f;
float gy = 0.0f;
float gz = 0.0f;
#pragma unroll
for (int kz = -1; kz <= 1; ++kz) {
int in_d = d + kz;
float wz_s = (kz == 0) ? 2.0f : 1.0f; // Smooth weight
float wz_d = (float)kz; // Diff weight (-1, 0, 1)
// Y Loop
#pragma unroll
for (int ky = -1; ky <= 1; ++ky) {
int in_h = h + ky;
float wy_s = (ky == 0) ? 2.0f : 1.0f;
float wy_d = (float)ky;
// X Loop
#pragma unroll
for (int kx = -1; kx <= 1; ++kx) {
int in_w = w + kx;
float wx_s = (kx == 0) ? 2.0f : 1.0f;
float wx_d = (float)kx;
// Boundary Check (Zero Padding)
float val = 0.0f;
if (in_d >= 0 && in_d < D &&
in_h >= 0 && in_h < H &&
in_w >= 0 && in_w < W)
{
// Calculate offset manually to avoid multiplication if possible
// But here stride is necessary
long idx = (long)in_d * spatial_size + (long)in_h * W + in_w;
val = __ldg(&vol_in[idx]);
}
// Accumulate Gradients
// Gx: Smooth(z) * Smooth(y) * Diff(x)
gx += val * (wz_s * wy_s * wx_d);
// Gy: Smooth(z) * Diff(y) * Smooth(x)
gy += val * (wz_s * wy_d * wx_s);
// Gz: Diff(z) * Smooth(y) * Smooth(x)
gz += val * (wz_d * wy_s * wx_s);
}
}
}
// Write Result: Squared Magnitude
long out_idx = (long)d * spatial_size + spatial_idx;
vol_out[out_idx] = gx * gx + gy * gy + gz * gz;
}
}
torch::Tensor sobel_3d_cuda(torch::Tensor input) {
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);
// Output shape same as input
auto output = torch::empty_like(input);
long spatial_size = H * W;
long volume_size = D * spatial_size;
int nc = N * C;
// Grid Config
const int block = 256;
dim3 grid((spatial_size + block - 1) / block, D, nc);
sobel_3d_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
D, H, W,
spatial_size,
volume_size
);
return output;
}
"""
cpp_source = "torch::Tensor sobel_3d_cuda(torch::Tensor input);"
sobel_module = load_inline(
name="sobel_filter_3d_extension",
cpp_sources=cpp_source,
cuda_sources=sobel_source,
functions=["sobel_3d_cuda"],
verbose=True,
with_cuda=True
)
class ModelNew(torch.nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.cuda_op = sobel_module
def forward(self, x):
return self.cuda_op.sobel_3d_cuda(x.contiguous())

View File

@ -0,0 +1,50 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.backends.cuda.matmul.allow_tf32 = False
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
smooth = torch.tensor([1., 2., 1.], dtype=torch.float32)
diff = torch.tensor([-1., 0., 1.], dtype=torch.float32)
k_x = (smooth.view(3, 1, 1) * smooth.view(1, 3, 1) * diff.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
k_y = (smooth.view(3, 1, 1) * diff.view(1, 3, 1) * smooth.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
k_z = (diff.view(3, 1, 1) * smooth.view(1, 3, 1) * smooth.view(1, 1, 3)).unsqueeze(0).unsqueeze(0)
self.register_buffer('k_x', k_x)
self.register_buffer('k_y', k_y)
self.register_buffer('k_z', k_z)
def forward(self, x: torch.Tensor) -> torch.Tensor:
N, C, D, H, W = x.shape
weight_x = self.k_x.expand(C, 1, 3, 3, 3)
weight_y = self.k_y.expand(C, 1, 3, 3, 3)
weight_z = self.k_z.expand(C, 1, 3, 3, 3)
gx = F.conv3d(x, weight_x, padding=1, groups=C)
gy = F.conv3d(x, weight_y, padding=1, groups=C)
gz = F.conv3d(x, weight_z, padding=1, groups=C)
return gx*gx + gy*gy + gz*gz
N = 4
C = 4
D = 64
H = 128
W = 128
def get_inputs():
x = torch.randint(0, 10, (N, C, D, H, W), device='cuda').float()
return [x]
def get_init_inputs():
return []