finish SoftBootstrappingLoss #41 #369

Closed
hli28146 wants to merge 1 commits from hli28146/GPUCodeForces:h41 into main
4 changed files with 414 additions and 0 deletions

View File

@ -0,0 +1,84 @@
Write a custom CUDA kernel to optimize `Soft Bootstrapping Loss`.
Formula: Loss = beta * CrossEntropy(p, target) + (1 - beta) * Entropy(p)
Where p = softmax(logits).
Entropy(p) = -sum(p * log(p)).
Problem Analysis:
1. Redundant Memory Access: Standard implementation calculates Softmax first, producing an (N, C) probability tensor. Then it computes CrossEntropy and Entropy separately. Calculating Entropy explicitly requires reading the probability tensor, computing log, multiplying, and summing, which is highly bandwidth-intensive.
2. Numerical Optimization: The entropy term H(p) can be simplified analytically using logits to avoid explicit probability materialization and improve stability:
H(p) = log(SumExp) - (1/SumExp) * sum(exp(x_i - max) * (x_i - max))
Optimization Strategy: Fused Row-wise Kernel with Mathematical Simplification
1. One-Block-per-Row: Each block handles one sample (row). Data is loaded into Shared Memory once to support multiple reduction passes.
2. Shared Memory Caching: Use float4 vectorized loads to move logits from global memory to shared memory efficiently.
3. Multi-Pass Reduction in Shared Memory:
- Pass 1: Find Max logit (M) for stability.
- Pass 2: Calculate SumExp (S = sum(exp(x - M))).
- Pass 3: Calculate Weighted Sum (W = sum(exp(x - M) * (x - M))) for the entropy term.
- All reductions use optimized warp/block reduction primitives.
4. Fused Calculation:
- CrossEntropy = log(S) - (target_logit - M)
- Entropy = log(S) - W / S
- Combine terms using beta and write the single scalar loss per row.
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_SIZE = 2048
NUM_CLASSES = 4096
SHAPE = (BATCH_SIZE, NUM_CLASSES)
BETA = 0.95
REDUCTION = 'none'
class SoftBootstrappingLoss(nn.Module):
"""
Soft Bootstrapping Loss
L = beta * CE(p, y) + (1-beta) * H(p)
"""
def __init__(self, beta=0.95, reduction='mean'):
super(SoftBootstrappingLoss, self).__init__()
self.beta = beta
self.reduction = reduction
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
# logits: (N, C)
# targets: (N)
probs = F.softmax(logits, dim=-1)
ce_loss = F.cross_entropy(logits, targets, reduction='none')
entropy = -torch.sum(probs * torch.log(probs + 1e-8), dim=1)
loss = self.beta * ce_loss + (1.0 - self.beta) * entropy
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
return loss
class Model(nn.Module):
def __init__(self, beta=0.95, reduction='none'):
super(Model, self).__init__()
self.loss_fn = SoftBootstrappingLoss(beta=beta, reduction=reduction)
def forward(self, logits, targets):
return self.loss_fn(logits, targets)
def get_inputs():
logits = torch.randn(SHAPE, dtype=torch.float32)
targets = torch.randint(0, NUM_CLASSES, (BATCH_SIZE,), dtype=torch.long)
return [logits.contiguous(), targets.contiguous()]
def get_init_inputs():
return [BETA, REDUCTION]

View File

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

View File

@ -0,0 +1,203 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cpp_source = """
#include <torch/extension.h>
#include <string>
torch::Tensor soft_bootstrap_loss_cuda_forward(
const torch::Tensor& logits,
const torch::Tensor& targets,
float beta,
std::string reduction);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
#include <cfloat>
#define BLOCK_SIZE 256
#define WARP_SIZE 32
struct __align__(16) Float4 {
float x, y, z, w;
};
template<typename T>
__device__ __forceinline__ T warp_reduce_max(T val) {
#pragma unroll
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
val = max(val, __shfl_down_sync(0xffffffff, val, offset));
}
return val;
}
template<typename T>
__device__ __forceinline__ T warp_reduce_sum(T val) {
#pragma unroll
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
val += __shfl_down_sync(0xffffffff, val, offset);
}
return val;
}
__device__ __forceinline__ float block_reduce_max(float val) {
static __shared__ float shared[32];
int lane = threadIdx.x % WARP_SIZE;
int wid = threadIdx.x / WARP_SIZE;
val = warp_reduce_max(val);
if (lane == 0) shared[wid] = val;
__syncthreads();
val = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared[lane] : -FLT_MAX;
if (wid == 0) val = warp_reduce_max(val);
return val;
}
__device__ __forceinline__ float block_reduce_sum(float val) {
static __shared__ float shared[32];
int lane = threadIdx.x % WARP_SIZE;
int wid = threadIdx.x / WARP_SIZE;
val = warp_reduce_sum(val);
if (lane == 0) shared[wid] = val;
__syncthreads();
val = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared[lane] : 0.0f;
if (wid == 0) val = warp_reduce_sum(val);
return val;
}
// Loss = beta * CE + (1-beta) * Entropy
// CE = log(S) - (target - M)
// Entropy = log(S) - (1/S) * Sum( exp(x-M) * (x-M) )
__global__ void soft_bootstrap_kernel(
float* __restrict__ output,
const float* __restrict__ logits,
const int64_t* __restrict__ targets,
int cols,
float beta)
{
// Shared Memory to cache the row
extern __shared__ float s_row[];
int row_idx = blockIdx.x;
int tid = threadIdx.x;
const float* row_logits = logits + row_idx * cols;
// 1. Load Data: Global -> Shared (Vectorized)
int i = tid * 4;
while (i < cols) {
if (i + 4 <= cols) {
*(Float4*)&s_row[i] = *(reinterpret_cast<const Float4*>(&row_logits[i]));
} else {
for (int k = 0; k < 4 && i + k < cols; ++k) {
s_row[i + k] = row_logits[i + k];
}
}
i += blockDim.x * 4;
}
__syncthreads();
// 2. Find Max (M)
float local_max = -FLT_MAX;
for (int k = tid; k < cols; k += blockDim.x) {
local_max = fmaxf(local_max, s_row[k]);
}
float M = block_reduce_max(local_max);
// Broadcast M
__shared__ float s_M;
if (tid == 0) s_M = M;
__syncthreads();
M = s_M;
// 3. Compute SumExp (S) and WeightedSum (W)
// S = sum(exp(z))
// W = sum(exp(z) * z), where z = x - M
float local_S = 0.0f;
float local_W = 0.0f;
for (int k = tid; k < cols; k += blockDim.x) {
float z = s_row[k] - M;
float e_z = __expf(z);
local_S += e_z;
local_W += e_z * z;
}
float S = block_reduce_sum(local_S);
float W = block_reduce_sum(local_W);
// 4. Final Calculation
if (tid == 0) {
int64_t target_idx = targets[row_idx];
float target_val = s_row[target_idx]; // Read from shared memory
float log_S = __logf(S);
// Cross Entropy = -log(pt) = -( (target-M) - log(S) ) = log(S) - target + M
float ce_loss = log_S - target_val + M;
// Entropy = log(S) - W / S
float entropy = log_S - W / S;
output[row_idx] = beta * ce_loss + (1.0f - beta) * entropy;
}
}
torch::Tensor soft_bootstrap_loss_cuda_forward(
const torch::Tensor& logits,
const torch::Tensor& targets,
float beta,
std::string reduction)
{
TORCH_CHECK(logits.is_cuda() && targets.is_cuda(), "Inputs must be CUDA");
TORCH_CHECK(logits.is_contiguous() && targets.is_contiguous(), "Inputs must be contiguous");
int batch_size = logits.size(0);
int num_classes = logits.size(1);
auto output = torch::empty({batch_size}, logits.options());
size_t smem_size = num_classes * sizeof(float);
soft_bootstrap_kernel<<<batch_size, BLOCK_SIZE, smem_size>>>(
output.data_ptr<float>(),
logits.data_ptr<float>(),
targets.data_ptr<int64_t>(),
num_classes,
beta
);
if (reduction == "mean") {
return output.mean();
} else if (reduction == "sum") {
return output.sum();
}
return output;
}
"""
class ModelNew(nn.Module):
def __init__(self, beta=0.95, reduction='none'):
super(ModelNew, self).__init__()
self.beta = beta
self.reduction = reduction
self.op = load_inline(
name='soft_bootstrapping_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['soft_bootstrap_loss_cuda_forward'],
verbose=False,
extra_cuda_cflags=['-O3']
)
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
return self.op.soft_bootstrap_loss_cuda_forward(
logits.contiguous(),
targets.contiguous(),
self.beta,
self.reduction
)

View File

@ -0,0 +1,53 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 2048
NUM_CLASSES = 4096
SHAPE = (BATCH_SIZE, NUM_CLASSES)
BETA = 0.95
REDUCTION = 'none'
class SoftBootstrappingLoss(nn.Module):
"""
Soft Bootstrapping Loss
L = beta * CE(p, y) + (1-beta) * H(p)
"""
def __init__(self, beta=0.95, reduction='mean'):
super(SoftBootstrappingLoss, self).__init__()
self.beta = beta
self.reduction = reduction
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
# logits: (N, C)
# targets: (N)
probs = F.softmax(logits, dim=-1)
ce_loss = F.cross_entropy(logits, targets, reduction='none')
entropy = -torch.sum(probs * torch.log(probs + 1e-8), dim=1)
loss = self.beta * ce_loss + (1.0 - self.beta) * entropy
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
return loss
class Model(nn.Module):
def __init__(self, beta=0.95, reduction='none'):
super(Model, self).__init__()
self.loss_fn = SoftBootstrappingLoss(beta=beta, reduction=reduction)
def forward(self, logits, targets):
return self.loss_fn(logits, targets)
def get_inputs():
logits = torch.randn(SHAPE, dtype=torch.float32)
targets = torch.randint(0, NUM_CLASSES, (BATCH_SIZE,), dtype=torch.long)
return [logits.contiguous(), targets.contiguous()]
def get_init_inputs():
return [BETA, REDUCTION]