forked from ccf-ai-infra/GPUCodeForces
fixes marginrankingloss #16
This commit is contained in:
parent
bee0a2a683
commit
0d044322ef
|
|
@ -0,0 +1,122 @@
|
|||
# marginrankingloss_cuda.py
|
||||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
from marginrankingloss_torch import BATCH_SIZE, FEATURE_DIM, MARGIN
|
||||
|
||||
|
||||
|
||||
N_ELEMENTS = BATCH_SIZE * FEATURE_DIM
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor mrl_forward_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor target, float margin_val);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
#include <float.h>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define MARGIN_VAL {margin_val}f
|
||||
|
||||
__device__ __forceinline__ float warp_reduce_sum(float val) {{
|
||||
for (int offset = BLOCK_SIZE / 2; offset > 0; offset /= 2) {{
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
}}
|
||||
return val;
|
||||
}}
|
||||
|
||||
|
||||
__global__ void mrl_fused_kernel(
|
||||
const float* __restrict__ x1,
|
||||
const float* __restrict__ x2,
|
||||
const float* __restrict__ target,
|
||||
float* __restrict__ loss_sum_out,
|
||||
int n_elements,
|
||||
float margin_val
|
||||
) {{
|
||||
__shared__ float s_data[BLOCK_SIZE];
|
||||
|
||||
// Grid-Stride Loop
|
||||
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 val1 = x1[idx];
|
||||
float val2 = x2[idx];
|
||||
float y = target[idx];
|
||||
|
||||
// Loss = max(0, -y * (x1 - x2) + margin)
|
||||
|
||||
float diff = val1 - val2;
|
||||
float term = -y * diff + MARGIN_VAL;
|
||||
|
||||
float loss_val = fmaxf(0.0f, term);
|
||||
|
||||
thread_loss += loss_val;
|
||||
}}
|
||||
|
||||
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 mrl_forward_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor target, float margin_val) {{
|
||||
TORCH_CHECK(x1.is_cuda(), "Input must be a CUDA tensor");
|
||||
x1 = x1.contiguous();
|
||||
x2 = x2.contiguous();
|
||||
target = target.contiguous();
|
||||
|
||||
int n_elements = x1.numel();
|
||||
|
||||
const int block_size = BLOCK_SIZE;
|
||||
const int grid_size = std::max(1, (n_elements + block_size - 1) / block_size);
|
||||
|
||||
auto block_loss_sums = torch::empty({{grid_size}}, x1.options());
|
||||
|
||||
mrl_fused_kernel<<<grid_size, block_size>>>(
|
||||
x1.data_ptr<float>(),
|
||||
x2.data_ptr<float>(),
|
||||
target.data_ptr<float>(),
|
||||
block_loss_sums.data_ptr<float>(),
|
||||
n_elements,
|
||||
margin_val
|
||||
);
|
||||
|
||||
|
||||
return block_loss_sums.sum() / n_elements;
|
||||
}}
|
||||
""".format(margin_val=MARGIN)
|
||||
|
||||
self.mrl_op = load_inline(
|
||||
name="mrl_fused_op_safest",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["mrl_forward_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
return self.mrl_op.mrl_forward_cuda(x1, x2, target, MARGIN)
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
# marginrankingloss_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
BATCH_SIZE = 4096
|
||||
FEATURE_DIM = 512
|
||||
MARGIN = 1.0
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.criterion = nn.MarginRankingLoss(margin=MARGIN, reduction='mean')
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.criterion(x1, x2, target)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x1 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
x2 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
target = torch.randint(0, 2, (BATCH_SIZE, FEATURE_DIM), dtype=torch.float32)
|
||||
target[target == 0] = -1
|
||||
return [x1, x2, target]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
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
|
||||
# marginrankingloss_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
BATCH_SIZE = 4096
|
||||
FEATURE_DIM = 512
|
||||
MARGIN = 1.0
|
||||
|
||||
class Model(nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.criterion = nn.MarginRankingLoss(margin=MARGIN, reduction='mean')
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
return self.criterion(x1, x2, target)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x1 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
x2 = torch.randn(BATCH_SIZE, FEATURE_DIM, dtype=torch.float32)
|
||||
target = torch.randint(0, 2, (BATCH_SIZE, FEATURE_DIM), dtype=torch.float32)
|
||||
target[target == 0] = -1
|
||||
return [x1, x2, target]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from marginrankingloss_torch import Model, get_inputs, get_init_inputs
|
||||
from marginrankingloss_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