use crate::matrix;
use crate::{Error, Matrix, Result};
use super::common::validate_pointwise_loss_inputs;
pub fn kl_div(input: &Matrix, target: &Matrix) -> Result<Matrix> {
validate_pointwise_loss_inputs(input, target, "kl_div")?;
let log_target = matrix::log(&matrix::clamp_min(target, 1e-12)?)?;
let divergence = matrix::sub(
&matrix::mul(target, &log_target)?,
&matrix::mul(target, input)?,
)?;
matrix::mean(&divergence, -1)?.reshape([])
}
pub fn nll(input: &Matrix, target: &Matrix) -> Result<Matrix> {
let selected = matrix::gather_last_dim(input, target)?;
matrix::neg(&matrix::mean(&selected, -1)?)?.reshape([])
}
pub fn gaussian_nll(
prediction: &Matrix,
target: &Matrix,
variance: &Matrix,
eps: f32,
full: bool,
) -> Result<Matrix> {
let operation = "gaussian_nll";
validate_pointwise_loss_inputs(prediction, target, operation)?;
validate_pointwise_loss_inputs(prediction, variance, operation)?;
if !eps.is_finite() || eps <= 0.0 {
return Err(Error::invalid_argument(format!(
"{operation} eps must be a positive finite scalar"
)));
}
let clamped = matrix::clamp_min(variance, eps)?;
let residual = matrix::sub(prediction, target)?;
let term = matrix::scale(
&matrix::add(
&matrix::log(&clamped)?,
&matrix::div(&matrix::mul(&residual, &residual)?, &clamped)?,
)?,
0.5,
)?;
let term = if full {
matrix::add_scalar(&term, 0.5 * std::f32::consts::TAU.ln())?
} else {
term
};
matrix::mean(&term, -1)?.reshape([])
}
pub fn poisson_nll(input: &Matrix, target: &Matrix) -> Result<Matrix> {
validate_pointwise_loss_inputs(input, target, "poisson_nll")?;
let term = matrix::sub(&matrix::exp(input)?, &matrix::mul(target, input)?)?;
matrix::mean(&term, -1)?.reshape([])
}
pub fn multi_label_soft_margin(
input: &Matrix,
target: &Matrix,
weight: Option<&Matrix>,
) -> Result<Matrix> {
let operation = "multi_label_soft_margin";
validate_pointwise_loss_inputs(input, target, operation)?;
if input.shape().len() != 2 {
return Err(Error::invalid_argument(format!(
"{operation} requires rank-two [N, C] inputs"
)));
}
let mut term = matrix::add(
&matrix::clamp_min(input, 0.0)?,
&matrix::add(
&matrix::neg(&matrix::mul(input, target)?)?,
&matrix::log(&matrix::add_scalar(
&matrix::exp(&matrix::neg(&matrix::abs(input)?)?)?,
1.0,
)?)?,
)?,
)?;
if let Some(weight) = weight {
if !weight.runtime().same_as(input.runtime()) {
return Err(Error::invalid_argument(format!(
"{operation} weight must belong to the same runtime"
)));
}
term = matrix::mul(&term, weight)?;
}
matrix::mean(&matrix::mean(&term, 1)?, -1)?.reshape([])
}