feat:add high performance focallossfuse #31

This commit is contained in:
wut0n 2025-12-04 14:59:40 +08:00
parent f989885dde
commit 2e2b036748
4 changed files with 415 additions and 0 deletions

View File

@ -0,0 +1,158 @@
import torch
from torch.utils.cpp_extension import load_inline
import os
# CUDA C++ 源代码字符串
focal_loss_cpp_source = """
torch::Tensor focal_loss_forward_backward_cuda(
torch::Tensor logits,
torch::Tensor targets,
float alpha,
float gamma
);
"""
# CUDA 源代码字符串
focal_loss_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cmath>
__global__ void focal_loss_forward_backward_kernel(
const float* logits,
const float* targets,
float* loss, // 输出损失值
float* d_logits, // 输出梯度
int batch_size,
float alpha,
float gamma
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < batch_size) {
float logit = logits[idx];
float target = targets[idx];
// --- 1. 前向计算部分 ---
float prob; // p
if (logit > 0) {
prob = 1.0f / (1.0f + expf(-logit));
} else {
float exp_logit = expf(logit);
prob = exp_logit / (1.0f + exp_logit);
}
prob = fmaxf(fminf(prob, 1.0f - 1e-7f), 1e-7f);
float pt = (target > 0.5f) ? prob : (1.0f - prob);
float bce = -(target * logf(prob) + (1.0f - target) * logf(1.0f - prob));
float focal_weight = alpha * powf(1.0f - pt, gamma);
loss[idx] = focal_weight * bce;
// --- 2. 反向梯度计算部分 ---
// dL/dlogit = alpha * gamma * (1-pt)^(gamma-1) * (1-p) * p * log(pt) - alpha * (1-pt)^gamma * (p - target)
float one_minus_pt = 1.0f - pt;
float one_minus_pt_pow_gamma_minus_1 = powf(one_minus_pt, gamma - 1.0f);
float term1 = alpha * gamma * one_minus_pt_pow_gamma_minus_1 * (1.0f - prob) * prob * logf(pt);
float term2 = focal_weight * (prob - target);
d_logits[idx] = term1 - term2;
}
}
// C++ 封装函数
torch::Tensor focal_loss_forward_backward_cuda(
torch::Tensor logits,
torch::Tensor targets,
float alpha,
float gamma
) {
logits = logits.contiguous().to(torch::kFloat32);
targets = targets.contiguous().to(torch::kFloat32);
auto batch_size = logits.numel();
// 创建一个输出张量前半部分存loss后半部分存梯度
auto output = torch::empty({2 * batch_size}, logits.options());
float* loss_ptr = output.data_ptr<float>();
float* d_logits_ptr = loss_ptr + batch_size;
const int block_size = 256;
int num_blocks = (batch_size + block_size - 1) / block_size;
focal_loss_forward_backward_kernel<<<num_blocks, block_size>>>(
logits.data_ptr<float>(),
targets.data_ptr<float>(),
loss_ptr,
d_logits_ptr,
batch_size,
alpha,
gamma
);
return output; // 返回包含loss和grads的组合张量
}
"""
# 编译CUDA代码
build_dir = './cuda_build_fused'
os.makedirs(build_dir, exist_ok=True)
focal_loss_module = load_inline(
name="focal_loss_fused",
cpp_sources=focal_loss_cpp_source,
cuda_sources=focal_loss_source,
functions=["focal_loss_forward_backward_cuda"],
verbose=True,
build_directory=build_dir,
extra_cuda_cflags=["-O3"]
)
class FocalLossFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, logits, targets, alpha, gamma):
# 调用融合内核
output = focal_loss_module.focal_loss_forward_backward_cuda(logits, targets, alpha, gamma)
batch_size = logits.numel()
loss = output.narrow(0, 0, batch_size)
d_logits = output.narrow(0, batch_size, batch_size)
# 为反向传播保存梯度和超参数
ctx.save_for_backward(d_logits)
ctx.alpha = alpha
ctx.gamma = gamma
return loss
@staticmethod
def backward(ctx, grad_output):
# 从上下文中恢复梯度
d_logits, = ctx.saved_tensors
# grad_output是上游传来的梯度需要相乘
return d_logits * grad_output, None, None, None
class ModelNew(torch.nn.Module):
def __init__(self, alpha=0.25, gamma=2.0, reduction='mean'):
super(ModelNew, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
self.focal_loss_fn = FocalLossFunction.apply
def forward(self, logits, targets):
logits = logits.to(torch.float32)
targets = targets.to(torch.float32)
if logits.dim() == 2 and logits.size(1) == 1:
logits = logits.squeeze(1)
# 调用自定义的autograd函数
loss = self.focal_loss_fn(logits, targets, self.alpha, self.gamma)
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else:
return loss

View File

@ -0,0 +1,69 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
"""
Focal Loss implementation for binary classification.
Focal Loss = -α * (1-pt)^γ * log(pt)
where pt = p if target=1, else (1-p)
"""
def __init__(self, alpha=0.25, gamma=2.0, reduction='mean'):
super(Model, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""
Compute Focal Loss between inputs and targets.
Args:
inputs (torch.Tensor): Predicted logits of shape (batch_size, num_classes)
targets (torch.Tensor): Ground truth labels of shape (batch_size,)
Returns:
torch.Tensor: Computed focal loss
"""
# 确保输入输出类型完全一致
inputs = inputs.to(torch.float32)
targets = targets.to(torch.float32)
# 确保targets的形状与inputs匹配
if inputs.dim() == 2 and inputs.size(1) == 1:
targets = targets.unsqueeze(1) # 将targets从[batch_size]变为[batch_size, 1]
# Convert logits to probabilities
probs = torch.sigmoid(inputs)
# Compute pt
pt = torch.where(targets == 1, probs, 1 - probs)
# Compute focal weight
focal_weight = self.alpha * torch.pow(1 - pt, self.gamma)
# Compute binary cross entropy
bce = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none')
# Apply focal weight
focal_loss = focal_weight * bce
if self.reduction == 'mean':
return focal_loss.mean()
elif self.reduction == 'sum':
return focal_loss.sum()
else:
return focal_loss
batch_size = 1024 # 增大批次以更好地观察性能差异
num_classes = 1 # Binary classification
def get_inputs():
# Generate random logits - 明确指定float32
inputs = torch.randn(batch_size, num_classes, dtype=torch.float32)
# Generate random binary targets (0 or 1) - 明确指定float32
targets = torch.randint(0, 2, (batch_size,), dtype=torch.float32)
return [inputs, targets]
def get_init_inputs():
return [] # No special initialization inputs needed

102
S1/wut0n_#31/prompt.txt Normal file
View File

@ -0,0 +1,102 @@
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.
Heres 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
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, a, b):
return a + b
def get_inputs():
a = torch.randn(1, 128).cuda()
b = torch.randn(1, 128).cuda()
return [a, b]
def get_init_inputs():
return []
The example new arch with custom CUDA kernels looks like this:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, a, b):
return a + b
def get_inputs():
a = torch.randn(1, 128).cuda()
b = torch.randn(1, 128).cuda()
return [a, b]
def get_init_inputs():
return []
You are given the following architecture:
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Baseline Focal Loss implementation using fundamental PyTorch ops.
This version avoids any built-in fused functions like `binary_cross_entropy_with_logits`
to provide a fair comparison against a custom fused kernel.
"""
def __init__(self, alpha=0.25, gamma=2.0, reduction='mean'):
super(Model, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
# 1. Manually implement Sigmoid
probs = torch.sigmoid(inputs)
# 2. Manually implement Binary Cross Entropy
eps = 1e-7
bce = -(targets * torch.log(probs + eps) + (1 - targets) * torch.log(1 - probs + eps))
# 3. Compute pt
pt = torch.where(targets == 1, probs, 1 - probs)
# 4. Compute Focal Weight
focal_weight = self.alpha * torch.pow(1 - pt, self.gamma)
# 5. Apply Focal Weight
focal_loss = focal_weight * bce
if self.reduction == 'mean':
return focal_loss.mean()
elif self.reduction == 'sum':
return focal_loss.sum()
else:
return focal_loss
batch_size = 1024
num_classes = 1
def get_inputs():
inputs = torch.randn(batch_size, num_classes, dtype=torch.float32)
targets = torch.randint(0, 2, (batch_size,), dtype=torch.float32)
return [inputs, targets]
def get_init_inputs():
return []
IMPORTANT: The baseline architecture is a step-by-step implementation of Focal Loss, involving multiple separate operations (sigmoid, log, pow, etc.). This creates several intermediate tensors (probs, bce, pt, focal_weight) and requires multiple kernel launches during the forward pass. Furthermore, during backpropagation, PyTorchs autograd engine will launch separate kernels for each operations gradient calculation. The primary optimization goal is operator fusion across the forward and backward passes: combine the entire forward computation and the entire backward gradient computation into a single, highly efficient CUDA kernel. This fusion should eliminate all intermediate tensors, drastically reduce memory traffic, and minimize kernel launch overhead. Focus on creating a novel torch.autograd.Function that encapsulates this fused logic, providing a seamless drop-in replacement that significantly accelerates the training process.

86
S1/wut0n_#31/run_code.py Normal file
View File

@ -0,0 +1,86 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
# --- 修改点 1: 更新 import 语句,指向我们新的文件 ---
from focalloss_fused_torchcode import Model, get_inputs, get_init_inputs
from focalloss_fused_cudacode 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, atol=1e-05)
max_diff = torch.max(torch.abs(output_torch - output_cuda)).item()
mean_diff = torch.mean(torch.abs(output_torch - output_cuda)).item()
if precision_flag:
print(f"✅ 精度对齐:两个模型的输出结果非常接近。")
print(f"最大误差: {max_diff:.8f}, 平均误差: {mean_diff:.8f}")
else:
print(f"❌ 精度不一致!最大误差: {max_diff:.8f}, 平均误差: {mean_diff:.8f}")
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 基准 Focal Loss 平均执行时间: {torch_time:.6f}")
print(f"自定义 Fused Focal Loss 平均执行时间: {cuda_time:.6f}")
speedup = 0
if cuda_time > 0:
speedup = torch_time / cuda_time
print(f"加速比: {speedup:.2f}x")
else:
print("CUDA 内核执行时间为0无法计算加速比。")
return precision_flag, speedup
if __name__ == "__main__":
precision_flag, speedup = run_benchmark()