Merge pull request 'fixes upsamplingnearest2d Operator #21' (#45) from ZZZJ/GPUCodeForces:upsamplingnearest2d into main

This commit is contained in:
Kuohais 2025-11-06 22:03:58 +08:00
commit e3a2776067
4 changed files with 284 additions and 0 deletions

35
S1/21/prompt.txt Normal file
View File

@ -0,0 +1,35 @@
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
# upsample_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 16
CHANNELS = 64
H_IN, W_IN = 128, 128
SCALE_FACTOR = 2
class Model(nn.Module):
def __init__(self):
super().__init__()
self.upsample = nn.UpsamplingNearest2d(scale_factor=SCALE_FACTOR)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.upsample(input)
def get_inputs():
input_tensor = torch.randn(BATCH_SIZE, CHANNELS, H_IN, W_IN, dtype=torch.float32)
return [input_tensor]
def get_init_inputs():
return []

88
S1/21/run_code.py Normal file
View File

@ -0,0 +1,88 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from upsample_torch import Model, get_inputs, get_init_inputs
from upsample_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)
# 更严格的精度检查
abs_diff = (output_torch - output_cuda).abs()
max_diff = abs_diff.max().item()
mean_diff = abs_diff.mean().item()
print(f"最大差异: {max_diff:.6f}")
print(f"平均差异: {mean_diff:.6f}")
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
if precision_flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
# Warm up
for _ in range(100):
_ = torch_model(*inputs)
_ = cuda_model(*inputs)
# 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 (matmul + relu) 平均执行时间: {torch_time:.6f}")
print(f"自定义 CUDA ReLU 平均执行时间: {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()

133
S1/21/upsample_cuda.py Normal file
View File

@ -0,0 +1,133 @@
# upsample_cuda.py
import torch
from torch.utils.cpp_extension import load_inline
from upsample_torch import BATCH_SIZE, CHANNELS, H_IN, W_IN, SCALE_FACTOR # 导入维度常量
W_OUT = W_IN * SCALE_FACTOR
assert W_OUT % 4 == 0, "Output width (W_in * scale) must be a multiple of 4 for float4 vectorization"
VEC_SIZE = 4
class ModelNew(torch.nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor upsample_forward_cuda(torch::Tensor input);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE 256
#define SCALE_VAL {scale_factor}
#define VEC_SIZE {vec_size}
__global__ void upsample_fused_vectorized_kernel(
const float* __restrict__ x,
float* __restrict__ y,
int N, int C, int H_in, int W_in
) {{
int H_out = H_in * SCALE_VAL;
int W_out = W_in * SCALE_VAL;
int W_out_vec = W_out / VEC_SIZE;
int CHW_out_vec = C * H_out * W_out_vec;
int C_HW_in = C * H_in * W_in;
int output_elements_vec = N * CHW_out_vec;
int grid_stride = gridDim.x * blockDim.x;
for (int idx_vec = blockIdx.x * blockDim.x + threadIdx.x;
idx_vec < output_elements_vec;
idx_vec += grid_stride)
{{
int n = idx_vec / CHW_out_vec;
int rem_n = idx_vec % CHW_out_vec;
int c = rem_n / (H_out * W_out_vec);
int rem_c = rem_n % (H_out * W_out_vec);
int h_out = rem_c / W_out_vec;
int w_out_vec = rem_c % W_out_vec;
int h_in = h_out / SCALE_VAL;
long base_input_idx = (long)n * C_HW_in +
(long)c * (H_in * W_in) +
(long)h_in * W_in;
float4* y4_ptr = reinterpret_cast<float4*>(y);
int w_out_start = w_out_vec * VEC_SIZE;
int w_in_start = w_out_start / SCALE_VAL;
float val_in_0 = x[base_input_idx + w_in_start];
float val_in_1 = x[base_input_idx + w_in_start + 1];
float4 output_vec;
output_vec.x = val_in_0;
output_vec.y = val_in_0;
output_vec.z = val_in_1;
output_vec.w = val_in_1;
y4_ptr[idx_vec] = output_vec;
}}
}}
torch::Tensor upsample_forward_cuda(torch::Tensor input) {{
TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
input = input.contiguous();
int N = input.size(0);
int C = input.size(1);
int H_in = input.size(2);
int W_in = input.size(3);
int up_factor = SCALE_VAL;
int H_out = H_in * up_factor;
int W_out = W_in * up_factor;
TORCH_CHECK(W_out % VEC_SIZE == 0, "Output width must be divisible by 4 for float4 vectorization");
auto output = torch::empty({{N, C, H_out, W_out}}, input.options());
int n_elements_vec = output.numel() / VEC_SIZE;
const int block_size = 256;
const int grid_size = (n_elements_vec + block_size - 1) / block_size;
upsample_fused_vectorized_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
N, C, H_in, W_in
);
return output;
}}
""".format(scale_factor=SCALE_FACTOR, vec_size=VEC_SIZE)
self.ps_op = load_inline(
name="upsample_fused_vectorized_op_final",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["upsample_forward_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=True
)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.ps_op.upsample_forward_cuda(input)

28
S1/21/upsample_torch.py Normal file
View File

@ -0,0 +1,28 @@
# upsample_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 16
CHANNELS = 64
H_IN, W_IN = 128, 128
SCALE_FACTOR = 2
class Model(nn.Module):
def __init__(self):
super().__init__()
self.upsample = nn.UpsamplingNearest2d(scale_factor=SCALE_FACTOR)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.upsample(input)
def get_inputs():
input_tensor = torch.randn(BATCH_SIZE, CHANNELS, H_IN, W_IN, dtype=torch.float32)
return [input_tensor]
def get_init_inputs():
return []