mod compute;
#[cfg(test)]
mod tests;
use crate::error::{BarracudaError, Result};
use crate::tensor::Tensor;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TripletParams {
pub batch_size: u32,
pub embedding_dim: u32,
pub margin: f32,
pub distance_type: u32,
}
#[derive(Copy, Clone, Debug)]
pub enum DistanceMetric {
L2,
Cosine,
}
pub struct TripletLoss {
anchors: Tensor,
positives: Tensor,
negatives: Tensor,
margin: f32,
distance_metric: DistanceMetric,
}
impl TripletLoss {
pub fn new(
anchors: Tensor,
positives: Tensor,
negatives: Tensor,
margin: f32,
distance_metric: DistanceMetric,
) -> Result<Self> {
if anchors.shape() != positives.shape() {
return Err(BarracudaError::shape_mismatch(
anchors.shape().to_vec(),
positives.shape().to_vec(),
));
}
if anchors.shape() != negatives.shape() {
return Err(BarracudaError::shape_mismatch(
anchors.shape().to_vec(),
negatives.shape().to_vec(),
));
}
if anchors.shape().len() != 2 {
return Err(BarracudaError::invalid_op(
"TripletLoss",
format!(
"Expected 2D tensors [batch, embedding_dim], got shape {:?}",
anchors.shape()
),
));
}
if margin < 0.0 {
return Err(BarracudaError::invalid_op(
"TripletLoss",
format!("margin must be non-negative, got {margin}"),
));
}
Ok(Self {
anchors,
positives,
negatives,
margin,
distance_metric,
})
}
pub(super) fn shader() -> &'static str {
static SHADER: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
include_str!("../../shaders/loss/triplet_loss_f64.wgsl").to_string()
});
&SHADER
}
pub(super) fn anchors(&self) -> &Tensor {
&self.anchors
}
pub(super) fn positives(&self) -> &Tensor {
&self.positives
}
pub(super) fn negatives(&self) -> &Tensor {
&self.negatives
}
pub(super) fn margin(&self) -> f32 {
self.margin
}
pub(super) fn distance_metric(&self) -> DistanceMetric {
self.distance_metric
}
}
impl Tensor {
pub fn triplet_loss(self, positives: &Self, negatives: &Self, margin: f32) -> Result<Self> {
TripletLoss::new(
self,
positives.clone(),
negatives.clone(),
margin,
DistanceMetric::L2,
)?
.execute()
}
pub fn triplet_loss_cosine(
self,
positives: &Self,
negatives: &Self,
margin: f32,
) -> Result<Self> {
TripletLoss::new(
self,
positives.clone(),
negatives.clone(),
margin,
DistanceMetric::Cosine,
)?
.execute()
}
}