use burn_core as burn;
use burn::config::Config;
use burn::module::{Content, DisplaySettings, Module, ModuleDisplay};
use burn::tensor::Tensor;
use super::Reduction;
#[derive(Config, Debug)]
pub struct HingeEmbeddingLossConfig {
#[config(default = 1.0)]
pub margin: f64,
}
impl HingeEmbeddingLossConfig {
pub fn init(&self) -> HingeEmbeddingLoss {
HingeEmbeddingLoss {
margin: self.margin,
}
}
}
#[derive(Module, Debug)]
#[module(custom_display)]
pub struct HingeEmbeddingLoss {
pub margin: f64,
}
impl ModuleDisplay for HingeEmbeddingLoss {
fn custom_settings(&self) -> Option<DisplaySettings> {
DisplaySettings::new()
.with_new_line_after_attribute(false)
.optional()
}
fn custom_content(&self, content: Content) -> Option<Content> {
content.add("margin", &self.margin).optional()
}
}
impl HingeEmbeddingLoss {
pub fn forward<const D: usize>(
&self,
input: Tensor<D>,
target: Tensor<D>,
reduction: Reduction,
) -> Tensor<1> {
let loss = self.forward_no_reduction(input, target);
match reduction {
Reduction::Mean | Reduction::Auto => loss.mean(),
Reduction::Sum => loss.sum(),
other => panic!("{other:?} reduction is not supported"),
}
}
pub fn forward_no_reduction<const D: usize>(
&self,
input: Tensor<D>,
target: Tensor<D>,
) -> Tensor<D> {
let negative = input.clone().neg().add_scalar(self.margin).clamp_min(0.0);
let positive_mask = target.equal_scalar(1);
negative.mask_where(positive_mask, input)
}
}
#[cfg(test)]
mod tests {
use super::*;
use burn::tensor::TensorData;
use burn::tensor::Tolerance;
type FT = f32;
#[test]
fn test_hinge_embedding_loss() {
let device = Default::default();
let input = Tensor::<1>::from_data(TensorData::from([0.5, 2.0, 1.5]), &device);
let target = Tensor::<1>::from_data(TensorData::from([1.0, -1.0, -1.0]), &device);
let loss = HingeEmbeddingLossConfig::new().init();
let no_reduction = loss.forward_no_reduction(input.clone(), target.clone());
let mean = loss.forward(input.clone(), target.clone(), Reduction::Mean);
let sum = loss.forward(input, target, Reduction::Sum);
let expected = TensorData::from([0.5, 0.0, 0.0]);
no_reduction
.into_data()
.assert_approx_eq::<FT>(&expected, Tolerance::default());
mean.into_data()
.assert_approx_eq::<FT>(&TensorData::from([0.166_667]), Tolerance::default());
sum.into_data()
.assert_approx_eq::<FT>(&TensorData::from([0.5]), Tolerance::default());
}
#[test]
fn display() {
let config = HingeEmbeddingLossConfig::new().with_margin(0.5);
let loss = config.init();
assert_eq!(alloc::format!("{loss}"), "HingeEmbeddingLoss {margin: 0.5}");
}
}