oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Token-weighted perplexity as a derivation over mergeable weighted NLL.

use super::weighted::WeightedMean;
use crate::{Matrix, Result, ml::metric::scalar_loss};

/// Additive token-NLL moments behind perplexity.
///
/// Perplexity is `exp(sum(nll × tokens) / sum(tokens))` with the exponential
/// applied only at observation time. Batches contribute their token-weighted
/// mean negative log-likelihood — exactly what `cross_entropy_masked` returns
/// when its `valid_count` is the token denominator — so partitioned language
/// evaluation merges exactly. The contract forbids the mean of per-batch
/// perplexities, which is not the corpus perplexity. Empty denominators
/// report NaN.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Perplexity {
	nll: WeightedMean,
}

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

	/// Add one batch's token-weighted mean NLL with its valid token count.
	///
	/// The accumulated numerator is `mean_nll × token_count`, so callers may
	/// pass the mean their loss reports rather than re-summing per-token
	/// values.
	///
	/// # Errors
	///
	/// Returns an error when the mean is non-finite.
	pub fn update(&mut self, mean_nll: f64, token_count: u64) -> Result<()> {
		if !mean_nll.is_finite() {
			return Err(crate::Error::invalid_argument(
				"perplexity requires a finite mean negative log-likelihood",
			));
		}
		self
			.nll
			.update(mean_nll * token_count as f64, token_count as f64)
	}

	/// Read back one batch's masked-NLL scalar and accumulate it.
	///
	/// `mean_nll` must be the device scalar `cross_entropy_masked` produces
	/// for the same tokens, keeping observation on the once-per-batch
	/// evaluation plane.
	///
	/// # Errors
	///
	/// Returns an error when the scalar readback fails.
	pub fn update_device(&mut self, mean_nll: &Matrix, token_count: u64) -> Result<()> {
		self.update(f64::from(scalar_loss(mean_nll)?), token_count)
	}

	/// Merge another instance's accumulated moments.
	pub fn merge(&mut self, other: &Self) {
		self.nll.merge(&other.nll);
	}

	/// Corpus perplexity, or NaN when empty.
	#[must_use]
	pub fn result(&self) -> f64 {
		self.nll.result().exp()
	}

	/// Token-weighted mean NLL behind the perplexity, or NaN when empty.
	#[must_use]
	pub fn mean_nll(&self) -> f64 {
		self.nll.result()
	}

	/// Return the accumulated token denominator.
	#[must_use]
	pub const fn tokens(&self) -> f64 {
		self.nll.weight()
	}

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