oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
//! Mergeable absolute and squared error sums for regression metrics.

use crate::{DType, Error, Matrix, Result, matrix};

/// Additive error moments behind MAE and RMSE.
///
/// One batch observation computes both numerators on the device and reads
/// them back together — the same once-per-evaluation-batch host boundary the
/// loss scalar uses. MAE is `sum|e| / samples`; RMSE squares the mean only at
/// observation time, so partitioned merges stay exact. Empty denominators
/// report NaN.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RegressionErrors {
	absolute_sum: f64,
	squared_sum: f64,
	samples: u64,
}

impl RegressionErrors {
	/// Construct empty state.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}

	/// Add host-observed error sums for `samples` predictions.
	pub fn update(&mut self, absolute_sum: f64, squared_sum: f64, samples: u64) {
		self.absolute_sum += absolute_sum;
		self.squared_sum += squared_sum;
		self.samples = self.samples.saturating_add(samples);
	}

	/// Reduce one batch's errors on the device and accumulate them.
	///
	/// Predictions and targets must share shape, FP32 storage, and Runtime
	/// ownership. The absolute and squared sums cross the host boundary in one
	/// combined readback.
	///
	/// # Errors
	///
	/// Returns an error for mismatched geometry, dtype, or ownership, or when
	/// reduction or readback fails.
	pub fn update_device(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
		if prediction.shape() != target.shape()
			|| prediction.dtype() != DType::F32
			|| target.dtype() != DType::F32
		{
			return Err(Error::invalid_argument(
				"regression metrics require same-shape F32 predictions and targets",
			));
		}
		if !prediction.runtime().same_as(target.runtime()) {
			return Err(Error::invalid_argument(
				"regression metric inputs must belong to the same runtime",
			));
		}
		if prediction.num_elements() == 0 {
			return Err(Error::invalid_argument(
				"regression metrics require nonempty batches",
			));
		}
		let difference = matrix::sub(prediction, target)?;
		let absolute = matrix::sum(&matrix::abs(&difference)?, -1)?;
		let squared = matrix::sum(&matrix::mul(&difference, &difference)?, -1)?;
		let pair = matrix::concat(&[absolute, squared], 0)?.read_f32()?;
		self.update(
			f64::from(pair[0]),
			f64::from(pair[1]),
			prediction.num_elements() as u64,
		);
		Ok(())
	}

	/// Merge another instance's accumulated moments.
	pub fn merge(&mut self, other: &Self) {
		self.absolute_sum += other.absolute_sum;
		self.squared_sum += other.squared_sum;
		self.samples = self.samples.saturating_add(other.samples);
	}

	/// Mean absolute error, or NaN when empty.
	#[must_use]
	pub fn mae(&self) -> f64 {
		if self.samples == 0 {
			f64::NAN
		} else {
			self.absolute_sum / self.samples as f64
		}
	}

	/// Root mean squared error, or NaN when empty.
	///
	/// The square root applies at observation time; merged state keeps exact
	/// squared sums.
	#[must_use]
	pub fn rmse(&self) -> f64 {
		if self.samples == 0 {
			f64::NAN
		} else {
			(self.squared_sum / self.samples as f64).sqrt()
		}
	}

	/// Return the accumulated sample denominator.
	#[must_use]
	pub const fn samples(&self) -> u64 {
		self.samples
	}

	/// Drop all accumulated moments.
	pub fn reset(&mut self) {
		*self = Self::default();
	}
}