Merge pull request 'finish BhattacharyyaDistance #5' (#104) from uucoco/GPUCodeForces:uucoco5 into main

This commit is contained in:
Kuohais 2025-11-14 09:50:17 +08:00
commit d94a6585c2
4 changed files with 431 additions and 0 deletions

View File

@ -0,0 +1,224 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
N, C, H, W = 32, 64, 56, 56
EPS = 1e-6
assert (C * H * W) % 4 == 0, "Instance size (C*H*W) must be a multiple of 4"
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.block_size = 512
self.eps = EPS
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
void bhattacharyya_sum_cuda(
torch::Tensor x,
torch::Tensor y,
torch::Tensor out,
float eps,
int N,
int D);
"""
cuda_source = f"""
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE {self.block_size}
#define WARP_SIZE 32
#define ILP 4
__inline__ __device__ float warp_reduce_sum(float val) {{
#pragma unroll
for (int offset = 16; offset > 0; offset /= 2) {{
val += __shfl_down_sync(0xffffffff, val, offset);
}}
return val;
}}
__global__ __launch_bounds__(BLOCK_SIZE)
void bhattacharyya_split_kernel(
const float* __restrict__ x,
const float* __restrict__ y,
float* __restrict__ out,
float eps,
int D_vec_total // D / 4
) {{
const int n_idx = blockIdx.y; // Batch Index
const int split_idx = blockIdx.x; // Split Index
const int num_splits = gridDim.x;
const int chunk_size = (D_vec_total + num_splits - 1) / num_splits;
const int start_idx = split_idx * chunk_size;
const int end_idx = min(start_idx + chunk_size, D_vec_total);
if (start_idx >= D_vec_total) return;
const int64_t batch_offset = (int64_t)n_idx * D_vec_total * 4;
const float4* curr_x = reinterpret_cast<const float4*>(x + batch_offset) + start_idx + threadIdx.x;
const float4* curr_y = reinterpret_cast<const float4*>(y + batch_offset) + start_idx + threadIdx.x;
const float4* end_ptr = reinterpret_cast<const float4*>(x + batch_offset) + end_idx;
float sum[ILP];
#pragma unroll
for (int k=0; k<ILP; ++k) sum[k] = 0.0f;
const int stride = BLOCK_SIZE * ILP;
while (curr_x + (ILP - 1) * BLOCK_SIZE < end_ptr) {{
float4 r_x[ILP];
float4 r_y[ILP];
#pragma unroll
for (int k = 0; k < ILP; ++k) {{
r_x[k] = __ldg(curr_x + k * BLOCK_SIZE);
r_y[k] = __ldg(curr_y + k * BLOCK_SIZE);
}}
#pragma unroll
for (int k = 0; k < ILP; ++k) {{
// x
float p_x = r_x[k].x * r_y[k].x; sum[k] += sqrtf(p_x + eps);
// y
float p_y = r_x[k].y * r_y[k].y; sum[k] += sqrtf(p_y + eps);
// z
float p_z = r_x[k].z * r_y[k].z; sum[k] += sqrtf(p_z + eps);
// w
float p_w = r_x[k].w * r_y[k].w; sum[k] += sqrtf(p_w + eps);
}}
curr_x += stride;
curr_y += stride;
}}
while (curr_x < end_ptr) {{
float4 vx = __ldg(curr_x);
float4 vy = __ldg(curr_y);
sum[0] += sqrtf(vx.x * vy.x + eps);
sum[0] += sqrtf(vx.y * vy.y + eps);
sum[0] += sqrtf(vx.z * vy.z + eps);
sum[0] += sqrtf(vx.w * vy.w + eps);
curr_x += BLOCK_SIZE;
curr_y += BLOCK_SIZE;
}}
float local_sum = 0.0f;
#pragma unroll
for (int k=0; k<ILP; ++k) local_sum += sum[k];
float warp_sum = warp_reduce_sum(local_sum);
__shared__ float s_warp_sums[BLOCK_SIZE / WARP_SIZE];
const int lane_id = threadIdx.x % WARP_SIZE;
const int warp_id = threadIdx.x / WARP_SIZE;
if (lane_id == 0) {{
s_warp_sums[warp_id] = warp_sum;
}}
__syncthreads();
if (warp_id == 0) {{
float block_val = 0.0f;
if (lane_id < (BLOCK_SIZE / WARP_SIZE)) {{
block_val = s_warp_sums[lane_id];
}}
block_val = warp_reduce_sum(block_val);
if (lane_id == 0) {{
atomicAdd(&out[n_idx], block_val);
}}
}}
}}
void bhattacharyya_sum_cuda(
torch::Tensor x,
torch::Tensor y,
torch::Tensor out,
float eps,
int N,
int D)
{{
int D_vec = D / 4;
int device_id;
cudaGetDevice(&device_id);
int sm_count;
cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, device_id);
int target_blocks = sm_count * 4;
int splits = (target_blocks + N - 1) / N;
int max_splits = (D_vec + 1024 - 1) / 1024;
if (splits > max_splits) splits = max_splits;
if (splits < 1) splits = 1;
if (splits > 512) splits = 512;
dim3 blocks(splits, N);
dim3 threads(BLOCK_SIZE);
bhattacharyya_split_kernel<<<blocks, threads>>>(
x.data_ptr<float>(),
y.data_ptr<float>(),
out.data_ptr<float>(),
eps,
D_vec
);
}}
"""
self.op = load_inline(
name='bhattacharyya_cuda_opt_v1',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['bhattacharyya_sum_cuda'],
extra_cuda_cflags=[
'-O3',
'--use_fast_math',
'-Xptxas=-v'
],
verbose=False
)
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
if not x.is_contiguous(): x = x.contiguous()
if not y.is_contiguous(): y = y.contiguous()
N, C, H, W = x.size()
D = C * H * W
out = torch.zeros(N, device=x.device, dtype=torch.float32)
self.op.bhattacharyya_sum_cuda(
x,
y,
out,
self.eps,
N,
D
)
return -torch.log(out + self.eps)

View File

@ -0,0 +1,45 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
N, C, H, W = 32, 64, 56, 56
EPS = 1e-6
class BhattacharyyaDistance(nn.Module):
def __init__(self, eps=1e-6):
super().__init__()
self.eps = eps
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
x = torch.relu(x)
y = torch.relu(y)
product = x * y
sqrt_prod = torch.sqrt(product + self.eps)
bc = torch.sum(sqrt_prod, dim=[1, 2, 3])
distance = -torch.log(bc + self.eps)
return distance
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = BhattacharyyaDistance(EPS)
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return self.op(x, y)
def get_inputs():
x = torch.rand(N, C, H, W, dtype=torch.float32)
y = torch.rand(N, C, H, W, dtype=torch.float32)
return [x, y]
def get_init_inputs():
return []

84
S1/uucoco_#5/prompt.txt Normal file
View File

@ -0,0 +1,84 @@
You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm 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 normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
Technologies Used :
PyTorch: Deep learning framework.
CUDA: GPU acceleration for parallel computing.
C++/CUDA C++: High-performance kernel programming.
Inline C++/CUDA Extension (torch.utils.cpp_extension.load_inline): Just-In-Time (JIT) compilation of custom operators.
Bhattacharyya Distance: Statistical measure for similarity between probability distributions.
Vectorized Memory Access (float4): Uses 128-bit wide loads (4 floats) to improve memory bandwidth utilization.
Instruction-Level Parallelism (ILP): Processes multiple float4 elements per loop iteration to hide instruction latency.
Warp-Level Primitives: Uses __shfl_down_sync for efficient intra-warp reduction.
Two-Stage Parallel Reduction: Combines warp-level reduction with shared memory and block-level reduction.
Grid-Stride Loops with Boundary Checks: Handles data of arbitrary size safely.
Constant Memory/__ldg: Uses read-only data cache for improved memory access patterns.
Atomic Operations (atomicAdd): Safely accumulates results from multiple thread blocks.
Multi-Kernel Launch Configuration: Dynamically calculates grid dimensions based on GPU SM count and data size.
Fast Math Operations: Uses sqrtf with --use_fast_math compiler flag.
Memory Coalescing: Optimized memory access patterns through contiguous tensor layout.
Tensor Contiguity Enforcement: Ensures optimal memory layout in PyTorch wrapper.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn
import torch.nn.functional as F
N, C, H, W = 32, 64, 56, 56
EPS = 1e-6
class BhattacharyyaDistance(nn.Module):
def __init__(self, eps=1e-6):
super().__init__()
self.eps = eps
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
x = torch.relu(x)
y = torch.relu(y)
product = x * y
sqrt_prod = torch.sqrt(product + self.eps)
bc = torch.sum(sqrt_prod, dim=[1, 2, 3])
distance = -torch.log(bc + self.eps)
return distance
class Model(nn.Module):
def __init__(self):
super().__init__()
self.op = BhattacharyyaDistance(EPS)
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return self.op(x, y)
def get_inputs():
x = torch.rand(N, C, H, W, dtype=torch.float32)
y = torch.rand(N, C, H, W, dtype=torch.float32)
return [x, y]
def get_init_inputs():
return []

78
S1/uucoco_#5/run_code.py Normal file
View File

@ -0,0 +1,78 @@
import torch
import time
from BhattacharyyaDistance_torch import Model, get_inputs, get_init_inputs
from BhattacharyyaDistance_cuda import ModelNew
def run_benchmark():
if not torch.cuda.is_available():
print("CUDA 不可用")
return
device = torch.device("cuda")
# 准备输入数据
inputs = [x.cuda(device=device) for x in get_inputs()]
init_inputs = [x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in get_init_inputs()]
# 初始化模型
torch_model = Model(*init_inputs).cuda()
cuda_model = ModelNew(*init_inputs).cuda()
torch_model.eval()
cuda_model.eval()
print("-------------------- 精度对齐验证 --------------------")
with torch.no_grad():
# 预热GPU
_ = torch_model(*inputs)
_ = cuda_model(*inputs)
# 正式测试
output_torch = torch_model(*inputs)
output_cuda = cuda_model(*inputs)
# 精度验证
abs_diff = torch.abs(output_torch - output_cuda)
max_diff = torch.max(abs_diff).item()
mean_diff = torch.mean(abs_diff).item()
if max_diff < 1e-4 and mean_diff < 1e-5:
print(f"✅ 精度对齐:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
precision_flag = True
else:
print(f"❌ 精度不一致:最大误差 {max_diff:.6f},平均误差 {mean_diff:.6f}")
precision_flag = False
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 100
# 预热GPU
for _ in range(10):
_ = 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内置Swish平均执行时间: {torch_time:.6f}")
print(f"自定义CUDA Swish平均执行时间: {cuda_time:.6f}")
speedup = torch_time / cuda_time if cuda_time > 0 else 0
print(f"加速比 (Speedup): {speedup:.2f}x")
return precision_flag, speedup
if __name__ == "__main__":
precision_flag, speedup = run_benchmark()