Skip to main content

oa/ml/metric/
perplexity.rs

1//! Token-weighted perplexity as a derivation over mergeable weighted NLL.
2
3use super::weighted::WeightedMean;
4use crate::{Matrix, Result, ml::metric::scalar_loss};
5
6/// Additive token-NLL moments behind perplexity.
7///
8/// Perplexity is `exp(sum(nll × tokens) / sum(tokens))` with the exponential
9/// applied only at observation time. Batches contribute their token-weighted
10/// mean negative log-likelihood — exactly what `cross_entropy_masked` returns
11/// when its `valid_count` is the token denominator — so partitioned language
12/// evaluation merges exactly. The contract forbids the mean of per-batch
13/// perplexities, which is not the corpus perplexity. Empty denominators
14/// report NaN.
15#[derive(Clone, Copy, Debug, Default, PartialEq)]
16pub struct Perplexity {
17	nll: WeightedMean,
18}
19
20impl Perplexity {
21	/// Construct empty state.
22	#[inline]
23	#[must_use]
24	pub fn new() -> Self {
25		Self::default()
26	}
27
28	/// Add one batch's token-weighted mean NLL with its valid token count.
29	///
30	/// The accumulated numerator is `mean_nll × token_count`, so callers may
31	/// pass the mean their loss reports rather than re-summing per-token
32	/// values.
33	///
34	/// # Errors
35	///
36	/// Returns an error when the mean is non-finite.
37	pub fn update(&mut self, mean_nll: f64, token_count: u64) -> Result<()> {
38		if !mean_nll.is_finite() {
39			return Err(crate::Error::invalid_argument(
40				"perplexity requires a finite mean negative log-likelihood",
41			));
42		}
43		self
44			.nll
45			.update(mean_nll * token_count as f64, token_count as f64)
46	}
47
48	/// Read back one batch's masked-NLL scalar and accumulate it.
49	///
50	/// `mean_nll` must be the device scalar `cross_entropy_masked` produces
51	/// for the same tokens, keeping observation on the once-per-batch
52	/// evaluation plane.
53	///
54	/// # Errors
55	///
56	/// Returns an error when the scalar readback fails.
57	pub fn update_device(&mut self, mean_nll: &Matrix, token_count: u64) -> Result<()> {
58		self.update(f64::from(scalar_loss(mean_nll)?), token_count)
59	}
60
61	/// Merge another instance's accumulated moments.
62	pub fn merge(&mut self, other: &Self) {
63		self.nll.merge(&other.nll);
64	}
65
66	/// Corpus perplexity, or NaN when empty.
67	#[must_use]
68	pub fn result(&self) -> f64 {
69		self.nll.result().exp()
70	}
71
72	/// Token-weighted mean NLL behind the perplexity, or NaN when empty.
73	#[must_use]
74	pub fn mean_nll(&self) -> f64 {
75		self.nll.result()
76	}
77
78	/// Return the accumulated token denominator.
79	#[must_use]
80	pub const fn tokens(&self) -> f64 {
81		self.nll.weight()
82	}
83
84	/// Drop all accumulated moments.
85	pub fn reset(&mut self) {
86		*self = Self::default();
87	}
88}