forked from ccf-ai-infra/GPUCodeForces
finish CosineEmbeddingLoss #37
This commit is contained in:
parent
e309547055
commit
5893bd3f6b
|
|
@ -0,0 +1,230 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-8
|
||||
|
||||
assert (C * H * W) % 4 == 0, "Instance size (C*H*W) must be a multiple of 4"
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
|
||||
def __init__(self, margin=0.5):
|
||||
super().__init__()
|
||||
self.margin = margin
|
||||
self.eps = EPS
|
||||
self.block_size = 256
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
torch::Tensor cosine_loss_forward_cuda(
|
||||
torch::Tensor x1,
|
||||
torch::Tensor x2,
|
||||
torch::Tensor target,
|
||||
float margin,
|
||||
float eps,
|
||||
int N,
|
||||
int D);
|
||||
"""
|
||||
|
||||
cuda_source = f"""
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE {self.block_size}
|
||||
#define WARP_SIZE 32
|
||||
#define ILP 4
|
||||
|
||||
|
||||
__inline__ __device__ float warp_reduce_sum(float val) {{
|
||||
#pragma unroll
|
||||
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {{
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
}}
|
||||
return val;
|
||||
}}
|
||||
|
||||
|
||||
__global__ void cosine_embedding_kernel(
|
||||
const float* __restrict__ x1,
|
||||
const float* __restrict__ x2,
|
||||
const float* __restrict__ target,
|
||||
float* __restrict__ output,
|
||||
float margin,
|
||||
float eps,
|
||||
int D_vec // D / 4
|
||||
) {{
|
||||
|
||||
const int n_idx = blockIdx.x;
|
||||
|
||||
|
||||
const int offset = n_idx * D_vec * 4;
|
||||
|
||||
const float4* x1_ptr = reinterpret_cast<const float4*>(x1 + offset);
|
||||
const float4* x2_ptr = reinterpret_cast<const float4*>(x2 + offset);
|
||||
|
||||
float sum_dot = 0.0f;
|
||||
float sum_sq1 = 0.0f;
|
||||
float sum_sq2 = 0.0f;
|
||||
|
||||
|
||||
for (int i = threadIdx.x * ILP; i < D_vec; i += blockDim.x * ILP) {{
|
||||
float4 r1[ILP];
|
||||
float4 r2[ILP];
|
||||
|
||||
|
||||
#pragma unroll
|
||||
for (int k = 0; k < ILP; ++k) {{
|
||||
if (i + k < D_vec) {{
|
||||
r1[k] = __ldg(&x1_ptr[i + k]);
|
||||
r2[k] = __ldg(&x2_ptr[i + k]);
|
||||
}} else {{
|
||||
r1[k] = make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
r2[k] = make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
}}
|
||||
}}
|
||||
|
||||
// 2. 计算累加
|
||||
#pragma unroll
|
||||
for (int k = 0; k < ILP; ++k) {{
|
||||
// Dot Product
|
||||
sum_dot += r1[k].x * r2[k].x;
|
||||
sum_dot += r1[k].y * r2[k].y;
|
||||
sum_dot += r1[k].z * r2[k].z;
|
||||
sum_dot += r1[k].w * r2[k].w;
|
||||
|
||||
// Norm Sq 1
|
||||
sum_sq1 += r1[k].x * r1[k].x;
|
||||
sum_sq1 += r1[k].y * r1[k].y;
|
||||
sum_sq1 += r1[k].z * r1[k].z;
|
||||
sum_sq1 += r1[k].w * r1[k].w;
|
||||
|
||||
// Norm Sq 2
|
||||
sum_sq2 += r2[k].x * r2[k].x;
|
||||
sum_sq2 += r2[k].y * r2[k].y;
|
||||
sum_sq2 += r2[k].z * r2[k].z;
|
||||
sum_sq2 += r2[k].w * r2[k].w;
|
||||
}}
|
||||
}}
|
||||
|
||||
|
||||
__shared__ float shared_data[32][3];
|
||||
|
||||
int lane = threadIdx.x % WARP_SIZE;
|
||||
int wid = threadIdx.x / WARP_SIZE;
|
||||
|
||||
|
||||
sum_dot = warp_reduce_sum(sum_dot);
|
||||
sum_sq1 = warp_reduce_sum(sum_sq1);
|
||||
sum_sq2 = warp_reduce_sum(sum_sq2);
|
||||
|
||||
|
||||
if (lane == 0) {{
|
||||
shared_data[wid][0] = sum_dot;
|
||||
shared_data[wid][1] = sum_sq1;
|
||||
shared_data[wid][2] = sum_sq2;
|
||||
}}
|
||||
__syncthreads();
|
||||
|
||||
|
||||
if (wid == 0) {{
|
||||
// 读取
|
||||
sum_dot = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared_data[lane][0] : 0.0f;
|
||||
sum_sq1 = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared_data[lane][1] : 0.0f;
|
||||
sum_sq2 = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared_data[lane][2] : 0.0f;
|
||||
|
||||
|
||||
sum_dot = warp_reduce_sum(sum_dot);
|
||||
sum_sq1 = warp_reduce_sum(sum_sq1);
|
||||
sum_sq2 = warp_reduce_sum(sum_sq2);
|
||||
|
||||
|
||||
if (threadIdx.x == 0) {{
|
||||
float norm1 = sqrtf(sum_sq1);
|
||||
float norm2 = sqrtf(sum_sq2);
|
||||
float cos_sim = sum_dot / (norm1 * norm2 + eps);
|
||||
|
||||
float t_val = target[n_idx];
|
||||
float loss = 0.0f;
|
||||
|
||||
if (t_val == 1.0f) {{
|
||||
loss = 1.0f - cos_sim;
|
||||
}} else {{
|
||||
loss = fmaxf(0.0f, cos_sim - margin);
|
||||
}}
|
||||
|
||||
output[n_idx] = loss;
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
|
||||
torch::Tensor cosine_loss_forward_cuda(
|
||||
torch::Tensor x1,
|
||||
torch::Tensor x2,
|
||||
torch::Tensor target,
|
||||
float margin,
|
||||
float eps,
|
||||
int N,
|
||||
int D)
|
||||
{{
|
||||
x1 = x1.contiguous();
|
||||
x2 = x2.contiguous();
|
||||
target = target.contiguous();
|
||||
|
||||
auto output = torch::empty({{N}}, x1.options());
|
||||
|
||||
int D_vec = D / 4;
|
||||
|
||||
// Grid = Batch Size, Block = 256
|
||||
dim3 blocks(N);
|
||||
dim3 threads(BLOCK_SIZE);
|
||||
|
||||
cosine_embedding_kernel<<<blocks, threads>>>(
|
||||
x1.data_ptr<float>(),
|
||||
x2.data_ptr<float>(),
|
||||
target.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
margin,
|
||||
eps,
|
||||
D_vec
|
||||
);
|
||||
|
||||
return output;
|
||||
}}
|
||||
"""
|
||||
|
||||
self.op = load_inline(
|
||||
name='cosine_loss_cuda_v1',
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=['cosine_loss_forward_cuda'],
|
||||
extra_cuda_cflags=['-O3', '--use_fast_math'],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
x1_flat = x1.view(x1.size(0), -1)
|
||||
x2_flat = x2.view(x2.size(0), -1)
|
||||
|
||||
if not x1_flat.is_cuda: x1_flat = x1_flat.cuda()
|
||||
if not x2_flat.is_cuda: x2_flat = x2_flat.cuda()
|
||||
if not target.is_cuda: target = target.cuda()
|
||||
|
||||
N, D = x1_flat.shape
|
||||
|
||||
out = self.op.cosine_loss_forward_cuda(
|
||||
x1_flat,
|
||||
x2_flat,
|
||||
target,
|
||||
self.margin,
|
||||
self.eps,
|
||||
N,
|
||||
D
|
||||
)
|
||||
|
||||
return out.mean()
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-8
|
||||
|
||||
|
||||
class CosineEmbeddingLossCustom(nn.Module):
|
||||
|
||||
def __init__(self, margin=0.0, reduction='mean', eps=1e-8):
|
||||
super().__init__()
|
||||
self.margin = margin
|
||||
self.reduction = reduction
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
dot_product = torch.sum(x1 * x2, dim=1)
|
||||
norm_x1 = torch.norm(x1, p=2, dim=1)
|
||||
norm_x2 = torch.norm(x2, p=2, dim=1)
|
||||
|
||||
cos_sim = dot_product / (norm_x1 * norm_x2 + self.eps)
|
||||
|
||||
loss_pos = 1.0 - cos_sim
|
||||
loss_neg = F.relu(cos_sim - self.margin)
|
||||
|
||||
loss = torch.where(target == 1, loss_pos, loss_neg)
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else:
|
||||
return loss
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, margin=0.5):
|
||||
super().__init__()
|
||||
self.op = CosineEmbeddingLossCustom(margin=margin, reduction='mean', eps=EPS)
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
x1_flat = x1.view(x1.size(0), -1)
|
||||
x2_flat = x2.view(x2.size(0), -1)
|
||||
return self.op(x1_flat, x2_flat, target)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
x1 = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
x2 = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
|
||||
target = torch.randint(0, 2, (N,), dtype=torch.float32) # 0 or 1
|
||||
target = torch.where(target == 0, torch.tensor(-1.0), torch.tensor(1.0))
|
||||
|
||||
return [x1, x2, target]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return [0.5]
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
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 Cosine Embedding Loss
|
||||
This implementation provides a high-performance CUDA kernel for computing cosine embedding loss, designed for deep learning applications with optimized memory access and parallel computation.
|
||||
Key Features:
|
||||
Architecture:
|
||||
Custom CUDA kernel with inline compilation using PyTorch C++ extensions
|
||||
Optimized for NVIDIA GPUs with warp-level parallelism and shared memory utilization
|
||||
Supports 4-element vectorization (float4) for memory coalescing
|
||||
Performance Optimizations:
|
||||
Vectorized Memory Access: Uses float4 data type to load 4 elements per instruction
|
||||
Instruction-Level Parallelism (ILP): Processes 4 vectors simultaneously per thread
|
||||
Warp Reduction: Efficient warp-level reduction operations using __shfl_down_sync
|
||||
Shared Memory: Intermediate results stored in shared memory for block-level reduction
|
||||
Memory Coalescing: Contiguous memory access patterns for optimal bandwidth utilization
|
||||
Kernel Specifications:
|
||||
Block size: 256 threads
|
||||
Warp size: 32 threads
|
||||
Grid dimension: N (batch size)
|
||||
Input requirement: C×H×W must be divisible by 4 for vectorization
|
||||
|
||||
|
||||
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
|
||||
EPS = 1e-8
|
||||
|
||||
class CosineEmbeddingLossCustom(nn.Module):
|
||||
|
||||
def __init__(self, margin=0.0, reduction='mean', eps=1e-8):
|
||||
super().__init__()
|
||||
self.margin = margin
|
||||
self.reduction = reduction
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
|
||||
dot_product = torch.sum(x1 * x2, dim=1)
|
||||
norm_x1 = torch.norm(x1, p=2, dim=1)
|
||||
norm_x2 = torch.norm(x2, p=2, dim=1)
|
||||
|
||||
cos_sim = dot_product / (norm_x1 * norm_x2 + self.eps)
|
||||
|
||||
|
||||
|
||||
loss_pos = 1.0 - cos_sim
|
||||
loss_neg = F.relu(cos_sim - self.margin)
|
||||
|
||||
|
||||
loss = torch.where(target == 1, loss_pos, loss_neg)
|
||||
|
||||
|
||||
if self.reduction == 'mean':
|
||||
return loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return loss.sum()
|
||||
else:
|
||||
return loss
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, margin=0.5):
|
||||
super().__init__()
|
||||
self.op = CosineEmbeddingLossCustom(margin=margin, reduction='mean', eps=EPS)
|
||||
|
||||
def forward(self, x1: torch.Tensor, x2: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
x1_flat = x1.view(x1.size(0), -1)
|
||||
x2_flat = x2.view(x2.size(0), -1)
|
||||
return self.op(x1_flat, x2_flat, target)
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x1 = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
x2 = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
|
||||
|
||||
target = torch.randint(0, 2, (N,), dtype=torch.float32) # 0 or 1
|
||||
target = torch.where(target == 0, torch.tensor(-1.0), torch.tensor(1.0))
|
||||
|
||||
return [x1, x2, target]
|
||||
|
||||
def get_init_inputs():
|
||||
return [0.5] # margin
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from CosineEmbeddingLoss_torch import Model, get_inputs, get_init_inputs
|
||||
from CosineEmbeddingLoss_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