use crate::{DType, Error, Matrix, Result, matrix};
use super::common::validate_pointwise_loss_inputs;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LossReduction {
None,
Sum,
#[default]
Mean,
}
fn validate_same_shape_weight(
reference: &Matrix,
weight: &Matrix,
label: &str,
operation: &str,
) -> Result<()> {
if weight.dtype() != DType::F32 {
return Err(Error::invalid_argument(format!(
"{operation} {label} must be F32; found {}",
weight.dtype().token()
)));
}
if !weight.runtime().same_as(reference.runtime()) {
return Err(Error::invalid_argument(format!(
"{operation} {label} must belong to the same runtime"
)));
}
if weight.shape() != reference.shape() {
return Err(Error::invalid_argument(format!(
"{operation} {label} shape {:?} must match loss shape {:?}",
weight.shape(),
reference.shape()
)));
}
Ok(())
}
pub fn reduce_loss(
per_item: &Matrix,
sample_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
const OPERATION: &str = "reduce_loss";
if per_item.dtype() != DType::F32 || per_item.num_elements() == 0 {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires a nonempty F32 loss matrix; found {} {:?}",
per_item.dtype().token(),
per_item.shape()
)));
}
match sample_weight {
None => match reduction {
LossReduction::None => Ok(per_item.clone()),
LossReduction::Sum => matrix::sum(per_item, -1)?.reshape([]),
LossReduction::Mean => matrix::mean(per_item, -1)?.reshape([]),
},
Some(weight) => {
validate_same_shape_weight(per_item, weight, "sample_weight", OPERATION)?;
let weighted = matrix::mul(per_item, weight)?;
match reduction {
LossReduction::None => Ok(weighted),
LossReduction::Sum => matrix::sum(&weighted, -1)?.reshape([]),
LossReduction::Mean => {
let numerator = matrix::sum(&weighted, -1)?;
let denominator = matrix::sum(weight, -1)?;
matrix::div(&numerator, &denominator)?.reshape([])
}
}
}
}
}
pub fn mse_with_options(
prediction: &Matrix,
target: &Matrix,
sample_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
validate_pointwise_loss_inputs(prediction, target, "mse_with_options")?;
let diff = matrix::sub(prediction, target)?;
let per_item = matrix::mul(&diff, &diff)?;
reduce_loss(&per_item, sample_weight, reduction)
}
pub fn l1_with_options(
prediction: &Matrix,
target: &Matrix,
sample_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
validate_pointwise_loss_inputs(prediction, target, "l1_with_options")?;
let per_item = matrix::abs(&matrix::sub(prediction, target)?)?;
reduce_loss(&per_item, sample_weight, reduction)
}
pub fn smooth_l1_with_options(
prediction: &Matrix,
target: &Matrix,
beta: f32,
sample_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
const OPERATION: &str = "smooth_l1_with_options";
validate_pointwise_loss_inputs(prediction, target, OPERATION)?;
if !beta.is_finite() || beta <= 0.0 {
return Err(Error::invalid_argument(format!(
"{OPERATION} beta must be positive and finite; found {beta}"
)));
}
let abs_diff = matrix::abs(&matrix::sub(prediction, target)?)?;
let quad_part = matrix::clamp_max(&abs_diff, beta)?;
let quadratic = matrix::scale(&matrix::mul(&quad_part, &quad_part)?, 0.5 / beta)?;
let linear = matrix::sub(&abs_diff, &quad_part)?;
let per_item = matrix::add(&quadratic, &linear)?;
reduce_loss(&per_item, sample_weight, reduction)
}
pub fn bce_with_options(
prediction: &Matrix,
target: &Matrix,
sample_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
const CLAMP_MIN: f32 = 1.0e-7;
const CLAMP_MAX: f32 = 1.0 - 1.0e-7;
validate_pointwise_loss_inputs(prediction, target, "bce_with_options")?;
let clamped = matrix::clamp_max(&matrix::clamp_min(prediction, CLAMP_MIN)?, CLAMP_MAX)?;
let one_minus_p = matrix::add_scalar(&matrix::neg(&clamped)?, 1.0)?;
let one_minus_t = matrix::add_scalar(&matrix::neg(target)?, 1.0)?;
let pos = matrix::mul(target, &matrix::log(&clamped)?)?;
let neg = matrix::mul(&one_minus_t, &matrix::log(&one_minus_p)?)?;
let per_item = matrix::neg(&matrix::add(&pos, &neg)?)?;
reduce_loss(&per_item, sample_weight, reduction)
}
pub fn bce_with_logits(logits: &Matrix, target: &Matrix) -> Result<Matrix> {
bce_with_logits_with_options(logits, target, None, None, LossReduction::Mean)
}
pub fn bce_with_logits_with_options(
logits: &Matrix,
target: &Matrix,
sample_weight: Option<&Matrix>,
pos_weight: Option<&Matrix>,
reduction: LossReduction,
) -> Result<Matrix> {
const OPERATION: &str = "bce_with_logits_with_options";
validate_pointwise_loss_inputs(logits, target, OPERATION)?;
let log1p_exp_neg_abs = matrix::log(&matrix::add_scalar(
&matrix::exp(&matrix::neg(&matrix::abs(logits)?)?)?,
1.0,
)?)?;
let per_item = match pos_weight {
None => matrix::add(
&matrix::sub(
&matrix::clamp_min(logits, 0.0)?,
&matrix::mul(logits, target)?,
)?,
&log1p_exp_neg_abs,
)?,
Some(pw) => {
if pw.dtype() != DType::F32 || pw.num_elements() == 0 {
return Err(Error::invalid_argument(format!(
"{OPERATION} pos_weight must be nonempty F32; found {} {:?}",
pw.dtype().token(),
pw.shape()
)));
}
if !pw.runtime().same_as(logits.runtime()) {
return Err(Error::invalid_argument(format!(
"{OPERATION} pos_weight must belong to the same runtime"
)));
}
let one_minus_y = matrix::add_scalar(&matrix::neg(target)?, 1.0)?;
let log_weight =
matrix::add_scalar(&matrix::mul(&matrix::sub_scalar(pw, 1.0)?, target)?, 1.0)?;
let max_neg_x = matrix::clamp_min(&matrix::neg(logits)?, 0.0)?;
let stable_log = matrix::add(&log1p_exp_neg_abs, &max_neg_x)?;
matrix::add(
&matrix::mul(&one_minus_y, logits)?,
&matrix::mul(&log_weight, &stable_log)?,
)?
}
};
reduce_loss(&per_item, sample_weight, reduction)
}
pub fn cross_entropy_with_options(
logits: &Matrix,
targets: &Matrix,
class_weight: Option<&Matrix>,
sample_weight: Option<&Matrix>,
ignore_index: Option<i32>,
reduction: LossReduction,
) -> Result<Matrix> {
const OPERATION: &str = "cross_entropy_with_options";
let &[rows, classes] = logits.shape() else {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires rank-two [N, C] logits; found {:?}",
logits.shape()
)));
};
if rows == 0 || classes == 0 || logits.dtype() != DType::F32 {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires nonempty F32 [N, C] logits; found {} {:?}",
logits.dtype().token(),
logits.shape()
)));
}
if targets.shape() != [rows]
|| !matches!(targets.dtype(), DType::U8 | DType::U32 | DType::I32)
|| !logits.runtime().same_as(targets.runtime())
{
return Err(Error::invalid_argument(format!(
"{OPERATION} requires same-runtime [N] U8/U32/I32 targets; found {} {:?}",
targets.dtype().token(),
targets.shape()
)));
}
if let Some(cw) = class_weight
&& (cw.dtype() != DType::F32
|| cw.shape() != [classes]
|| !cw.runtime().same_as(logits.runtime()))
{
return Err(Error::invalid_argument(format!(
"{OPERATION} class_weight must be same-runtime F32 [{classes}]; found {} {:?}",
cw.dtype().token(),
cw.shape()
)));
}
if let Some(sw) = sample_weight
&& (sw.dtype() != DType::F32 || sw.shape() != [rows] || !sw.runtime().same_as(logits.runtime()))
{
return Err(Error::invalid_argument(format!(
"{OPERATION} sample_weight must be same-runtime F32 [{rows}]; found {} {:?}",
sw.dtype().token(),
sw.shape()
)));
}
let runtime = logits.runtime();
let (safe_indices_2d, safe_indices_1d, valid_mask): (Matrix, Matrix, Option<Matrix>) =
if targets.dtype() == DType::I32 && ignore_index.is_none() {
(targets.reshape([rows, 1])?, targets.clone(), None)
} else {
let raw: Vec<i64> = match targets.dtype() {
DType::U8 => targets.read::<u8>()?.into_iter().map(i64::from).collect(),
DType::U32 => targets.read::<u32>()?.into_iter().map(i64::from).collect(),
DType::I32 => targets.read::<i32>()?.into_iter().map(i64::from).collect(),
_ => unreachable!("target dtype validated above"),
};
let classes_i64 = classes as i64;
let ignore_i64 = ignore_index.map(i64::from);
let mut safe = Vec::with_capacity(rows);
let mut mask = Vec::with_capacity(rows);
let mut any_ignored = false;
for (row, label) in raw.into_iter().enumerate() {
if ignore_i64 == Some(label) {
safe.push(0_i32);
mask.push(0.0_f32);
any_ignored = true;
} else if (0..classes_i64).contains(&label) {
safe.push(label as i32);
mask.push(1.0_f32);
} else {
return Err(Error::invalid_argument(format!(
"{OPERATION} target {label} at row {row} is outside 0..{classes}"
)));
}
}
let idx_1d = Matrix::new_from_slice_handle(runtime, vec![rows], &safe)?;
let idx_2d = idx_1d.reshape([rows, 1])?;
let mask_mat = if any_ignored {
Some(Matrix::new_from_slice_handle(runtime, vec![rows], &mask)?)
} else {
None
};
(idx_2d, idx_1d, mask_mat)
};
let log_probs = matrix::log_softmax(logits, 1)?;
let nll =
matrix::neg(&matrix::gather_last_dim(&log_probs, &safe_indices_2d)?)?.reshape([rows])?;
let mut effective_weight: Option<Matrix> = None;
if let Some(cw) = class_weight {
let gathered = matrix::gather(&cw.reshape([classes, 1])?, &safe_indices_1d)?.reshape([rows])?;
effective_weight = Some(gathered);
}
if let Some(mask) = valid_mask {
effective_weight = Some(match effective_weight {
Some(prev) => matrix::mul(&prev, &mask)?,
None => mask,
});
}
if let Some(sw) = sample_weight {
effective_weight = Some(match effective_weight {
Some(prev) => matrix::mul(&prev, sw)?,
None => sw.clone(),
});
}
reduce_loss(&nll, effective_weight.as_ref(), reduction)
}
pub fn combine_losses(terms: &[(&Matrix, f32)], normalize: bool) -> Result<Matrix> {
const OPERATION: &str = "combine_losses";
if terms.is_empty() {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires at least one (loss, weight) term"
)));
}
let runtime = terms[0].0.runtime();
let mut total_weight = 0.0_f64;
for (index, (loss, weight)) in terms.iter().enumerate() {
if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
return Err(Error::invalid_argument(format!(
"{OPERATION} term {index} must be an F32 scalar; found {} {:?}",
loss.dtype().token(),
loss.shape()
)));
}
if !loss.runtime().same_as(runtime) {
return Err(Error::invalid_argument(format!(
"{OPERATION} term {index} must belong to the same runtime"
)));
}
if !weight.is_finite() || *weight < 0.0 {
return Err(Error::invalid_argument(format!(
"{OPERATION} term {index} weight must be finite and non-negative; found {weight}"
)));
}
total_weight += f64::from(*weight);
}
if normalize && total_weight <= 0.0 {
return Err(Error::invalid_argument(format!(
"{OPERATION} with normalize=true requires a positive weight sum"
)));
}
let denom = if normalize { total_weight } else { 1.0 };
let mut acc: Option<Matrix> = None;
for (loss, weight) in terms {
let factor = (f64::from(*weight) / denom) as f32;
let scaled = matrix::scale(loss, factor)?;
acc = Some(match acc {
Some(prev) => matrix::add(&prev, &scaled)?,
None => scaled,
});
}
acc.ok_or_else(|| Error::internal("combine_losses nonempty guard failed"))
}