finish Fold #196

This commit is contained in:
wawahejun 2025-12-14 17:41:28 +08:00
commit 2c144becee
4 changed files with 318 additions and 0 deletions

164
S1/ZZZJ_#196/fold_cuda.py Normal file
View File

@ -0,0 +1,164 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.kernel_size = 3
self.stride = 1
self.padding = 1
self.height = 64
self.width = 64
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor fold_cuda(torch::Tensor input, int output_h, int output_w, int k_size, int stride, int padding);
"""
cuda_source = """
#include <cuda_runtime.h>
#define BLOCK_SIZE 256
__global__ void fold_gather_f4_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int n_vec,
int batch,
int channels,
int out_h,
int out_w,
int k_size,
int stride,
int padding,
int L_in
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= n_vec) return;
int w_vec_dim = out_w / 4;
int tmp = idx;
int w_vec = tmp % w_vec_dim; tmp /= w_vec_dim;
int h = tmp % out_h; tmp /= out_h;
int c = tmp % channels;
int b = tmp / channels;
int w_start = w_vec * 4;
float sum0 = 0.0f, sum1 = 0.0f, sum2 = 0.0f, sum3 = 0.0f;
long long input_batch_offset = (long long)b * (channels * k_size * k_size * L_in);
for (int kh = 0; kh < k_size; ++kh) {
int dist_h = h + padding - kh;
if (dist_h % stride == 0) {
int win_h = dist_h / stride;
int grid_w = (out_w + 2 * padding - k_size) / stride + 1;
int grid_h = (out_h + 2 * padding - k_size) / stride + 1;
if (win_h >= 0 && win_h < grid_h) {
for (int kw = 0; kw < k_size; ++kw) {
// Input Channel Offset: c * K*K + kh*K + kw
int c_in_idx = c * k_size * k_size + kh * k_size + kw;
long long input_channel_ptr = input_batch_offset + (long long)c_in_idx * L_in;
int dist_w0 = w_start + 0 + padding - kw;
int dist_w1 = w_start + 1 + padding - kw;
int dist_w2 = w_start + 2 + padding - kw;
int dist_w3 = w_start + 3 + padding - kw;
// Pixel 0
if (dist_w0 % stride == 0) {
int win_w = dist_w0 / stride;
if (win_w >= 0 && win_w < grid_w) {
int l_idx = win_h * grid_w + win_w;
sum0 += input[input_channel_ptr + l_idx];
}
}
// Pixel 1
if (dist_w1 % stride == 0) {
int win_w = dist_w1 / stride;
if (win_w >= 0 && win_w < grid_w) {
int l_idx = win_h * grid_w + win_w;
sum1 += input[input_channel_ptr + l_idx];
}
}
// Pixel 2
if (dist_w2 % stride == 0) {
int win_w = dist_w2 / stride;
if (win_w >= 0 && win_w < grid_w) {
int l_idx = win_h * grid_w + win_w;
sum2 += input[input_channel_ptr + l_idx];
}
}
// Pixel 3
if (dist_w3 % stride == 0) {
int win_w = dist_w3 / stride;
if (win_w >= 0 && win_w < grid_w) {
int l_idx = win_h * grid_w + win_w;
sum3 += input[input_channel_ptr + l_idx];
}
}
}
}
}
}
long long out_idx = (long long)b * (channels * out_h * out_w) + c * (out_h * out_w) + h * out_w + w_start;
output[out_idx + 0] = sum0;
output[out_idx + 1] = sum1;
output[out_idx + 2] = sum2;
output[out_idx + 3] = sum3;
}
torch::Tensor fold_cuda(torch::Tensor input, int output_h, int output_w, int k_size, int stride, int padding) {
int batch = input.size(0);
int c_total = input.size(1); // C * K * K
int L_in = input.size(2);
int channels = c_total / (k_size * k_size);
auto output = torch::empty({batch, channels, output_h, output_w}, input.options());
if (output_w % 4 != 0) return output;
long long total_elements = output.numel();
int n_vec = total_elements / 4;
const int block_size = 256;
const int grid_size = (n_vec + block_size - 1) / block_size;
fold_gather_f4_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
n_vec,
batch, channels, output_h, output_w,
k_size, stride, padding, L_in
);
return output;
}
"""
self.op = load_inline(
name="fold_gather_f4_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["fold_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not x.is_contiguous(): x = x.contiguous()
return self.op.fold_cuda(x, self.height, self.width, self.kernel_size, self.stride, self.padding)

View File

@ -0,0 +1,36 @@
import torch
import torch.nn as nn
BATCH = 16
CHANNELS = 64
HEIGHT = 64
WIDTH = 64
KERNEL_SIZE = 3
STRIDE = 1
PADDING = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
self.fold = nn.Fold(
output_size=(HEIGHT, WIDTH),
kernel_size=KERNEL_SIZE,
dilation=1,
padding=PADDING,
stride=STRIDE
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fold(x)
def get_inputs():
L = HEIGHT * WIDTH
C_in = CHANNELS * KERNEL_SIZE * KERNEL_SIZE
x = torch.randint(low=-2, high=3, size=(BATCH, C_in, L), device='cuda').float()
return [x]
def get_init_inputs():
return []

44
S1/ZZZJ_#196/prompt.txt Normal file
View File

@ -0,0 +1,44 @@
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
BATCH = 16
CHANNELS = 64
HEIGHT = 64
WIDTH = 64
KERNEL_SIZE = 3
STRIDE = 1
PADDING = 1
class Model(nn.Module):
def __init__(self):
super().__init__()
self.fold = nn.Fold(
output_size=(HEIGHT, WIDTH),
kernel_size=KERNEL_SIZE,
dilation=1,
padding=PADDING,
stride=STRIDE
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fold(x)
def get_inputs():
L = HEIGHT * WIDTH
C_in = CHANNELS * KERNEL_SIZE * KERNEL_SIZE
x = torch.randint(low=-2, high=3, size=(BATCH, C_in, L), device='cuda').float()
return [x]
def get_init_inputs():
return []
```

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

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