forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish TanimotoCoefficient# 33' (#60) from uucoco/GPUCodeForces:TanimotoCoefficient into main
This commit is contained in:
commit
0e824f277b
|
|
@ -0,0 +1,215 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
import os
|
||||
|
||||
# 定义维度常量
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-6
|
||||
INSTANCE_SIZE = C * H * W # 200704
|
||||
|
||||
# 确保 C*H*W 是 4 的倍数以便向量化
|
||||
assert (INSTANCE_SIZE) % 4 == 0, "Instance size (C*H*W) must be a multiple of 4"
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
"""
|
||||
Tanimoto 系数的 CUDA 优化实现。
|
||||
|
||||
优化点:
|
||||
1. 融合: 将 3 次归约 (dot, x_sq, y_sq) 和 1 次除法融合到一个 CUDA kernel。
|
||||
2. 向量化: 使用 float4 进行 128 位内存访问。
|
||||
3. 共享内存: 用于高效的块内归约。
|
||||
4. 精度匹配: 使用 'volatile' 禁用 FMA,以 100% 匹配 PyTorch 的分步舍入。
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.eps = EPS
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
# 1. C++ 接口定义
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
torch::Tensor tanimoto_forward_cuda(
|
||||
torch::Tensor x,
|
||||
torch::Tensor y,
|
||||
float eps,
|
||||
int N,
|
||||
int D);
|
||||
"""
|
||||
|
||||
# 2. CUDA 内核实现
|
||||
cuda_source = f"""
|
||||
#include <cuda_runtime.h>
|
||||
#include <device_launch_parameters.h>
|
||||
#include <cmath>
|
||||
|
||||
// ============================================================
|
||||
// Tanimoto 融合内核
|
||||
// ============================================================
|
||||
__global__ void tanimoto_fused_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ y,
|
||||
float* __restrict__ output,
|
||||
float eps,
|
||||
int N, // 批次大小
|
||||
int D // 实例大小 (C*H*W)
|
||||
) {{
|
||||
// 每个块处理一个实例 (n_idx)
|
||||
const int n_idx = blockIdx.x;
|
||||
if (n_idx >= N) return;
|
||||
|
||||
const int t_idx = threadIdx.x;
|
||||
const int block_size = blockDim.x; // e.g., 256
|
||||
|
||||
// 指向此实例数据的开头
|
||||
const int instance_offset = n_idx * D;
|
||||
const float4* x4_ptr = reinterpret_cast<const float4*>(x + instance_offset);
|
||||
const float4* y4_ptr = reinterpret_cast<const float4*>(y + instance_offset);
|
||||
|
||||
const int D_vec = D / 4; // 向量化维度
|
||||
|
||||
// 线程本地累加器
|
||||
float thread_dot = 0.0f;
|
||||
float thread_x_sq = 0.0f;
|
||||
float thread_y_sq = 0.0f;
|
||||
|
||||
// --- 1. 线程本地向量化累加 ---
|
||||
for (int i = t_idx; i < D_vec; i += block_size) {{
|
||||
float4 x_val = x4_ptr[i];
|
||||
float4 y_val = y4_ptr[i];
|
||||
|
||||
// --- 精度修复: 禁用 FMA ---
|
||||
// (x * y)
|
||||
volatile float m_dot_x = x_val.x * y_val.x;
|
||||
volatile float m_dot_y = x_val.y * y_val.y;
|
||||
volatile float m_dot_z = x_val.z * y_val.z;
|
||||
volatile float m_dot_w = x_val.w * y_val.w;
|
||||
|
||||
// (x * x)
|
||||
volatile float m_x_sq_x = x_val.x * x_val.x;
|
||||
volatile float m_x_sq_y = x_val.y * x_val.y;
|
||||
volatile float m_x_sq_z = x_val.z * x_val.z;
|
||||
volatile float m_x_sq_w = x_val.w * x_val.w;
|
||||
|
||||
// (y * y)
|
||||
volatile float m_y_sq_x = y_val.x * y_val.x;
|
||||
volatile float m_y_sq_y = y_val.y * y_val.y;
|
||||
volatile float m_y_sq_z = y_val.z * y_val.z;
|
||||
volatile float m_y_sq_w = y_val.w * y_val.w;
|
||||
|
||||
thread_dot += m_dot_x + m_dot_y + m_dot_z + m_dot_w;
|
||||
thread_x_sq += m_x_sq_x + m_x_sq_y + m_x_sq_z + m_x_sq_w;
|
||||
thread_y_sq += m_y_sq_x + m_y_sq_y + m_y_sq_z + m_y_sq_w;
|
||||
}}
|
||||
|
||||
// --- 2. 块内共享内存归约 ---
|
||||
// (BLOCK_SIZE 必须是 2 的幂, e.g., 256)
|
||||
extern __shared__ float s_data[];
|
||||
float* s_dot = s_data;
|
||||
float* s_x_sq = &s_data[block_size];
|
||||
float* s_y_sq = &s_data[block_size * 2];
|
||||
|
||||
s_dot[t_idx] = thread_dot;
|
||||
s_x_sq[t_idx] = thread_x_sq;
|
||||
s_y_sq[t_idx] = thread_y_sq;
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// (使用标准树形归约)
|
||||
for (int s = block_size / 2; s > 0; s >>= 1) {{
|
||||
if (t_idx < s) {{
|
||||
s_dot[t_idx] += s_dot[t_idx + s];
|
||||
s_x_sq[t_idx] += s_x_sq[t_idx + s];
|
||||
s_y_sq[t_idx] += s_y_sq[t_idx + s];
|
||||
}}
|
||||
__syncthreads();
|
||||
}}
|
||||
|
||||
// --- 3. 线程 0 计算最终结果 ---
|
||||
if (t_idx == 0) {{
|
||||
float total_dot = s_dot[0];
|
||||
float total_x_sq = s_x_sq[0];
|
||||
float total_y_sq = s_y_sq[0];
|
||||
|
||||
float denominator = total_x_sq + total_y_sq - total_dot + eps;
|
||||
|
||||
output[n_idx] = (total_dot + eps) / denominator;
|
||||
}}
|
||||
}}
|
||||
|
||||
// ============================================================
|
||||
// C++ Wrapper
|
||||
// ============================================================
|
||||
torch::Tensor tanimoto_forward_cuda(
|
||||
torch::Tensor x,
|
||||
torch::Tensor y,
|
||||
float eps,
|
||||
int N,
|
||||
int D // 实例大小 (C*H*W)
|
||||
) {{
|
||||
// 确保输入连续
|
||||
x = x.contiguous();
|
||||
y = y.contiguous();
|
||||
|
||||
// 输出张量形状为 [N]
|
||||
auto output = torch::empty({{N}}, x.options());
|
||||
|
||||
const int BLOCK_SIZE = 256;
|
||||
dim3 threads(BLOCK_SIZE);
|
||||
dim3 blocks(N);
|
||||
|
||||
// 动态分配共享内存 (每个累加器 256 * 4 字节)
|
||||
// (dot_sum, x_sq_sum, y_sq_sum)
|
||||
int shared_mem_size = 3 * BLOCK_SIZE * sizeof(float);
|
||||
|
||||
tanimoto_fused_kernel<<<blocks, threads, shared_mem_size>>>(
|
||||
x.data_ptr<float>(),
|
||||
y.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
eps,
|
||||
N,
|
||||
D
|
||||
);
|
||||
|
||||
return output;
|
||||
}}
|
||||
"""
|
||||
|
||||
# 3. 编译 CUDA 模块
|
||||
self.tanimoto_op = load_inline(
|
||||
name="tanimoto_cuda_v1_fma_fixed",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["tanimoto_forward_cuda"],
|
||||
# (使用高精度标志, 禁用 fast_math 以确保 volatile 生效)
|
||||
extra_cuda_cflags=[
|
||||
"-O3",
|
||||
"-ftz=false",
|
||||
"-prec-div=true",
|
||||
"-prec-sqrt=true",
|
||||
"-std=c++17"
|
||||
],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
if x.dtype != torch.float32 or not x.is_cuda:
|
||||
x = x.to("cuda", dtype=torch.float32)
|
||||
if y.dtype != torch.float32 or not y.is_cuda:
|
||||
y = y.to("cuda", dtype=torch.float32)
|
||||
|
||||
N, C, H, W = x.size()
|
||||
D = C * H * W # 实例大小
|
||||
|
||||
return self.tanimoto_op.tanimoto_forward_cuda(
|
||||
x.contiguous(),
|
||||
y.contiguous(),
|
||||
self.eps,
|
||||
N,
|
||||
D
|
||||
)
|
||||
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
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 Tanimoto(nn.Module):
|
||||
|
||||
|
||||
def __init__(self, eps=1e-6):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
# 我们将在 C, H, W 维度上进行归约
|
||||
self.reduction_dims = (1, 2, 3)
|
||||
|
||||
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
x_dot_y = torch.sum(x * y, dim=self.reduction_dims)
|
||||
|
||||
|
||||
x_norm_sq = torch.sum(x * x, dim=self.reduction_dims)
|
||||
y_norm_sq = torch.sum(y * y, dim=self.reduction_dims)
|
||||
|
||||
|
||||
denominator = x_norm_sq + y_norm_sq - x_dot_y
|
||||
|
||||
|
||||
similarity = (x_dot_y + self.eps) / (denominator + self.eps)
|
||||
|
||||
return similarity
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.op = Tanimoto(EPS)
|
||||
|
||||
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(x, y)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
y = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x, y]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
|
||||
return []
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
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
|
||||
|
||||
Tanimoto Coefficient (Jaccard Index): Similarity measure between sets or vectors
|
||||
|
||||
Fused Kernel Design: Combines dot product, squared sums, and division in single kernel
|
||||
|
||||
Vectorized Memory Access (float4): Uses 128-bit wide loads (4 floats) for improved memory bandwidth
|
||||
|
||||
One Block Per Sample: Each CUDA block processes one complete instance (N blocks for N samples)
|
||||
|
||||
Shared Memory Reduction: Uses __shared__ arrays for efficient block-level parallel reduction
|
||||
|
||||
Tree Reduction Pattern: Binary tree reduction within thread blocks using __syncthreads()
|
||||
|
||||
Precision Control: Uses volatile keyword to disable FMA (Fused Multiply-Add) for exact numerical matching
|
||||
|
||||
Compiler Precision Flags: Uses -ftz=false, -prec-div=true, -prec-sqrt=true for high precision
|
||||
|
||||
Dynamic Shared Memory Allocation: Allocates shared memory for three reduction buffers at kernel launch
|
||||
|
||||
Strided Memory Access: Threads process elements with stride equal to block size for coalesced access
|
||||
|
||||
Numerical Stability: Adds epsilon (eps) to prevent division by zero
|
||||
|
||||
Memory Coalescing: Ensures contiguous tensor layout for optimal memory access patterns
|
||||
|
||||
Automatic Type Conversion: Converts inputs to float32 and CUDA device if needed
|
||||
|
||||
Boundary Checking: Validates block indices to prevent out-of-bounds access
|
||||
|
||||
Three-Accumulator Design: Maintains separate accumulators for dot product, x squared, and y squared
|
||||
|
||||
Exact Numerical Matching: Designed to 100% match PyTorch's step-by-step floating point rounding
|
||||
|
||||
Optimized Memory Layout: Uses vectorized pointer arithmetic with float4 type casting
|
||||
|
||||
Efficient Resource Utilization: Maximizes memory bandwidth while maintaining numerical precision
|
||||
|
||||
|
||||
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 Tanimoto(nn.Module):
|
||||
|
||||
|
||||
def __init__(self, eps=1e-6):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
# 我们将在 C, H, W 维度上进行归约
|
||||
self.reduction_dims = (1, 2, 3)
|
||||
|
||||
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
x_dot_y = torch.sum(x * y, dim=self.reduction_dims)
|
||||
|
||||
|
||||
x_norm_sq = torch.sum(x * x, dim=self.reduction_dims)
|
||||
y_norm_sq = torch.sum(y * y, dim=self.reduction_dims)
|
||||
|
||||
|
||||
denominator = x_norm_sq + y_norm_sq - x_dot_y
|
||||
|
||||
|
||||
similarity = (x_dot_y + self.eps) / (denominator + self.eps)
|
||||
|
||||
return similarity
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.op = Tanimoto(EPS)
|
||||
|
||||
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(x, y)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
y = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x, y]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
|
||||
return []
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from TanimotoCoefficient_torch import Model, get_inputs, get_init_inputs
|
||||
from TanimotoCoefficient_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