forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish SmoothL1Loss # 40' (#68) from gsd123/GPUCodeForces:SmoothL1Loss into main
This commit is contained in:
commit
03e096a206
|
|
@ -0,0 +1,195 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, reduction='mean', beta=1.0):
|
||||
super().__init__()
|
||||
self.reduction = reduction
|
||||
self.beta = float(beta)
|
||||
|
||||
self.red_map = {'none': 0, 'mean': 1, 'sum': 2}
|
||||
if reduction not in self.red_map:
|
||||
raise ValueError("Invalid reduction")
|
||||
self.reduction_id = self.red_map[reduction]
|
||||
|
||||
self.block_size = 256
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
torch::Tensor smooth_l1_forward_cuda(
|
||||
torch::Tensor input,
|
||||
torch::Tensor target,
|
||||
float beta,
|
||||
int reduction);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define WARP_SIZE 32
|
||||
|
||||
__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;
|
||||
}
|
||||
|
||||
__inline__ __device__ float block_reduce_sum(float val) {
|
||||
__shared__ float shared[32];
|
||||
int lane = threadIdx.x % 32;
|
||||
int wid = threadIdx.x / 32;
|
||||
|
||||
val = warp_reduce_sum(val);
|
||||
if (lane == 0) shared[wid] = val;
|
||||
__syncthreads();
|
||||
|
||||
val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0f;
|
||||
if (wid == 0) val = warp_reduce_sum(val);
|
||||
return val;
|
||||
}
|
||||
|
||||
__global__ void smooth_l1_kernel(
|
||||
const float* __restrict__ input,
|
||||
const float* __restrict__ target,
|
||||
float* __restrict__ output,
|
||||
int n,
|
||||
float beta,
|
||||
int reduction
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int stride = blockDim.x * gridDim.x;
|
||||
|
||||
float local_sum = 0.0f;
|
||||
|
||||
float4* in_ptr = (float4*)input;
|
||||
float4* tgt_ptr = (float4*)target;
|
||||
float4* out_ptr = (float4*)output;
|
||||
|
||||
int vec_n = n / 4;
|
||||
|
||||
for (int i = idx; i < vec_n; i += stride) {
|
||||
float4 in_val = in_ptr[i];
|
||||
float4 tgt_val = tgt_ptr[i];
|
||||
float4 out_val;
|
||||
|
||||
float diff[4];
|
||||
diff[0] = fabsf(in_val.x - tgt_val.x);
|
||||
diff[1] = fabsf(in_val.y - tgt_val.y);
|
||||
diff[2] = fabsf(in_val.z - tgt_val.z);
|
||||
diff[3] = fabsf(in_val.w - tgt_val.w);
|
||||
|
||||
float losses[4];
|
||||
#pragma unroll
|
||||
for(int k=0; k<4; ++k) {
|
||||
if (diff[k] < beta) {
|
||||
losses[k] = 0.5f * diff[k] * diff[k] / beta;
|
||||
} else {
|
||||
losses[k] = diff[k] - 0.5f * beta;
|
||||
}
|
||||
}
|
||||
|
||||
if (reduction == 0) {
|
||||
out_val.x = losses[0];
|
||||
out_val.y = losses[1];
|
||||
out_val.z = losses[2];
|
||||
out_val.w = losses[3];
|
||||
out_ptr[i] = out_val;
|
||||
} else {
|
||||
local_sum += losses[0] + losses[1] + losses[2] + losses[3];
|
||||
}
|
||||
}
|
||||
|
||||
int rem_start = vec_n * 4;
|
||||
for (int i = rem_start + idx; i < n; i += stride) {
|
||||
float d = fabsf(input[i] - target[i]);
|
||||
float l;
|
||||
if (d < beta) {
|
||||
l = 0.5f * d * d / beta;
|
||||
} else {
|
||||
l = d - 0.5f * beta;
|
||||
}
|
||||
|
||||
if (reduction == 0) {
|
||||
output[i] = l;
|
||||
} else {
|
||||
local_sum += l;
|
||||
}
|
||||
}
|
||||
|
||||
if (reduction != 0) {
|
||||
local_sum = block_reduce_sum(local_sum);
|
||||
if (threadIdx.x == 0) {
|
||||
atomicAdd(output, local_sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor smooth_l1_forward_cuda(
|
||||
torch::Tensor input,
|
||||
torch::Tensor target,
|
||||
float beta,
|
||||
int reduction)
|
||||
{
|
||||
int64_t n = input.numel();
|
||||
auto options = input.options();
|
||||
|
||||
torch::Tensor output;
|
||||
if (reduction == 0) {
|
||||
output = torch::empty_like(input);
|
||||
} else {
|
||||
output = torch::zeros({1}, options);
|
||||
}
|
||||
|
||||
const int block_size = 256;
|
||||
const int grid_size = std::min((int)((n + block_size * 4 - 1) / (block_size * 4)), 1024);
|
||||
|
||||
smooth_l1_kernel<<<grid_size, block_size>>>(
|
||||
input.data_ptr<float>(),
|
||||
target.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
n,
|
||||
beta,
|
||||
reduction
|
||||
);
|
||||
|
||||
if (reduction == 1) {
|
||||
output.div_(n);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name='smooth_l1_cuda_opt',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['smooth_l1_forward_cuda'],
|
||||
extra_cuda_cflags=['-O3', '--use_fast_math'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
if not input.is_cuda: input = input.cuda()
|
||||
if not target.is_cuda: target = target.cuda()
|
||||
|
||||
input = input.contiguous()
|
||||
target = target.contiguous()
|
||||
|
||||
return self.op.smooth_l1_forward_cuda(
|
||||
input,
|
||||
target,
|
||||
self.beta,
|
||||
self.reduction_id
|
||||
)
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
|
||||
|
||||
class SmoothL1Loss(nn.Module):
|
||||
def __init__(self, reduction='mean', beta=1.0):
|
||||
super().__init__()
|
||||
self.reduction = reduction
|
||||
self.beta = beta
|
||||
|
||||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
diff = torch.abs(input - target)
|
||||
|
||||
if self.beta == 0:
|
||||
loss = diff
|
||||
else:
|
||||
loss = torch.where(
|
||||
diff < self.beta,
|
||||
0.5 * diff * diff / self.beta,
|
||||
diff - 0.5 * self.beta
|
||||
)
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else:
|
||||
return loss
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, reduction='mean', beta=1.0):
|
||||
super().__init__()
|
||||
self.op = SmoothL1Loss(reduction, beta)
|
||||
|
||||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(input, target)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
input = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
target = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [input, target]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return ['mean', 1.0]
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
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.
|
||||
|
||||
Technical Overview: CUDA-Optimized Smooth L1 Loss (Huber Loss)
|
||||
This implementation provides a high-performance CUDA kernel for computing Smooth L1 Loss, a robust loss function that combines the benefits of L1 and L2 losses, designed for regression tasks with optimized parallel computation.
|
||||
Key Features:
|
||||
Architecture:
|
||||
Custom CUDA kernel with inline compilation using PyTorch C++ extensions
|
||||
Optimized for NVIDIA GPUs with warp-level and block-level parallel reduction
|
||||
Supports 4-element vectorization (float4) for memory coalescing
|
||||
Implements three reduction modes: 'none', 'mean', and 'sum'
|
||||
Performance Optimizations:
|
||||
Vectorized Memory Access: Uses float4 data type to process 4 elements simultaneously
|
||||
Two-Phase Processing: Main loop processes vectorized elements, tail handles remaining elements
|
||||
Parallel Reduction: Efficient warp and block-level reduction for sum/mean operations
|
||||
Atomic Operations: Global atomic addition for final reduction across blocks
|
||||
Coalesced Memory: Contiguous memory access patterns throughout
|
||||
Kernel Specifications:
|
||||
Block size: 256 threads
|
||||
Warp size: 32 threads
|
||||
Grid size: Adaptive based on input size (up to 1024 blocks)
|
||||
Memory alignment: Requires element count divisible by 4 for optimal vectorization
|
||||
Reduction Modes:
|
||||
'none': Returns element-wise loss tensor of same shape as input
|
||||
'mean': Returns scalar mean loss across all elements
|
||||
'sum': Returns scalar sum loss across all elements
|
||||
Key Components:
|
||||
Conditional Loss Calculation: Branch-based selection between L2 (quadratic) and L1 (linear) regimes
|
||||
Beta Parameter: Threshold parameter controlling the transition between L1 and L2 behavior
|
||||
Numerical Stability: No explicit epsilon needed due to stable mathematical formulation
|
||||
Efficient Reduction: Hierarchical reduction (warp → block → global) for parallel aggregation
|
||||
Advantages over Standard Losses:
|
||||
L1 Loss: Less sensitive to outliers but has discontinuous gradients
|
||||
L2 Loss: Smooth gradients but overly sensitive to outliers
|
||||
Smooth L1: Combines benefits - L2-like behavior near zero (smooth gradients) and L1-like behavior for large errors (robust to outliers)
|
||||
Interface:
|
||||
Input: Two tensors (input, target) of any identical shape
|
||||
Parameters: Beta value (default=1.0) and reduction mode
|
||||
Output: Scalar loss or element-wise loss tensor based on reduction mode
|
||||
Automatic GPU tensor handling with device transfer and memory contiguity enforcement
|
||||
Typical Applications:
|
||||
Object detection (e.g., Faster R-CNN bounding box regression)
|
||||
Robust regression tasks with potential outliers
|
||||
Computer vision tasks requiring precise localization
|
||||
Any regression problem where error distribution may contain outliers
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
class SmoothL1Loss(nn.Module):
|
||||
def __init__(self, reduction='mean', beta=1.0):
|
||||
super().__init__()
|
||||
self.reduction = reduction
|
||||
self.beta = beta
|
||||
|
||||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
diff = torch.abs(input - target)
|
||||
|
||||
if self.beta == 0:
|
||||
loss = diff
|
||||
else:
|
||||
loss = torch.where(
|
||||
diff < self.beta,
|
||||
0.5 * diff * diff / self.beta,
|
||||
diff - 0.5 * self.beta
|
||||
)
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else:
|
||||
return loss
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, reduction='mean', beta=1.0):
|
||||
super().__init__()
|
||||
self.op = SmoothL1Loss(reduction, beta)
|
||||
|
||||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
return self.op(input, target)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
input = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
target = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [input, target]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return ['mean', 1.0]
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from SmoothL1Loss_torch import Model, get_inputs, get_init_inputs
|
||||
from SmoothL1Loss_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