forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish ContrastivePredictiveCodingLoss #106' (#466) from gsd123/GPUCodeForces:gsd106 into main
This commit is contained in:
commit
afe7ce5a0f
|
|
@ -0,0 +1,125 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
cuda_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
__global__ void info_nce_kernel(
|
||||
const float* __restrict__ context,
|
||||
const float* __restrict__ positive,
|
||||
const float* __restrict__ negatives,
|
||||
float* output,
|
||||
int batch_size,
|
||||
int dim,
|
||||
int num_negatives
|
||||
) {
|
||||
extern __shared__ float shared_mem[];
|
||||
float* s_ctx = shared_mem;
|
||||
float* s_scores = shared_mem + dim;
|
||||
|
||||
int bid = blockIdx.x;
|
||||
int tid = threadIdx.x;
|
||||
int lane = tid % 32;
|
||||
int warp_id = tid / 32;
|
||||
int num_warps = blockDim.x / 32;
|
||||
|
||||
if (bid >= batch_size) return;
|
||||
|
||||
for (int i = tid; i < dim; i += blockDim.x) {
|
||||
s_ctx[i] = context[bid * dim + i];
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
int total_scores = 1 + num_negatives;
|
||||
|
||||
for (int k = warp_id; k < total_scores; k += num_warps) {
|
||||
const float* target_ptr;
|
||||
if (k == 0) {
|
||||
target_ptr = positive + bid * dim;
|
||||
} else {
|
||||
target_ptr = negatives + bid * (num_negatives * dim) + (k - 1) * dim;
|
||||
}
|
||||
|
||||
float dot = 0.0f;
|
||||
for (int i = lane; i < dim; i += 32) {
|
||||
dot += s_ctx[i] * target_ptr[i];
|
||||
}
|
||||
|
||||
for (int offset = 16; offset > 0; offset /= 2) {
|
||||
dot += __shfl_down_sync(0xffffffff, dot, offset);
|
||||
}
|
||||
|
||||
if (lane == 0) {
|
||||
s_scores[k] = dot;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if (tid == 0) {
|
||||
float max_val = -1e38f;
|
||||
for (int i = 0; i < total_scores; ++i) {
|
||||
if (s_scores[i] > max_val) max_val = s_scores[i];
|
||||
}
|
||||
|
||||
float sum_exp = 0.0f;
|
||||
for (int i = 0; i < total_scores; ++i) {
|
||||
sum_exp += expf(s_scores[i] - max_val);
|
||||
}
|
||||
|
||||
float log_sum = logf(sum_exp) + max_val;
|
||||
float pos_score = s_scores[0];
|
||||
float loss = log_sum - pos_score;
|
||||
|
||||
atomicAdd(output, loss / batch_size);
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor info_nce_cuda(torch::Tensor context, torch::Tensor positive, torch::Tensor negatives) {
|
||||
auto context_c = context.contiguous();
|
||||
auto positive_c = positive.contiguous();
|
||||
auto negatives_c = negatives.contiguous();
|
||||
|
||||
int batch_size = context.size(0);
|
||||
int dim = context.size(1);
|
||||
int num_negatives = negatives.size(1);
|
||||
|
||||
auto output = torch::zeros({1}, context.options());
|
||||
|
||||
int shared_mem_size = (dim + 1 + num_negatives) * sizeof(float);
|
||||
|
||||
info_nce_kernel<<<batch_size, 256, shared_mem_size>>>(
|
||||
context_c.data_ptr<float>(),
|
||||
positive_c.data_ptr<float>(),
|
||||
negatives_c.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
batch_size,
|
||||
dim,
|
||||
num_negatives
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
cpp_source = """
|
||||
torch::Tensor info_nce_cuda(torch::Tensor context, torch::Tensor positive, torch::Tensor negatives);
|
||||
"""
|
||||
|
||||
info_nce_module = load_inline(
|
||||
name="info_nce_opt",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["info_nce_cuda"],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
|
||||
def forward(self, context, positive, negatives):
|
||||
return info_nce_module.info_nce_cuda(context, positive, negatives)
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, context: torch.Tensor, positive: torch.Tensor, negatives: torch.Tensor) -> torch.Tensor:
|
||||
pos_score = torch.sum(context * positive, dim=-1)
|
||||
|
||||
neg_scores = torch.matmul(context.unsqueeze(1), negatives.transpose(-2, -1)).squeeze(1)
|
||||
|
||||
scores = torch.cat([pos_score.unsqueeze(-1), neg_scores], dim=-1)
|
||||
|
||||
labels = torch.zeros(scores.shape[0], dtype=torch.long, device=scores.device)
|
||||
|
||||
loss = torch.nn.functional.cross_entropy(scores, labels)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 128
|
||||
num_negatives = 64
|
||||
|
||||
|
||||
def get_inputs():
|
||||
context = torch.randn(batch_size, dim)
|
||||
positive = torch.randn(batch_size, dim)
|
||||
negatives = torch.randn(batch_size, num_negatives, dim)
|
||||
return [context, positive, negatives]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
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.
|
||||
Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline
|
||||
|
||||
InfoNCE loss computation (contrastive predictive coding)
|
||||
|
||||
Warp-level dot product reduction using __shfl_down_sync
|
||||
|
||||
Shared memory caching for context vectors and scores
|
||||
|
||||
Numerically stable softmax with max subtraction
|
||||
|
||||
Per-batch parallel processing (one CUDA block per sample)
|
||||
|
||||
Atomic addition (atomicAdd) for loss accumulation
|
||||
|
||||
Log-sum-exp trick for numerical stability
|
||||
|
||||
Contiguous tensor handling for memory coalescing
|
||||
|
||||
Dynamic shared memory allocation for context and scores
|
||||
|
||||
Support for variable number of negatives per positive sample
|
||||
|
||||
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, context: torch.Tensor, positive: torch.Tensor, negatives: torch.Tensor) -> torch.Tensor:
|
||||
pos_score = torch.sum(context * positive, dim=-1)
|
||||
|
||||
neg_scores = torch.matmul(context.unsqueeze(1), negatives.transpose(-2, -1)).squeeze(1)
|
||||
|
||||
scores = torch.cat([pos_score.unsqueeze(-1), neg_scores], dim=-1)
|
||||
|
||||
labels = torch.zeros(scores.shape[0], dtype=torch.long, device=scores.device)
|
||||
|
||||
loss = torch.nn.functional.cross_entropy(scores, labels)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
batch_size = 16
|
||||
dim = 128
|
||||
num_negatives = 64
|
||||
|
||||
|
||||
def get_inputs():
|
||||
context = torch.randn(batch_size, dim)
|
||||
positive = torch.randn(batch_size, dim)
|
||||
negatives = torch.randn(batch_size, num_negatives, dim)
|
||||
return [context, positive, negatives]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from ContrastivePredictiveCodingLoss_torch import Model, get_inputs, get_init_inputs
|
||||
from ContrastivePredictiveCodingLoss_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