fixes Circularpad3d #186

This commit is contained in:
ZZZJ 2025-12-10 22:57:42 +08:00
parent cc73715277
commit 48201d38e4
4 changed files with 376 additions and 0 deletions

View File

@ -0,0 +1,220 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from circularpad3d_torch import (
BATCH_SIZE, CHANNELS,
D_IN, H_IN, W_IN,
D_OUT, H_OUT, W_OUT,
PADDING
)
PAD_L, PAD_R, PAD_T, PAD_B, PAD_F, PAD_K = PADDING
BLOCK_SIZE = 256
VEC_SIZE = 4
ILP_FACTOR = 4
class ModelNew(nn.Module):
def __init__(self, padding):
super().__init__()
self.pad_l = padding[0]
self.pad_r = padding[1]
self.pad_t = padding[2]
self.pad_b = padding[3]
self.pad_f = padding[4]
self.pad_k = padding[5]
self._compile_cuda_kernel_static()
def _compile_cuda_kernel_static(self):
macros = f"""
#define BLOCK_SIZE {BLOCK_SIZE}
#define VEC_SIZE {VEC_SIZE}
#define ILP {ILP_FACTOR}
#define D_IN {D_IN}
#define H_IN {H_IN}
#define W_IN {W_IN}
#define D_OUT {D_OUT}
#define H_OUT {H_OUT}
#define W_OUT {W_OUT}
#define PAD_L {self.pad_l}
#define PAD_T {self.pad_t}
#define PAD_F {self.pad_f}
#define HW_IN ({H_IN} * {W_IN})
#define DHW_IN ({D_IN} * {H_IN} * {W_IN})
#define HW_OUT ({H_OUT} * {W_OUT})
#define DHW_OUT ({D_OUT} * {H_OUT} * {W_OUT})
"""
cpp_header = """
#include <torch/extension.h>
torch::Tensor circularpad3d_cuda(torch::Tensor input);
"""
cuda_source = f"""
#include <torch/extension.h>
#include <cuda_runtime.h>
{macros}
__device__ __forceinline__ void val_vec_set_elem(float4& v, int idx, float val) {{
if (idx == 0) v.x = val;
else if (idx == 1) v.y = val;
else if (idx == 2) v.z = val;
else v.w = val;
}}
__global__ void __launch_bounds__(BLOCK_SIZE) circularpad3d_kernel_static(
const float* __restrict__ input_data,
float* __restrict__ output_data,
int total_vecs,
int total_elements
) {{
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
float4* out_ptr = (float4*)output_data;
for (int i = tid; i < total_vecs; i += stride * ILP) {{
#pragma unroll
for (int k = 0; k < ILP; ++k) {{
int idx = i + k * stride;
if (idx >= total_vecs) break;
int start_linear_idx = idx * VEC_SIZE;
int w_out_base = start_linear_idx % W_OUT;
int tmp = start_linear_idx / W_OUT;
int h_out_base = tmp % H_OUT;
tmp = tmp / H_OUT;
int d_out_base = tmp % D_OUT;
int nc_idx = tmp / D_OUT;
int input_base_addr = nc_idx * DHW_IN;
float4 val_vec;
#pragma unroll
for (int v = 0; v < VEC_SIZE; ++v) {{
int cur_w = w_out_base + v;
int cur_h = h_out_base;
int cur_d = d_out_base;
if (cur_w >= W_OUT) {{
cur_w -= W_OUT;
cur_h++;
if (cur_h >= H_OUT) {{
cur_h = 0;
cur_d++;
if (cur_d >= D_OUT) {{
cur_d = 0;
input_base_addr += DHW_IN;
}}
}}
}}
int d_offset = cur_d - PAD_F;
int d_in = d_offset % D_IN;
if (d_in < 0) d_in += D_IN;
int h_offset = cur_h - PAD_T;
int h_in = h_offset % H_IN;
if (h_in < 0) h_in += H_IN;
int w_offset = cur_w - PAD_L;
int w_in = w_offset % W_IN;
if (w_in < 0) w_in += W_IN;
int read_idx = input_base_addr
+ d_in * HW_IN
+ h_in * W_IN
+ w_in;
val_vec_set_elem(val_vec, v, input_data[read_idx]);
}}
out_ptr[idx] = val_vec;
}}
}}
int tail_start = total_vecs * VEC_SIZE;
for (int k = tail_start + tid; k < total_elements; k += stride) {{
int w_out = k % W_OUT;
int tmp = k / W_OUT;
int h_out = tmp % H_OUT;
tmp = tmp / H_OUT;
int d_out = tmp % D_OUT;
int nc_idx = tmp / D_OUT;
int d_in = (d_out - PAD_F) % D_IN;
if (d_in < 0) d_in += D_IN;
int h_in = (h_out - PAD_T) % H_IN;
if (h_in < 0) h_in += H_IN;
int w_in = (w_out - PAD_L) % W_IN;
if (w_in < 0) w_in += W_IN;
int read_idx = nc_idx * DHW_IN + d_in * HW_IN + h_in * W_IN + w_in;
output_data[k] = input_data[read_idx];
}}
}}
torch::Tensor circularpad3d_cuda(torch::Tensor input) {{
input = input.contiguous();
auto output = torch::empty(
{{input.size(0), input.size(1), D_OUT, H_OUT, W_OUT}},
input.options()
);
int64_t total_elements = output.numel();
int total_vecs = total_elements / VEC_SIZE;
int tasks = (total_vecs + ILP - 1) / ILP;
int grid_size = (tasks + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (grid_size > 65535) grid_size = 65535;
if (grid_size == 0) grid_size = 1;
circularpad3d_kernel_static<<<grid_size, BLOCK_SIZE>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
total_vecs,
(int)total_elements
);
return output;
}}
"""
self.pad_op = load_inline(
name="circularpad3d_static_opt",
cpp_sources=cpp_header,
cuda_sources=cuda_source,
functions=["circularpad3d_cuda"],
verbose=False,
extra_cuda_cflags=["-O3", "--use_fast_math"]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.pad_op.circularpad3d_cuda(x)

View File

@ -0,0 +1,37 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 8
CHANNELS = 32
D_IN = 32
H_IN = 64
W_IN = 64
PADDING = (2, 4, 1, 3, 2, 5)
PAD_L, PAD_R, PAD_T, PAD_B, PAD_F, PAD_K = PADDING
D_OUT = D_IN + PAD_F + PAD_K
H_OUT = H_IN + PAD_T + PAD_B
W_OUT = W_IN + PAD_L + PAD_R
class Model(nn.Module):
def __init__(self, padding):
super().__init__()
self.pad_layer = nn.CircularPad3d(padding)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.pad_layer(x)
def get_inputs():
x = torch.randn(BATCH_SIZE, CHANNELS, D_IN, H_IN, W_IN, dtype=torch.float32)
return [x]
def get_init_inputs():
return [PADDING]

45
S1/ZZZJ_#186/prompt.txt Normal file
View File

@ -0,0 +1,45 @@
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
BATCH_SIZE = 8
CHANNELS = 32
D_IN = 32
H_IN = 64
W_IN = 64
PADDING = (2, 4, 1, 3, 2, 5)
PAD_L, PAD_R, PAD_T, PAD_B, PAD_F, PAD_K = PADDING
D_OUT = D_IN + PAD_F + PAD_K
H_OUT = H_IN + PAD_T + PAD_B
W_OUT = W_IN + PAD_L + PAD_R
class Model(nn.Module):
def __init__(self, padding):
super().__init__()
self.pad_layer = nn.CircularPad3d(padding)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.pad_layer(x)
def get_inputs():
x = torch.randn(BATCH_SIZE, CHANNELS, D_IN, H_IN, W_IN, dtype=torch.float32)
return [x]
def get_init_inputs():
return [PADDING]
```

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

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