finish HistogramLoss #90

This commit is contained in:
uucoco 2025-12-10 19:11:45 +08:00
parent 10eed82956
commit cd30380193
4 changed files with 304 additions and 0 deletions

View File

@ -0,0 +1,96 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, num_bins=10, min_val=0.0, max_val=1.0):
super().__init__()
self.num_bins = num_bins
self.min_val = min_val
self.max_val = max_val
self.step = (max_val - min_val) / num_bins
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor histogramloss_cuda(torch::Tensor pos, torch::Tensor neg, int num_bins, float min_val, float max_val);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void histogram_kernel(
const float* __restrict__ data,
float* __restrict__ hist,
const int n_elements,
const int num_bins,
const float min_val,
const float step)
{
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int stride = blockDim.x * gridDim.x;
for (int i = tid; i < n_elements; i += stride) {
float val = data[i];
for (int b = 0; b < num_bins; ++b) {
float center = min_val + (b + 0.5f) * step;
float diff = fabsf(val - center);
float weight = fmaxf(0.0f, 1.0f - diff / step);
atomicAdd(&hist[b], weight);
}
}
}
torch::Tensor histogramloss_cuda(torch::Tensor pos, torch::Tensor neg, int num_bins, float min_val, float max_val) {
auto pos_c = pos.contiguous();
auto neg_c = neg.contiguous();
auto pos_hist = torch::zeros({num_bins}, pos.options());
auto neg_hist = torch::zeros({num_bins}, neg.options());
float step = (max_val - min_val) / num_bins;
const int threads = 256;
int pos_blocks = min((int)((pos_c.numel() + threads - 1) / threads), 65535);
histogram_kernel<<<pos_blocks, threads>>>(
pos_c.data_ptr<float>(),
pos_hist.data_ptr<float>(),
pos_c.numel(),
num_bins,
min_val,
step
);
int neg_blocks = min((int)((neg_c.numel() + threads - 1) / threads), 65535);
histogram_kernel<<<neg_blocks, threads>>>(
neg_c.data_ptr<float>(),
neg_hist.data_ptr<float>(),
neg_c.numel(),
num_bins,
min_val,
step
);
auto pos_cdf = torch::cumsum(pos_hist, 0);
pos_cdf = pos_cdf / (pos_cdf[num_bins - 1] + 1e-8);
auto neg_pdf = neg_hist / (neg_hist.sum() + 1e-8);
return (neg_pdf * pos_cdf).sum();
}
"""
self.op = load_inline(
name="histogramloss_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["histogramloss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, pos, neg):
return self.op.histogramloss_cuda(pos, neg, self.num_bins, self.min_val, self.max_val)

View File

@ -0,0 +1,51 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, num_bins=10, min_val=0.0, max_val=1.0):
super().__init__()
self.num_bins = num_bins
self.min_val = min_val
self.max_val = max_val
self.step = (max_val - min_val) / num_bins
self.centers = torch.linspace(min_val + self.step / 2, max_val - self.step / 2, num_bins)
def forward(self, pos: torch.Tensor, neg: torch.Tensor) -> torch.Tensor:
delta = self.step
centers = self.centers.to(pos.device)
pos_rep = pos.unsqueeze(1).repeat(1, self.num_bins)
neg_rep = neg.unsqueeze(1).repeat(1, self.num_bins)
centers_rep_pos = centers.unsqueeze(0).repeat(pos.size(0), 1)
centers_rep_neg = centers.unsqueeze(0).repeat(neg.size(0), 1)
pos_hist = torch.clamp(1 - torch.abs(pos_rep - centers_rep_pos) / delta, min=0)
neg_hist = torch.clamp(1 - torch.abs(neg_rep - centers_rep_neg) / delta, min=0)
pos_hist_sum = pos_hist.sum(dim=0)
neg_hist_sum = neg_hist.sum(dim=0)
pos_cdf = torch.cumsum(pos_hist_sum, dim=0)
pos_cdf = pos_cdf / (pos_cdf[-1] + 1e-8)
neg_pdf = neg_hist_sum / (neg_hist_sum.sum() + 1e-8)
loss = (neg_pdf * pos_cdf).sum()
return loss
batch_size = 128
num_features = 512
def get_inputs():
pos = torch.rand(batch_size, dtype=torch.float32)
neg = torch.rand(batch_size, dtype=torch.float32)
return [pos, neg]
def get_init_inputs():
return [10, 0.0, 1.0]

80
S1/uucoco_#90/prompt.txt Normal file
View File

@ -0,0 +1,80 @@
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
Histogram-based loss computation for positive/negative sample distributions
Soft histogram binning with linear interpolation weights
Atomic operations (atomicAdd) for histogram accumulation
Per-bin kernel parallelization with center-based distance calculation
Cumulative distribution function (CDF) computation via torch::cumsum
Probability density function (PDF) normalization
Contiguous tensor handling for input data
Numerical stability with epsilon addition (1e-8)
Dynamic kernel configuration based on element counts
Histogram intersection loss via PDF-CDF product sum
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, num_bins=10, min_val=0.0, max_val=1.0):
super().__init__()
self.num_bins = num_bins
self.min_val = min_val
self.max_val = max_val
self.step = (max_val - min_val) / num_bins
self.centers = torch.linspace(min_val + self.step / 2, max_val - self.step / 2, num_bins)
def forward(self, pos: torch.Tensor, neg: torch.Tensor) -> torch.Tensor:
delta = self.step
centers = self.centers.to(pos.device)
pos_rep = pos.unsqueeze(1).repeat(1, self.num_bins)
neg_rep = neg.unsqueeze(1).repeat(1, self.num_bins)
centers_rep_pos = centers.unsqueeze(0).repeat(pos.size(0), 1)
centers_rep_neg = centers.unsqueeze(0).repeat(neg.size(0), 1)
pos_hist = torch.clamp(1 - torch.abs(pos_rep - centers_rep_pos) / delta, min=0)
neg_hist = torch.clamp(1 - torch.abs(neg_rep - centers_rep_neg) / delta, min=0)
pos_hist_sum = pos_hist.sum(dim=0)
neg_hist_sum = neg_hist.sum(dim=0)
pos_cdf = torch.cumsum(pos_hist_sum, dim=0)
pos_cdf = pos_cdf / (pos_cdf[-1] + 1e-8)
neg_pdf = neg_hist_sum / (neg_hist_sum.sum() + 1e-8)
loss = (neg_pdf * pos_cdf).sum()
return loss
batch_size = 128
num_features = 512
def get_inputs():
pos = torch.rand(batch_size, dtype=torch.float32)
neg = torch.rand(batch_size, dtype=torch.float32)
return [pos, neg]
def get_init_inputs():
return [10, 0.0, 1.0]

77
S1/uucoco_#90/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from HistogramLoss_torch import Model, get_inputs, get_init_inputs
from HistogramLoss_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()