diff --git a/S1/ZZZJ_#166/kronecker_product_cuda.py b/S1/ZZZJ_#166/kronecker_product_cuda.py new file mode 100644 index 00000000..0b1757fd --- /dev/null +++ b/S1/ZZZJ_#166/kronecker_product_cuda.py @@ -0,0 +1,97 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_src = """ +torch::Tensor kronecker_product_cuda(torch::Tensor a, torch::Tensor b); +""" + +cuda_src = """ +#include +#include + +__global__ void __launch_bounds__(512) kronecker_product_kernel( + const float* __restrict__ a, + const float* __restrict__ b, + float* __restrict__ output, + int r1, int c1, + int r2, int c2, + int out_cols, + int64_t total_elements +) { + int64_t idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx >= total_elements) return; + + int col_out = idx % out_cols; + int row_out = idx / out_cols; + + int row_a = row_out / r2; + int col_a = col_out / c2; + int row_b = row_out % r2; + int col_b = col_out % c2; + + float val_a = a[row_a * c1 + col_a]; + float val_b = b[row_b * c2 + col_b]; + + output[idx] = val_a * val_b; +} + +torch::Tensor kronecker_product_cuda(torch::Tensor a, torch::Tensor b) { + if (a.dim() != 2 || b.dim() != 2) { + return torch::kron(a, b); + } + + int r1 = a.size(0); + int c1 = a.size(1); + int r2 = b.size(0); + int c2 = b.size(1); + + int out_rows = r1 * r2; + int out_cols = c1 * c2; + int64_t total_elements = (int64_t)out_rows * out_cols; + + auto output = torch::empty({out_rows, out_cols}, a.options()); + + a = a.contiguous(); + b = b.contiguous(); + + const int block_size = 512; + int64_t grid_size = (total_elements + block_size - 1) / block_size; + if (grid_size > 2147483647) grid_size = 2147483647; + + kronecker_product_kernel<<>>( + a.data_ptr(), + b.data_ptr(), + output.data_ptr(), + r1, c1, + r2, c2, + out_cols, + total_elements + ); + + return output; +} +""" + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self.module = load_inline( + name="kronecker_product_opt", + cpp_sources=cpp_src, + cuda_sources=cuda_src, + functions=["kronecker_product_cuda"], + verbose=False, + extra_cuda_cflags=["-O3"] + ) + + def forward(self, a, b): + return self.module.kronecker_product_cuda(a, b) + +def get_inputs(): + a = torch.randn(64, 64, dtype=torch.float32) + b = torch.randn(64, 64, dtype=torch.float32) + return [a, b] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#166/kronecker_product_torch.py b/S1/ZZZJ_#166/kronecker_product_torch.py new file mode 100644 index 00000000..f098cc9a --- /dev/null +++ b/S1/ZZZJ_#166/kronecker_product_torch.py @@ -0,0 +1,17 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, a, b): + return torch.kron(a, b) + +def get_inputs(): + a = torch.randn(64, 64, dtype=torch.float32) + b = torch.randn(64, 64, dtype=torch.float32) + return [a, b] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#166/prompt.txt b/S1/ZZZJ_#166/prompt.txt new file mode 100644 index 00000000..9b1da167 --- /dev/null +++ b/S1/ZZZJ_#166/prompt.txt @@ -0,0 +1,24 @@ +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 + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, a, b): + return torch.kron(a, b) + +def get_inputs(): + a = torch.randn(64, 64, dtype=torch.float32) + b = torch.randn(64, 64, dtype=torch.float32) + return [a, b] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#166/run_code.py b/S1/ZZZJ_#166/run_code.py new file mode 100644 index 00000000..87ede414 --- /dev/null +++ b/S1/ZZZJ_#166/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from kronecker_product_torch import Model,get_inputs,get_init_inputs +from kronecker_product_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