diff --git a/S1/wwmm_#6/prompt.txt b/S1/wwmm_#6/prompt.txt new file mode 100644 index 0000000..751fd25 --- /dev/null +++ b/S1/wwmm_#6/prompt.txt @@ -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] \ No newline at end of file diff --git a/S1/wwmm_#6/replicationpad3d_cuda.py b/S1/wwmm_#6/replicationpad3d_cuda.py new file mode 100644 index 0000000..29d81d0 --- /dev/null +++ b/S1/wwmm_#6/replicationpad3d_cuda.py @@ -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::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 + #include + #include + + #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>>( + input.data_ptr(), + output.data_ptr(), + static_cast(N_64), + static_cast(C_64), + static_cast(D_in_64), + static_cast(H_in_64), + static_cast(W_in_64), + static_cast(D_out_64), + static_cast(H_out_64), + static_cast(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 + ) \ No newline at end of file diff --git a/S1/wwmm_#6/replicationpad3d_torch.py b/S1/wwmm_#6/replicationpad3d_torch.py new file mode 100644 index 0000000..303ca81 --- /dev/null +++ b/S1/wwmm_#6/replicationpad3d_torch.py @@ -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] \ No newline at end of file diff --git a/S1/wwmm_#6/run_code.py b/S1/wwmm_#6/run_code.py new file mode 100644 index 0000000..78e17d2 --- /dev/null +++ b/S1/wwmm_#6/run_code.py @@ -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() \ No newline at end of file