Merge pull request 'finish AngularDistance #62' (#503) from gsd123/GPUCodeForces:gsd62 into main

This commit is contained in:
wawahejun 2025-12-14 22:47:36 +08:00
commit 21a8cf7fda
4 changed files with 627 additions and 0 deletions

View File

@ -0,0 +1,380 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
N, D = 32, 64
class AngularDistanceCUDAOp(torch.autograd.Function):
epsilon = 1e-6
def forward(ctx, input, target, beta, reduction_id, op):
if not input.is_cuda: input = input.cuda()
if not target.is_cuda: target = target.cuda()
input = input.contiguous()
target = target.contiguous()
N_batch = input.size(0)
output, dot, norm_i, norm_t = op.angular_loss_forward_cuda(
input,
target,
reduction_id,
N_batch,
AngularDistanceCUDAOp.epsilon
)
ctx.save_for_backward(input, target, dot, norm_i, norm_t)
ctx.reduction_id = reduction_id
ctx.N = N_batch
ctx.op = op
return output
def backward(ctx, grad_output):
input, target, dot, norm_i, norm_t = ctx.saved_tensors
grad_out_scalar = 0.0
grad_output_n = None
if ctx.reduction_id != 0:
grad_out_scalar = grad_output[0]
if ctx.reduction_id == 1:
grad_out_scalar = grad_out_scalar / ctx.N
else:
grad_output_n = grad_output.contiguous()
grad_input = torch.empty_like(input)
grad_target = torch.empty_like(target)
ctx.op.angular_loss_backward_cuda(
grad_out_scalar,
grad_output_n,
input,
target,
dot,
norm_i,
norm_t,
grad_input,
grad_target,
ctx.reduction_id,
input.size(0),
input.size(1),
AngularDistanceCUDAOp.epsilon
)
return grad_input, grad_target, None, None, None
class ModelNew(nn.Module):
def __init__(self, reduction='mean', beta=1.0):
super().__init__()
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._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
#include <vector>
std::vector<torch::Tensor> angular_loss_forward_cuda(
torch::Tensor input,
torch::Tensor target,
int reduction,
int N,
float epsilon);
void angular_loss_backward_cuda(
float grad_out_scalar,
torch::Tensor grad_output_n,
torch::Tensor input,
torch::Tensor target,
torch::Tensor dot,
torch::Tensor norm_i,
torch::Tensor norm_t,
torch::Tensor grad_input,
torch::Tensor grad_target,
int reduction,
int N, int D,
float epsilon);
"""
cuda_source = """
#include <torch/extension.h>
#include <vector>
#include <algorithm>
#include <cuda_runtime.h>
#include <cmath>
#include <device_functions.h>
#include <math_functions.h>
#define BLOCK_SIZE 256
#define MAX_GRID_SIZE 4096
__inline__ __device__ double warp_reduce_sum_double(double val) {
#pragma unroll
for (int offset = 16; offset > 0; offset /= 2) {
val += __shfl_down_sync(0xffffffff, val, offset);
}
return val;
}
__inline__ __device__ double block_reduce_sum_double(double val) {
__shared__ double shared[32];
int lane = threadIdx.x % 32;
int wid = threadIdx.x / 32;
val = warp_reduce_sum_double(val);
if (lane == 0) shared[wid] = val;
__syncthreads();
val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0;
if (wid == 0) val = warp_reduce_sum_double(val);
return val;
}
__global__ void reduce_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int n)
{
double local_sum = 0.0;
int idx = blockIdx.x * blockDim.x + threadIdx.x;
for (int i = idx; i < n; i += blockDim.x * gridDim.x) {
local_sum += (double)input[i];
}
local_sum = block_reduce_sum_double(local_sum);
if (threadIdx.x == 0) {
atomicAdd(output, (float)local_sum);
}
}
__global__ void angular_fwd_kernel(
const float* __restrict__ input,
const float* __restrict__ target,
float* __restrict__ loss_n,
float* __restrict__ dot_out,
float* __restrict__ norm_i_out,
float* __restrict__ norm_t_out,
int N, int D,
float epsilon)
{
int n_idx = blockIdx.x;
if (n_idx >= N) return;
const float* in_ptr = input + n_idx * D;
const float* tgt_ptr = target + n_idx * D;
double local_dot = 0.0;
double local_norm_in_sq = 0.0;
double local_norm_tgt_sq = 0.0;
for (int i = threadIdx.x; i < D; i += blockDim.x) {
double in_i = (double)in_ptr[i];
double tgt_i = (double)tgt_ptr[i];
local_dot += in_i * tgt_i;
local_norm_in_sq += in_i * in_i;
local_norm_tgt_sq += tgt_i * tgt_i;
}
__shared__ double s_data[3];
if (threadIdx.x == 0) s_data[0] = 0.0;
if (threadIdx.x == 1) s_data[1] = 0.0;
if (threadIdx.x == 2) s_data[2] = 0.0;
__syncthreads();
local_dot = block_reduce_sum_double(local_dot);
local_norm_in_sq = block_reduce_sum_double(local_norm_in_sq);
local_norm_tgt_sq = block_reduce_sum_double(local_norm_tgt_sq);
if (threadIdx.x == 0) {
s_data[0] = local_dot;
s_data[1] = local_norm_in_sq;
s_data[2] = local_norm_tgt_sq;
}
__syncthreads();
if (threadIdx.x == 0) {
double dot_d = s_data[0];
double norm_in_d = sqrt(s_data[1]);
double norm_t_d = sqrt(s_data[2]);
double norm_mult_d = norm_in_d * norm_t_d + (double)epsilon;
double cos_sim_d = dot_d / norm_mult_d;
loss_n[n_idx] = (float)(1.0 - cos_sim_d);
dot_out[n_idx] = (float)dot_d;
norm_i_out[n_idx] = (float)norm_in_d;
norm_t_out[n_idx] = (float)norm_t_d;
}
}
__global__ void angular_bwd_kernel(
const double grad_out_scalar_d,
const float* __restrict__ grad_output_n,
const float* __restrict__ input,
const float* __restrict__ target,
const float* __restrict__ dot,
const float* __restrict__ norm_i,
const float* __restrict__ norm_t,
float* __restrict__ grad_input,
float* __restrict__ grad_target,
const int reduction,
const int N, const int D,
const double eps_d
)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int idx = i; idx < N * D; idx += stride) {
int n_idx = idx / D;
const double dot_d = (double)dot[n_idx];
const double norm_i_d = (double)norm_i[n_idx];
const double norm_t_d = (double)norm_t[n_idx];
const double u_i = (double)input[idx];
const double v_i = (double)target[idx];
const double grad_out_d = (reduction == 0) ?
(double)grad_output_n[n_idx] :
grad_out_scalar_d;
const double norm_i_sq = norm_i_d * norm_i_d + eps_d;
const double norm_t_sq = norm_t_d * norm_t_d + eps_d;
const double norm_mult = norm_i_d * norm_t_d + eps_d;
const double cos_sim = dot_d / norm_mult;
const double grad_u_i = (cos_sim * u_i / norm_i_sq) - (v_i / norm_mult);
grad_input[idx] = (float)(grad_u_i * grad_out_d);
const double grad_v_i = (cos_sim * v_i / norm_t_sq) - (u_i / norm_mult);
grad_target[idx] = (float)(grad_v_i * grad_out_d);
}
}
std::vector<torch::Tensor> angular_loss_forward_cuda(
torch::Tensor input,
torch::Tensor target,
int reduction,
int N,
float epsilon)
{
int D = input.size(1);
auto options = input.options();
torch::Tensor loss_n = torch::empty({N}, options);
torch::Tensor dot_out = torch::empty({N}, options);
torch::Tensor norm_i_out = torch::empty({N}, options);
torch::Tensor norm_t_out = torch::empty({N}, options);
const int block_size = BLOCK_SIZE;
const int grid_size = N;
angular_fwd_kernel<<<grid_size, block_size>>>(
input.data_ptr<float>(),
target.data_ptr<float>(),
loss_n.data_ptr<float>(),
dot_out.data_ptr<float>(),
norm_i_out.data_ptr<float>(),
norm_t_out.data_ptr<float>(),
N, D, epsilon
);
torch::Tensor output;
if (reduction == 0) {
output = loss_n;
} else {
output = torch::zeros({1}, options);
const int reduce_grid_size = std::min(
(int)((N + BLOCK_SIZE - 1) / BLOCK_SIZE),
MAX_GRID_SIZE
);
reduce_kernel<<<reduce_grid_size, BLOCK_SIZE>>>(
loss_n.data_ptr<float>(),
output.data_ptr<float>(),
N
);
if (reduction == 1) {
output.div_(N);
}
}
return {output, dot_out, norm_i_out, norm_t_out};
}
void angular_loss_backward_cuda(
float grad_out_scalar,
torch::Tensor grad_output_n,
torch::Tensor input,
torch::Tensor target,
torch::Tensor dot,
torch::Tensor norm_i,
torch::Tensor norm_t,
torch::Tensor grad_input,
torch::Tensor grad_target,
int reduction,
int N, int D,
float epsilon)
{
const int64_t n_total = N * D;
const int block_size = BLOCK_SIZE;
const int grid_size = std::min(
(int)((n_total + block_size - 1) / block_size),
MAX_GRID_SIZE
);
const float* grad_output_n_ptr = (reduction == 0) ?
grad_output_n.data_ptr<float>() :
nullptr;
angular_bwd_kernel<<<grid_size, block_size>>>(
(double)grad_out_scalar,
grad_output_n_ptr,
input.data_ptr<float>(),
target.data_ptr<float>(),
dot.data_ptr<float>(),
norm_i.data_ptr<float>(),
norm_t.data_ptr<float>(),
grad_input.data_ptr<float>(),
grad_target.data_ptr<float>(),
reduction,
N, D,
(double)epsilon
);
}
"""
self.op = load_inline(
name='angular_loss_cuda_v1_full_double',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['angular_loss_forward_cuda', 'angular_loss_backward_cuda'],
extra_cuda_cflags=['-O3'],
verbose=False
)
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
if isinstance(input, (list, tuple)) and len(input) > 0:
input = input[0]
target = target[0] if len(target) > 0 else target
return AngularDistanceCUDAOp.apply(
input,
target,
self.beta,
self.reduction_id,
self.op
)

View File

@ -0,0 +1,55 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
N, D = 32, 64
class AngularDistance(nn.Module):
def __init__(self, reduction='mean', beta=1.0):
super().__init__()
self.reduction = reduction
self.epsilon = 1e-6
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
dot_product = (input * target).sum(dim=1)
norm_input = input.norm(p=2, dim=1)
norm_target = target.norm(p=2, dim=1)
norm_mult = norm_input * norm_target
cosine_sim = dot_product / (norm_mult + self.epsilon)
loss = 1.0 - cosine_sim
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 = AngularDistance(reduction, beta)
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
if isinstance(input, (list, tuple)) and len(input) > 0:
input = input[0]
target = target[0] if len(target) > 0 else target
return self.op(input, target)
def get_inputs():
input = torch.randn(N, D, dtype=torch.float32)
target = torch.randn(N, D, dtype=torch.float32)
return [input, target]
def get_init_inputs():
return ['mean', 1.0]

120
S1/gsd123_#62/prompt.txt Normal file
View File

@ -0,0 +1,120 @@
You write custom CUDA kernels to replace the pytorch operators in the given GeGLU 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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
Core Optimization Techniques:
Performance Optimizations
Double Precision Reduction - Uses double for accumulation to maintain numerical accuracy
Two-Stage Reduction - Warp-level shuffle reduction + block-level shared memory reduction
Parallel Sample Processing - Each CUDA block processes one sample (N-wise parallelization)
Grid Size Optimization - Limits grid size to MAX_GRID_SIZE for optimal resource usage
Memory Optimizations
Intermediate Storage - Stores dot products and norms for backward pass reuse
Memory Coalescing - Ensures contiguous memory access patterns
Shared Memory Reduction - Uses shared memory for efficient block-level reductions
Numerical Stability
Double Precision - All intermediate calculations use double to prevent precision loss
Epsilon Protection - Adds epsilon to denominators to prevent division by zero
Stable Cosine Similarity - Properly handles norm calculations with epsilon protection
Mathematical Optimizations
Efficient Cosine Distance - Computes 1 - cos_sim for angular distance
Analytical Gradients - Implements exact mathematical derivatives for cosine similarity:
grad_u_i = (cos_sim * u_i / norm_i_sq) - (v_i / norm_mult)
grad_v_i = (cos_sim * v_i / norm_t_sq) - (u_i / norm_mult)
Kernel Design
Separate Forward/Backward Kernels - Optimized kernels for each pass
Flexible Reduction Support - Handles 'none', 'mean', and 'sum' reduction types
Atomic Reduction - Uses atomicAdd for efficient multi-block reduction
Key Features
High Precision - Double precision ensures numerical accuracy for angular calculations
Efficient Gradient Computation - Reuses precomputed terms from forward pass
Proper Normalization - Correctly handles vector normalization in both forward and backward passes
Memory Efficient - Stores only necessary intermediate terms for gradients
This implementation provides highly accurate angular distance computation with proper gradient propagation, essential for metric learning and similarity-based tasks
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, D = 32, 64
class AngularDistance(nn.Module):
def __init__(self, reduction='mean', beta=1.0):
super().__init__()
self.reduction = reduction
self.epsilon = 1e-6
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
dot_product = (input * target).sum(dim=1)
norm_input = input.norm(p=2, dim=1)
norm_target = target.norm(p=2, dim=1)
norm_mult = norm_input * norm_target
cosine_sim = dot_product / (norm_mult + self.epsilon)
loss = 1.0 - cosine_sim
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 = AngularDistance(reduction, beta)
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
if isinstance(input, (list, tuple)) and len(input) > 0:
input = input[0]
target = target[0] if len(target) > 0 else target
return self.op(input, target)
def get_inputs():
input = torch.randn(N, D, dtype=torch.float32)
target = torch.randn(N, D, dtype=torch.float32)
return [input, target]
def get_init_inputs():
return ['mean', 1.0]

72
S1/gsd123_#62/run_code.py Normal file
View File

@ -0,0 +1,72 @@
import torch
import time
from AngularDistance_torch import Model, get_inputs, get_init_inputs
from AngularDistance_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()