forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish AvgPool2d #61' (#619) from ZZZJ/GPUCodeForces:AvgPool2d into main
This commit is contained in:
commit
50afbf095d
|
|
@ -0,0 +1,127 @@
|
|||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
avgpool_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
|
||||
__global__ void avgpool2d_opt_kernel(
|
||||
const float* __restrict__ input,
|
||||
float* __restrict__ output,
|
||||
int H_in, int W_in,
|
||||
int H_out, int W_out,
|
||||
int kernel_size, int stride, int padding,
|
||||
float inv_kernel_area,
|
||||
int total_elements_per_channel_in,
|
||||
int total_elements_per_channel_out
|
||||
) {
|
||||
|
||||
|
||||
// 1. Calculate Spatial Coordinates (No Division!)
|
||||
int w_out = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int h_out = blockIdx.y * blockDim.y + threadIdx.y;
|
||||
int nc = blockIdx.z;
|
||||
|
||||
// Check bounds
|
||||
if (w_out >= W_out || h_out >= H_out) return;
|
||||
|
||||
// 2. Base Pointers
|
||||
// Use long long for large tensor offsets
|
||||
long in_base = (long)nc * total_elements_per_channel_in;
|
||||
long out_base = (long)nc * total_elements_per_channel_out;
|
||||
|
||||
// 3. Compute Input Window Top-Left
|
||||
int h_start = h_out * stride - padding;
|
||||
int w_start = w_out * stride - padding;
|
||||
|
||||
float sum = 0.0f;
|
||||
|
||||
// 4. Pooling Loop
|
||||
// Compiler will unroll this for small constant kernel sizes (like 3)
|
||||
for (int ky = 0; ky < kernel_size; ++ky) {
|
||||
int h_in = h_start + ky;
|
||||
|
||||
if (h_in >= 0 && h_in < H_in) {
|
||||
// Pre-calculate row offset
|
||||
int row_offset = h_in * W_in;
|
||||
|
||||
for (int kx = 0; kx < kernel_size; ++kx) {
|
||||
int w_in = w_start + kx;
|
||||
|
||||
if (w_in >= 0 && w_in < W_in) {
|
||||
// Use __ldg for Read-Only Cache
|
||||
sum += __ldg(&input[in_base + row_offset + w_in]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Write Output
|
||||
int out_idx = h_out * W_out + w_out;
|
||||
output[out_base + out_idx] = sum * inv_kernel_area;
|
||||
}
|
||||
|
||||
torch::Tensor avgpool2d_cuda(torch::Tensor input, int kernel_size, int stride, int padding) {
|
||||
int N = input.size(0);
|
||||
int C = input.size(1);
|
||||
int H_in = input.size(2);
|
||||
int W_in = input.size(3);
|
||||
|
||||
int H_out = (H_in + 2 * padding - kernel_size) / stride + 1;
|
||||
int W_out = (W_in + 2 * padding - kernel_size) / stride + 1;
|
||||
|
||||
auto output = torch::empty({N, C, H_out, W_out}, input.options());
|
||||
|
||||
// Pre-calculate sizes
|
||||
int total_in = H_in * W_in;
|
||||
int total_out = H_out * W_out;
|
||||
int nc = N * C;
|
||||
|
||||
float inv_area = 1.0f / (kernel_size * kernel_size);
|
||||
|
||||
// Config: 2D Block for spatial, Grid Z for batch/channel
|
||||
// Block: 32x8 = 256 threads (Standard 2D tile)
|
||||
// ThreadIdx.x maps to Width (contiguous dimension) -> Coalesced Access
|
||||
dim3 block(32, 8);
|
||||
dim3 grid(
|
||||
(W_out + block.x - 1) / block.x,
|
||||
(H_out + block.y - 1) / block.y,
|
||||
nc
|
||||
);
|
||||
|
||||
avgpool2d_opt_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
H_in, W_in, H_out, W_out,
|
||||
kernel_size, stride, padding,
|
||||
inv_area,
|
||||
total_in,
|
||||
total_out
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = "torch::Tensor avgpool2d_cuda(torch::Tensor input, int kernel_size, int stride, int padding);"
|
||||
|
||||
avgpool_module = load_inline(
|
||||
name="avgpool2d_extension_v3",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=avgpool_source,
|
||||
functions=["avgpool2d_cuda"],
|
||||
verbose=True,
|
||||
with_cuda=True
|
||||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.kernel_size = 3
|
||||
self.stride = 2
|
||||
self.padding = 1
|
||||
self.cuda_op = avgpool_module
|
||||
|
||||
def forward(self, x):
|
||||
return self.cuda_op.avgpool2d_cuda(x.contiguous(), self.kernel_size, self.stride, self.padding)
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.kernel_size = 3
|
||||
self.stride = 2
|
||||
self.padding = 1
|
||||
|
||||
self.avg_pool = nn.AvgPool2d(
|
||||
kernel_size=self.kernel_size,
|
||||
stride=self.stride,
|
||||
padding=self.padding,
|
||||
count_include_pad=True
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.avg_pool(x)
|
||||
|
||||
N = 32
|
||||
C = 64
|
||||
H = 256
|
||||
W = 256
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randint(0, 16, (N, C, H, W), device='cuda').float()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
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
|
||||
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
self.kernel_size = 3
|
||||
self.stride = 2
|
||||
self.padding = 1
|
||||
|
||||
self.avg_pool = nn.AvgPool2d(
|
||||
kernel_size=self.kernel_size,
|
||||
stride=self.stride,
|
||||
padding=self.padding,
|
||||
count_include_pad=True
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.avg_pool(x)
|
||||
|
||||
N = 32
|
||||
C = 64
|
||||
H = 256
|
||||
W = 256
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randint(0, 16, (N, C, H, W), device='cuda').float()
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from avgpool2d_torch import Model,get_inputs,get_init_inputs
|
||||
from avgpool2d_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()
|
||||
Loading…
Reference in New Issue