fixes Permute #143

This commit is contained in:
ZZZJ 2025-12-09 21:28:00 +08:00
parent cc73715277
commit 33fd9f8f6a
4 changed files with 261 additions and 0 deletions

View File

@ -0,0 +1,133 @@
import torch
from torch.utils.cpp_extension import load_inline
permute_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#define TILE_DIM 32
#define BLOCK_ROWS 8
__global__ void permute_021_opt_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int H, int W)
{
// Padding to avoid bank conflicts in Shared Memory
__shared__ float tile[TILE_DIM][TILE_DIM + 1];
int b_idx = blockIdx.z;
// Diagonal Reordering to avoid Partition Camping
// Map blockIdx to a diagonal coordinate system
int grid_width = gridDim.x;
int grid_height = gridDim.y;
int block_x = blockIdx.x;
int block_y = (blockIdx.x + blockIdx.y) % grid_height;
// 1. Coalesced Read (Input: H x W)
// x corresponds to W (contig dim of input)
// y corresponds to H
int x = block_x * TILE_DIM + threadIdx.x;
int y = block_y * TILE_DIM + threadIdx.y;
// Base offset for this batch
// We process each batch independently
long batch_offset_in = (long)b_idx * H * W;
long batch_offset_out = (long)b_idx * W * H;
const float* input_b = input + batch_offset_in;
float* output_b = output + batch_offset_out;
// Load Loop (ILP = 4)
// Each thread loads 4 elements separated by BLOCK_ROWS
#pragma unroll
for (int j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
int current_y = y + j;
if (x < W && current_y < H) {
// Input is Row-Major: y * W + x
tile[threadIdx.y + j][threadIdx.x] = input_b[current_y * W + x];
}
}
__syncthreads();
// 2. Transpose Logic & Coalesced Write (Output: W x H)
// Output width is H, height is W.
// We want to write continuously along H.
// So threadIdx.x should map to H.
// Transpose coordinates relative to the Block
// Old x (W) becomes New y (Rows of output)
// Old y (H) becomes New x (Cols of output)
// New X (Output Col index) = Old Block Y * TILE + threadIdx.x
int out_x = block_y * TILE_DIM + threadIdx.x;
// New Y (Output Row index) = Old Block X * TILE + threadIdx.y
int out_y = block_x * TILE_DIM + threadIdx.y;
// Store Loop (ILP = 4)
#pragma unroll
for (int j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
int current_y = out_y + j;
if (out_x < H && current_y < W) {
// Output is Row-Major: y * H + x
// output[current_y][out_x]
// Read from Shared Memory (Transposed)
// We want value that was at Input[out_x][current_y]
// Input local coords: x=current_y(tx), y=out_x(ty) -> tile[ty][tx]
// But we mapped threadIdx.x to out_x (which was y)
// So we read tile[threadIdx.x][threadIdx.y + j]
float val = tile[threadIdx.x][threadIdx.y + j];
output_b[current_y * H + out_x] = val;
}
}
}
torch::Tensor permute_cuda(torch::Tensor input) {
int B = input.size(0);
int H = input.size(1);
int W = input.size(2);
auto output = torch::empty({B, W, H}, input.options());
// Block: 32 * 8 = 256 threads
dim3 block(TILE_DIM, BLOCK_ROWS);
// Grid: Covers W and H
// Grid X -> W, Grid Y -> H
dim3 grid((W + TILE_DIM - 1) / TILE_DIM, (H + TILE_DIM - 1) / TILE_DIM, B);
permute_021_opt_kernel<<<grid, block>>>(
input.data_ptr<float>(),
output.data_ptr<float>(),
H, W
);
return output;
}
"""
cpp_source = "torch::Tensor permute_cuda(torch::Tensor input);"
permute_module = load_inline(
name="permute_extension_v2",
cpp_sources=cpp_source,
cuda_sources=permute_source,
functions=["permute_cuda"],
verbose=True,
with_cuda=True
)
class ModelNew(torch.nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.cuda_op = permute_module
def forward(self, x):
return self.cuda_op.permute_cuda(x.contiguous())

View File

@ -0,0 +1,23 @@
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__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.permute(0, 2, 1).contiguous()
B = 64
H = 1024
W = 1024
def get_inputs():
x = torch.randn(B, H, W, device='cuda', dtype=torch.float32)
return [x]
def get_init_inputs():
return []

31
S1/ZZZJ_#143/prompt.txt Normal file
View File

@ -0,0 +1,31 @@
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__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.permute(0, 2, 1).contiguous()
B = 64
H = 1024
W = 1024
def get_inputs():
x = torch.randn(B, H, W, device='cuda', dtype=torch.float32)
return [x]
def get_init_inputs():
return []
```

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

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