diff --git a/S1/wwmm_#4/prompt.txt b/S1/wwmm_#4/prompt.txt new file mode 100644 index 00000000..29564b36 --- /dev/null +++ b/S1/wwmm_#4/prompt.txt @@ -0,0 +1,46 @@ +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 +# replicationpad1d_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + + +BATCH_SIZE = 32 +CHANNELS = 64 +WIDTH = 128 +PADDING = (3, 1) +PAD_L, PAD_R = PADDING + +WIDTH_OUT = WIDTH + PAD_L + PAD_R + + +class Model(nn.Module): + + def __init__(self, padding): + super().__init__() + + if isinstance(padding, int): + padding_tuple = (padding, padding) + else: + padding_tuple = padding + + self.pad_layer = nn.ReplicationPad1d(padding_tuple) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.pad_layer(x) + + +def get_inputs(): + + x = torch.randn(BATCH_SIZE, CHANNELS, WIDTH, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [PADDING] \ No newline at end of file diff --git a/S1/wwmm_#4/replicationpad1d_cuda.py b/S1/wwmm_#4/replicationpad1d_cuda.py new file mode 100644 index 00000000..f23f7fa0 --- /dev/null +++ b/S1/wwmm_#4/replicationpad1d_cuda.py @@ -0,0 +1,145 @@ +# replicationpad1d_cuda.py +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +from replicationpad1d_torch import BATCH_SIZE, CHANNELS, WIDTH, WIDTH_OUT, PADDING, PAD_L, PAD_R + +# 定义 CUDA 常量 +BLOCK_SIZE = 256 + +class ModelNew(nn.Module): + """ + ReplicationPad1d 的高性能 CUDA 融合核函数实现 + """ + + def __init__(self, padding): + super().__init__() + + if isinstance(padding, int): + self.pad_L = padding + self.pad_R = padding + else: + self.pad_L = padding[0] + self.pad_R = padding[1] + + self.width_in = WIDTH + self.width_out = WIDTH_OUT + self.block_size = BLOCK_SIZE + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + + cpp_header = f""" + #include + + torch::Tensor replication_pad1d_forward_cuda( + torch::Tensor input, + int pad_L, + int pad_R + ); + """ + + cuda_source = f""" + #include + #include + #include + + #define BLOCK_SIZE {self.block_size} + + /* + * ReplicationPad1d 融合核函数 + */ + __global__ void replication_pad1d_fused_kernel( + const float* __restrict__ input_data, + float* __restrict__ output_data, + int N, int C, int W_in, int W_out, + int pad_L, int pad_R + ) {{ + const int n_idx = blockIdx.x; + const int c_idx = blockIdx.y; + const int tid = threadIdx.x; + + // 当前 Batch * Channel 的起始偏移 + const int base_offset_in = (n_idx * C + c_idx) * W_in; + const int base_offset_out = (n_idx * C + c_idx) * W_out; + + const float* p_in = input_data + base_offset_in; + float* p_out = output_data + base_offset_out; + + // W_in_end 标记核心数据区的结束 + const int W_in_end = pad_L + W_in; + + // Grid-Strided Loop: 保证合并访存和负载均衡 + for (int j = tid; j < W_out; j += BLOCK_SIZE) {{ + int in_idx; + + if (j < pad_L) {{ + // 1. 左侧填充区: 复制左边界 (index 0) + in_idx = 0; + }} else if (j < W_in_end) {{ + // 2. 核心数据区: 复制原始数据 + in_idx = j - pad_L; + }} else {{ + // 3. 右侧填充区: 复制右边界 (index W_in - 1) + in_idx = W_in - 1; + }} + + p_out[j] = p_in[in_idx]; + }} + }} + + // C++ 封装函数 + torch::Tensor replication_pad1d_forward_cuda( + torch::Tensor input, + int pad_L, + int pad_R + ) {{ + TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor"); + TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); + TORCH_CHECK(input.dim() == 3, "input must be 3D (N, C, W)"); + + const int64_t N_64 = input.size(0); + const int64_t C_64 = input.size(1); + const int64_t W_in_64 = input.size(2); + + const int64_t W_out_64 = W_in_64 + pad_L + pad_R; + + auto output = torch::empty({{N_64, C_64, W_out_64}}, input.options()); + + // Grid 维度: N x C + dim3 grid_dim(N_64, C_64); + dim3 block_dim(BLOCK_SIZE); + + replication_pad1d_fused_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + static_cast(N_64), + static_cast(C_64), + static_cast(W_in_64), + static_cast(W_out_64), + pad_L, + pad_R + ); + + return output; + }} + """ + + # JIT (Just-In-Time) 编译 + self.pad_op = load_inline( + name="replication_pad1d_op_fixed", + cpp_sources=cpp_header, + cuda_sources=cuda_source, + functions=["replication_pad1d_forward_cuda"], + verbose=False + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + # 调用我们编译好的 CUDA C++ 函数 + return self.pad_op.replication_pad1d_forward_cuda( + x.contiguous(), + self.pad_L, + self.pad_R + ) \ No newline at end of file diff --git a/S1/wwmm_#4/replicationpad1d_torch.py b/S1/wwmm_#4/replicationpad1d_torch.py new file mode 100644 index 00000000..083aaa80 --- /dev/null +++ b/S1/wwmm_#4/replicationpad1d_torch.py @@ -0,0 +1,39 @@ +# replicationpad1d_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + + +BATCH_SIZE = 32 +CHANNELS = 64 +WIDTH = 128 +PADDING = (3, 1) +PAD_L, PAD_R = PADDING + +WIDTH_OUT = WIDTH + PAD_L + PAD_R + + +class Model(nn.Module): + + def __init__(self, padding): + super().__init__() + + if isinstance(padding, int): + padding_tuple = (padding, padding) + else: + padding_tuple = padding + + self.pad_layer = nn.ReplicationPad1d(padding_tuple) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.pad_layer(x) + + +def get_inputs(): + + x = torch.randn(BATCH_SIZE, CHANNELS, WIDTH, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + return [PADDING] \ No newline at end of file diff --git a/S1/wwmm_#4/run_code.py b/S1/wwmm_#4/run_code.py new file mode 100644 index 00000000..6bacad6d --- /dev/null +++ b/S1/wwmm_#4/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from replicationpad1d_torch import Model,get_inputs,get_init_inputs +from replicationpad1d_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