forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish Dropblock3d #194' (#938) from ZZZJ/GPUCodeForces:Dropblock3d into main
This commit is contained in:
commit
f23ee27255
|
|
@ -0,0 +1,191 @@
|
|||
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.block_size = 5
|
||||
self.keep_prob = 0.9
|
||||
self.gamma = None
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def calculate_gamma(self, x):
|
||||
D, H, W = x.shape[-3], x.shape[-2], x.shape[-1]
|
||||
vol = (D - self.block_size + 1) * (H - self.block_size + 1) * (W - self.block_size + 1)
|
||||
if vol <= 0: return 0.0
|
||||
return (1.0 - self.keep_prob) / (self.block_size ** 3) * (D * H * W) / vol
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor dropblock3d_cuda(torch::Tensor input, torch::Tensor rand, int block_size, float gamma, float scale);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
// Block Output Size: 4x8x8 = 256 threads
|
||||
#define TILE_D 4
|
||||
#define TILE_H 8
|
||||
#define TILE_W 8
|
||||
|
||||
// Kernel Radius (BlockSize=5 -> Radius=2)
|
||||
#define RADIUS 2
|
||||
|
||||
// Shared Memory Size for Rand
|
||||
#define SMEM_D (TILE_D + RADIUS * 2) // 4+4=8
|
||||
#define SMEM_H (TILE_H + RADIUS * 2) // 8+4=12
|
||||
#define SMEM_W (TILE_W + RADIUS * 2) // 8+4=12
|
||||
|
||||
__global__ void dropblock3d_smem_kernel(
|
||||
const float* __restrict__ input,
|
||||
const float* __restrict__ rand,
|
||||
float* __restrict__ output,
|
||||
int batch, int channels, int depth, int height, int width,
|
||||
float gamma,
|
||||
float scale
|
||||
) {
|
||||
// Grid Mapping
|
||||
// Block: 4x8x8
|
||||
int tx = threadIdx.x;
|
||||
int ty = threadIdx.y;
|
||||
int tz = threadIdx.z;
|
||||
|
||||
// Grid.x -> W blocks, Grid.y -> H blocks, Grid.z -> D blocks * B * C
|
||||
int w_blocks = (width + TILE_W - 1) / TILE_W;
|
||||
int h_blocks = (height + TILE_H - 1) / TILE_H;
|
||||
|
||||
int bz = blockIdx.z;
|
||||
int by = blockIdx.y;
|
||||
int bx = blockIdx.x;
|
||||
|
||||
int tmp = bz;
|
||||
int c = tmp % channels; tmp /= channels;
|
||||
int b = tmp;
|
||||
|
||||
int od_base = by / h_blocks * TILE_D;
|
||||
int oh_base = by % h_blocks * TILE_H;
|
||||
int ow_base = bx * TILE_W;
|
||||
|
||||
int od = od_base + tz;
|
||||
int oh = oh_base + ty;
|
||||
int ow = ow_base + tx;
|
||||
|
||||
// Shared Memory for Rand Tile
|
||||
__shared__ float smem[SMEM_D][SMEM_H][SMEM_W];
|
||||
|
||||
// 1. Cooperative Loading (Rand -> Smem)
|
||||
int rand_d_start = od_base - RADIUS;
|
||||
int rand_h_start = oh_base - RADIUS;
|
||||
int rand_w_start = ow_base - RADIUS;
|
||||
|
||||
int tid = tz * (TILE_H * TILE_W) + ty * TILE_W + tx; // 0..255
|
||||
int num_smem_elements = SMEM_D * SMEM_H * SMEM_W;
|
||||
|
||||
long long rand_plane_offset = (long long)b * (channels * depth * height * width) + c * (depth * height * width);
|
||||
|
||||
for (int i = tid; i < num_smem_elements; i += 256) {
|
||||
int sz = i / (SMEM_H * SMEM_W);
|
||||
int rem_s = i % (SMEM_H * SMEM_W);
|
||||
int sy = rem_s / SMEM_W;
|
||||
int sx = rem_s % SMEM_W;
|
||||
|
||||
int gd = rand_d_start + sz;
|
||||
int gh = rand_h_start + sy;
|
||||
int gw = rand_w_start + sx;
|
||||
|
||||
float val = 1.0f; // Default > gamma
|
||||
if (gd >= 0 && gd < depth && gh >= 0 && gh < height && gw >= 0 && gw < width) {
|
||||
val = rand[rand_plane_offset + gd * (height * width) + gh * width + gw];
|
||||
}
|
||||
smem[sz][sy][sx] = val;
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// 2. Compute
|
||||
if (od < depth && oh < height && ow < width) {
|
||||
|
||||
bool dropped = false;
|
||||
|
||||
// Window Search in Smem
|
||||
// Smem local coord for center: tz+R, ty+R, tx+R
|
||||
|
||||
// We check a 5x5x5 window. The window start in Smem: tz, ty, tx
|
||||
#pragma unroll
|
||||
for (int z = tz; z < tz + 2*RADIUS + 1; ++z) {
|
||||
#pragma unroll
|
||||
for (int y = ty; y < ty + 2*RADIUS + 1; ++y) {
|
||||
#pragma unroll
|
||||
for (int x = tx; x < tx + 2*RADIUS + 1; ++x) {
|
||||
if (smem[z][y][x] < gamma) {
|
||||
dropped = true;
|
||||
goto end_check;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
end_check:;
|
||||
|
||||
// 3. Apply & Write
|
||||
long long io_idx = rand_plane_offset + od * (height * width) + oh * width + ow;
|
||||
if (dropped) {
|
||||
output[io_idx] = 0.0f;
|
||||
} else {
|
||||
output[io_idx] = input[io_idx] * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor dropblock3d_cuda(torch::Tensor input, torch::Tensor rand, int block_size, float gamma, float scale) {
|
||||
int batch = input.size(0);
|
||||
int channels = input.size(1);
|
||||
int depth = input.size(2);
|
||||
int height = input.size(3);
|
||||
int width = input.size(4);
|
||||
|
||||
auto output = torch::empty_like(input);
|
||||
|
||||
dim3 block(TILE_W, TILE_H, TILE_D);
|
||||
|
||||
// Grid Mapping
|
||||
// X: Width Blocks
|
||||
// Y: Height * Depth Blocks (Flattened)
|
||||
// Z: Batch * Channel Blocks (Flattened)
|
||||
dim3 grid(
|
||||
(width + TILE_W - 1) / TILE_W,
|
||||
((height + TILE_H - 1) / TILE_H) * ((depth + TILE_D - 1) / TILE_D),
|
||||
batch * channels
|
||||
);
|
||||
|
||||
dropblock3d_smem_kernel<<<grid, block>>>(
|
||||
input.data_ptr<float>(),
|
||||
rand.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch, channels, depth, height, width,
|
||||
gamma, scale
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name="dropblock3d_smem_v1",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["dropblock3d_cuda"],
|
||||
extra_cuda_cflags=["-O3"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, rand: torch.Tensor) -> torch.Tensor:
|
||||
if self.gamma is None:
|
||||
self.gamma = self.calculate_gamma(x)
|
||||
if not x.is_contiguous(): x = x.contiguous()
|
||||
if not rand.is_contiguous(): rand = rand.contiguous()
|
||||
|
||||
scale = 1.0 / self.keep_prob
|
||||
|
||||
return self.op.dropblock3d_cuda(x, rand, self.block_size, self.gamma, scale)
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
BATCH = 8
|
||||
CHANNELS = 32
|
||||
DEPTH = 32
|
||||
HEIGHT = 64
|
||||
WIDTH = 64
|
||||
BLOCK_SIZE = 5
|
||||
KEEP_PROB = 0.9
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.block_size = BLOCK_SIZE
|
||||
self.keep_prob = KEEP_PROB
|
||||
self.gamma = None
|
||||
|
||||
def calculate_gamma(self, x):
|
||||
D, H, W = x.shape[-3], x.shape[-2], x.shape[-1]
|
||||
vol = (D - self.block_size + 1) * (H - self.block_size + 1) * (W - self.block_size + 1)
|
||||
if vol <= 0:
|
||||
return 0.0
|
||||
return (1.0 - self.keep_prob) / (self.block_size ** 3) * (D * H * W) / vol
|
||||
|
||||
def forward(self, x: torch.Tensor, rand_tensor: torch.Tensor) -> torch.Tensor:
|
||||
if self.gamma is None:
|
||||
self.gamma = self.calculate_gamma(x)
|
||||
|
||||
mask = (rand_tensor < self.gamma).float()
|
||||
|
||||
pad = self.block_size // 2
|
||||
mask = F.max_pool3d(mask, kernel_size=self.block_size, stride=1, padding=pad)
|
||||
|
||||
mask = 1.0 - mask
|
||||
|
||||
scale = 1.0 / self.keep_prob
|
||||
|
||||
return x * mask * scale
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(BATCH, CHANNELS, DEPTH, HEIGHT, WIDTH, device='cuda', dtype=torch.float32)
|
||||
rand = torch.rand_like(x)
|
||||
return [x, rand]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
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
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
BATCH = 8
|
||||
CHANNELS = 32
|
||||
DEPTH = 32
|
||||
HEIGHT = 64
|
||||
WIDTH = 64
|
||||
BLOCK_SIZE = 5
|
||||
KEEP_PROB = 0.9
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.block_size = BLOCK_SIZE
|
||||
self.keep_prob = KEEP_PROB
|
||||
self.gamma = None
|
||||
|
||||
def calculate_gamma(self, x):
|
||||
D, H, W = x.shape[-3], x.shape[-2], x.shape[-1]
|
||||
vol = (D - self.block_size + 1) * (H - self.block_size + 1) * (W - self.block_size + 1)
|
||||
if vol <= 0:
|
||||
return 0.0
|
||||
return (1.0 - self.keep_prob) / (self.block_size ** 3) * (D * H * W) / vol
|
||||
|
||||
def forward(self, x: torch.Tensor, rand_tensor: torch.Tensor) -> torch.Tensor:
|
||||
if self.gamma is None:
|
||||
self.gamma = self.calculate_gamma(x)
|
||||
|
||||
mask = (rand_tensor < self.gamma).float()
|
||||
|
||||
pad = self.block_size // 2
|
||||
mask = F.max_pool3d(mask, kernel_size=self.block_size, stride=1, padding=pad)
|
||||
|
||||
mask = 1.0 - mask
|
||||
|
||||
scale = 1.0 / self.keep_prob
|
||||
|
||||
return x * mask * scale
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(BATCH, CHANNELS, DEPTH, HEIGHT, WIDTH, device='cuda', dtype=torch.float32)
|
||||
rand = torch.rand_like(x)
|
||||
return [x, rand]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from dropblock3d_torch import Model,get_inputs,get_init_inputs
|
||||
from dropblock3d_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