forked from ccf-ai-infra/GPUCodeForces
fixes bcewithlogitsloss #14
This commit is contained in:
parent
5dd881c63d
commit
9caad44d08
|
|
@ -0,0 +1,115 @@
|
|||
# bcewithlogitsloss_cuda.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
from bcewithlogitsloss_torch import BATCH_SIZE, FEATURE_DIM # 导入维度常量
|
||||
|
||||
N_ELEMENTS = BATCH_SIZE * FEATURE_DIM
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor bce_forward_cuda(torch::Tensor logits, torch::Tensor target);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
#include <float.h> // For FLT_MAX
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define WARP_SIZE 32
|
||||
|
||||
__device__ __forceinline__ float warp_reduce_sum(float val) {
|
||||
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
return val;
|
||||
}
|
||||
|
||||
__global__ void bce_fused_kernel(
|
||||
const float* __restrict__ logits,
|
||||
const float* __restrict__ target,
|
||||
float* __restrict__ loss_sum_out,
|
||||
int n_elements
|
||||
) {
|
||||
__shared__ float s_data[BLOCK_SIZE];
|
||||
|
||||
|
||||
float thread_loss = 0.0f;
|
||||
int grid_stride = gridDim.x * blockDim.x;
|
||||
|
||||
for (int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
idx < n_elements;
|
||||
idx += grid_stride)
|
||||
{
|
||||
float x = logits[idx];
|
||||
float y = target[idx];
|
||||
|
||||
float max_val = fmaxf(0.0f, x);
|
||||
|
||||
|
||||
if (x >= 0) {
|
||||
thread_loss += (x - x * y) + logf(1.0f + expf(-x));
|
||||
} else {
|
||||
thread_loss += (-x * y) + logf(1.0f + expf(x));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
s_data[threadIdx.x] = thread_loss;
|
||||
__syncthreads();
|
||||
|
||||
|
||||
for (int offset = BLOCK_SIZE / 2; offset > 0; offset >>= 1) {
|
||||
if (threadIdx.x < offset) {
|
||||
s_data[threadIdx.x] += s_data[threadIdx.x + offset];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
|
||||
if (threadIdx.x == 0) {
|
||||
loss_sum_out[blockIdx.x] = s_data[0];
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor bce_forward_cuda(torch::Tensor logits, torch::Tensor target) {
|
||||
TORCH_CHECK(logits.is_cuda(), "Input must be a CUDA tensor");
|
||||
logits = logits.contiguous();
|
||||
target = target.contiguous();
|
||||
|
||||
int n_elements = logits.numel();
|
||||
|
||||
const int block_size = BLOCK_SIZE;
|
||||
const int grid_size = (n_elements + block_size - 1) / block_size;
|
||||
|
||||
auto block_loss_sums = torch::empty({grid_size}, logits.options());
|
||||
|
||||
bce_fused_kernel<<<grid_size, block_size>>>(
|
||||
logits.data_ptr<float>(),
|
||||
target.data_ptr<float>(),
|
||||
block_loss_sums.data_ptr<float>(),
|
||||
n_elements
|
||||
);
|
||||
|
||||
return block_loss_sums.sum() / n_elements;
|
||||
}
|
||||
"""
|
||||
|
||||
self.bce_op = load_inline(
|
||||
name="bce_fused_op",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["bce_forward_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def forward(self, logits: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
return self.bce_op.bce_forward_cuda(logits, target)
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
# bcewithlogitsloss_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
BATCH_SIZE = 4096
|
||||
FEATURE_DIM = 256
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.criterion = nn.BCEWithLogitsLoss(reduction='mean')
|
||||
|
||||
def forward(self, logits: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.criterion(logits, target)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
logits = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
target = torch.randint(0, 2, (BATCH_SIZE, FEATURE_DIM), dtype=torch.float32)
|
||||
return [logits, target]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
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.
|
||||
|
||||
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
|
||||
|
||||
```python
|
||||
# bcewithlogitsloss_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
BATCH_SIZE = 4096
|
||||
FEATURE_DIM = 256
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.criterion = nn.BCEWithLogitsLoss(reduction='mean')
|
||||
|
||||
def forward(self, logits: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.criterion(logits, target)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
logits = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
target = torch.randint(0, 2, (BATCH_SIZE, FEATURE_DIM), dtype=torch.float32)
|
||||
return [logits, target]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from bcewithlogitsloss_torch import Model, get_inputs, get_init_inputs
|
||||
from bcewithlogitsloss_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)
|
||||
|
||||
# 更严格的精度检查
|
||||
abs_diff = (output_torch - output_cuda).abs()
|
||||
max_diff = abs_diff.max().item()
|
||||
mean_diff = abs_diff.mean().item()
|
||||
|
||||
print(f"最大差异: {max_diff:.6f}")
|
||||
print(f"平均差异: {mean_diff:.6f}")
|
||||
|
||||
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
|
||||
if precision_flag:
|
||||
print("✅ 精度对齐:两个模型的输出结果非常接近。")
|
||||
else:
|
||||
print("❌ 精度不一致!")
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
|
||||
|
||||
# Warm up
|
||||
for _ in range(100):
|
||||
_ = 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒")
|
||||
print(f"自定义 CUDA ReLU 平均执行时间: {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