Merge pull request 'finish replicationpad3d #6' (#421) from wwmm/GPUCodeForces:replicationpad3d into main

This commit is contained in:
wawahejun 2025-12-14 22:58:14 +08:00
commit 06b71d4b74
4 changed files with 334 additions and 0 deletions

45
S1/wwmm_#6/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
# replicationpad3d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 4
CHANNELS = 64
D_IN, H_IN, W_IN = 32, 32, 32
PADDING = (1, 2, 3, 4, 5, 6)
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.ReplicationPad3d(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]

View File

@ -0,0 +1,177 @@
# replicationpad3d_cuda.py
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
from replicationpad3d_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 = 512
VEC_SIZE = 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.d_in = D_IN
self.h_in = H_IN
self.w_in = W_IN
self.d_out = D_OUT
self.h_out = H_OUT
self.w_out = W_OUT
self.block_size = BLOCK_SIZE
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_header = """
#include <torch/extension.h>
torch::Tensor replication_pad3d_forward_cuda(
torch::Tensor input,
int pad_L, int pad_R, int pad_T, int pad_B, int pad_F, int pad_K
);
"""
cuda_source = f"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <algorithm>
#define BLOCK_SIZE {self.block_size}
#define VEC_SIZE 4
__global__ void replication_pad3d_fused_kernel(
const float* __restrict__ input_data,
float* __restrict__ output_data,
int N, int C, int D_in, int H_in, int W_in, int D_out, int H_out, int W_out,
int pad_L, int pad_T, int pad_F
) {{
const int N_C_D_H_W_out = N * C * D_out * H_out * W_out;
const int tid_vec = blockIdx.x * blockDim.x + threadIdx.x;
const int grid_stride_vec = gridDim.x * blockDim.x;
const int CDHW_in = C * D_in * H_in * W_in;
const int DHW_in = D_in * H_in * W_in;
const int HW_in = H_in * W_in;
float4* __restrict__ p_out_vec = (float4*)output_data;
const int N_vec = N_C_D_H_W_out / VEC_SIZE;
for (int idx_vec = tid_vec; idx_vec < N_vec; idx_vec += grid_stride_vec) {{
const int start_idx = idx_vec * VEC_SIZE;
float4 output_val4;
for(int k=0; k<VEC_SIZE; k++) {{
const int idx = start_idx + k;
const int w_out = idx % W_out;
const int h_w_out = idx / W_out;
const int h_out = h_w_out % H_out;
const int d_h_w_out = h_w_out / H_out;
const int d_out = d_h_w_out % D_out;
const int n_c = d_h_w_out / D_out;
const int n_idx = n_c / C;
const int c_idx = n_c % C;
int d_rel = d_out - pad_F;
int d_in = std::max(0, std::min(D_in - 1, d_rel));
int h_rel = h_out - pad_T;
int h_in = std::max(0, std::min(H_in - 1, h_rel));
int w_rel = w_out - pad_L;
int w_in = std::max(0, std::min(W_in - 1, w_rel));
const int base_offset_in = (n_idx * CDHW_in) + (c_idx * DHW_in);
const int in_idx = base_offset_in + (d_in * HW_in) + (h_in * W_in) + w_in;
if (k == 0) output_val4.x = input_data[in_idx];
if (k == 1) output_val4.y = input_data[in_idx];
if (k == 2) output_val4.z = input_data[in_idx];
if (k == 3) output_val4.w = input_data[in_idx];
}}
p_out_vec[idx_vec] = output_val4;
}}
}}
torch::Tensor replication_pad3d_forward_cuda(
torch::Tensor input,
int pad_L, int pad_R, int pad_T, int pad_B, int pad_F, int pad_K
) {{
TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
input = input.contiguous();
const int64_t N_64 = input.size(0);
const int64_t C_64 = input.size(1);
const int64_t D_in_64 = input.size(2);
const int64_t H_in_64 = input.size(3);
const int64_t W_in_64 = input.size(4);
const int64_t D_out_64 = D_in_64 + pad_F + pad_K;
const int64_t H_out_64 = H_in_64 + pad_T + pad_B;
const int64_t W_out_64 = W_in_64 + pad_L + pad_R;
const int N_elements_out = N_64 * C_64 * D_out_64 * H_out_64 * W_out_64;
TORCH_CHECK(N_elements_out % VEC_SIZE == 0, "Output size must be divisible by 4 for vectorization.");
auto output = torch::empty({{N_64, C_64, D_out_64, H_out_64, W_out_64}}, input.options());
dim3 block_dim(BLOCK_SIZE);
const int grid_size = (N_elements_out / VEC_SIZE + BLOCK_SIZE - 1) / BLOCK_SIZE;
dim3 grid_dim(grid_size);
replication_pad3d_fused_kernel<<<grid_dim, block_dim>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
static_cast<int>(N_64),
static_cast<int>(C_64),
static_cast<int>(D_in_64),
static_cast<int>(H_in_64),
static_cast<int>(W_in_64),
static_cast<int>(D_out_64),
static_cast<int>(H_out_64),
static_cast<int>(W_out_64),
pad_L,
pad_T,
pad_F
);
return output;
}}
"""
self.pad_op = load_inline(
name="replication_pad3d_op",
cpp_sources=cpp_header,
cuda_sources=cuda_source,
functions=["replication_pad3d_forward_cuda"],
verbose=False
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.pad_op.replication_pad3d_forward_cuda(
x.contiguous(),
self.pad_L,
self.pad_R,
self.pad_T,
self.pad_B,
self.pad_F,
self.pad_K
)

View File

@ -0,0 +1,38 @@
# replicationpad3d_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 4
CHANNELS = 64
D_IN, H_IN, W_IN = 32, 32, 32
PADDING = (1, 2, 3, 4, 5, 6)
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.ReplicationPad3d(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/wwmm_#6/run_code.py Normal file
View File

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