oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
//! Running metrics over completed training steps.

use crate::{Matrix, Result, ml::matrix::training_accumulate};

use super::{TrainingCallbackContext, TrainingSnapshot};

/// Stateful metric updated once after each completed step.
///
/// Snapshot-only loss-style metrics implement the four legacy methods.
/// Prediction metrics need batch tensors the snapshot does not carry: they
/// instead observe batches inside the step's record closure
/// ([`AccuracyObserver::observe`]) and commit their epoch result to the shared
/// history bus through [`TrainingMetric::commit_epoch`]. New code should not
/// add snapshot-only metrics; the snapshot path exists for scalars the
/// lifecycle itself produces.
pub trait TrainingMetric {
	fn name(&self) -> &str;
	fn reset(&mut self);
	fn update_step(&mut self, state: TrainingSnapshot);
	fn result(&self) -> f64;

	/// Commit the completed epoch's result to the shared history bus.
	///
	/// The lifecycle invokes this at the epoch boundary after its own
	/// training-loss commit and before any epoch-end callback fires, so
	/// training metrics land in the bus before validation results.
	/// Snapshot-only legacy metrics use the default no-op.
	fn commit_epoch(&mut self, _context: &mut TrainingCallbackContext<'_>) -> Result<()> {
		Ok(())
	}

	/// Observe one batch's prediction and target inside a managed fit.
	///
	/// The managed classification route supplies both automatically before
	/// the step completes, so registered prediction metrics are fed without
	/// user wiring. Custom-step lifecycles use the metric's observer handle
	/// inside the record closure instead. Snapshot-only metrics use the
	/// default no-op.
	fn observe_batch(&mut self, _prediction: &Matrix, _target: &Matrix) -> Result<()> {
		Ok(())
	}
}

/// Device-resident training accuracy for classification steps.
///
/// The metric owns a persistent accumulator: each [`AccuracyObserver::observe`]
/// call inside the step's record closure records the correctness count, its
/// cast, and its accumulation — operations that capture into the training
/// program and execute on every replay, so no per-step accuracy readback
/// exists. The single observation is one readback per epoch boundary inside
/// `commit_epoch`. Epoch isolation is exact cumulative differencing of both
/// the device correct-count and the lifecycle's exact sample accounting;
/// integer counts in F32 are exact far beyond any training run (2^24
/// samples), so the counter never resets.
pub struct AccuracyMetric {
	name: String,
	accumulator: Matrix,
	cursor: Matrix,
	previous_correct: u64,
	previous_samples: u64,
	last: f64,
}

impl AccuracyMetric {
	/// Allocate the persistent device state for one training run.
	///
	/// The buffers belong to the run, never the model registry, and never
	/// enter checkpoints. Host mutation is forbidden while a captured program
	/// borrows them, matching the mutable-output-slot rules.
	///
	/// # Errors
	///
	/// Returns device allocation errors from the owning runtime.
	pub fn new(name: impl Into<String>) -> Result<Self> {
		Self::new_with_runtime(&crate::Runtime::current()?, name)
	}

	/// Allocate the persistent device state on an explicit runtime.
	///
	/// The runtime must own the training run's matrices; accumulation
	/// validates runtime ownership on every observation.
	///
	/// # Errors
	///
	/// Returns device allocation errors from `runtime`.
	pub fn new_with_runtime(runtime: &crate::Runtime, name: impl Into<String>) -> Result<Self> {
		Ok(Self {
			name: name.into(),
			accumulator: Matrix::new_from_f32_on(runtime, [1], &[0.0])?,
			cursor: Matrix::new_from_slice_on(runtime, [2], &[0_u32, 0])?,
			previous_correct: 0,
			previous_samples: 0,
			last: f64::NAN,
		})
	}

	/// Return the recording handle for the step's record closure.
	///
	/// The lifecycle holds the metric mutably once registered, so observation
	/// flows through this cloneable handle: it shares the device state but
	/// borrows nothing, and the record closure may own it for the whole run.
	pub fn observer(&self) -> AccuracyObserver {
		AccuracyObserver {
			accumulator: self.accumulator.clone(),
			cursor: self.cursor.clone(),
		}
	}
}

/// Cloneable recording handle for one [`AccuracyMetric`].
///
/// Call [`AccuracyObserver::observe`] exactly once per step inside the record
/// closure; in the captured plane the operations record once and execute on
/// every replay, so no per-step accuracy readback exists.
#[derive(Clone)]
pub struct AccuracyObserver {
	accumulator: Matrix,
	cursor: Matrix,
}

impl AccuracyObserver {
	/// Record the batch's correctness count into the device accumulator.
	///
	/// # Errors
	///
	/// Returns shape, dtype, and runtime-ownership errors from the counting,
	/// cast, and accumulation operations.
	pub fn observe(&self, logits: &Matrix, targets: &Matrix) -> Result<()> {
		let correct = logits.categorical_accuracy_count(targets)?;
		let correct_f32 = correct.cast_i32_f32()?;
		training_accumulate(&self.accumulator, &correct_f32, &self.cursor, 1.0)
	}
}

impl TrainingMetric for AccuracyMetric {
	fn name(&self) -> &str {
		&self.name
	}

	fn reset(&mut self) {
		// The lifecycle resets metrics at every epoch begin. The cumulative
		// baselines mirror device state that never resets — integer-exact
		// differencing is this metric's epoch isolation — so only the
		// observed-result cache clears here.
		self.last = f64::NAN;
	}

	fn update_step(&mut self, _state: TrainingSnapshot) {}

	fn result(&self) -> f64 {
		self.last
	}

	fn observe_batch(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
		self.observer().observe(prediction, target)
	}

	fn commit_epoch(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<()> {
		let cumulative = self.accumulator.read_f32()?[0] as u64;
		let correct = cumulative - self.previous_correct;
		self.previous_correct = cumulative;
		let total_samples = context.snapshot().total_samples();
		let samples = total_samples - self.previous_samples;
		self.previous_samples = total_samples;
		self.last = if samples == 0 {
			f64::NAN
		} else {
			correct as f64 / samples as f64
		};
		context.commit_metric("train", &self.name.clone(), self.last);
		Ok(())
	}
}

/// Aggregation policy for [`LossMetric`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LossAggregation {
	#[default]
	Mean,
	Last,
}

/// Running completed-step loss metric.
pub struct LossMetric {
	name: String,
	aggregation: LossAggregation,
	sum: f64,
	last: f64,
	count: u64,
}

impl LossMetric {
	pub fn new(name: impl Into<String>, aggregation: LossAggregation) -> Self {
		Self {
			name: name.into(),
			aggregation,
			sum: 0.0,
			last: 0.0,
			count: 0,
		}
	}

	pub const fn count(&self) -> u64 {
		self.count
	}

	pub fn mean(&self) -> f64 {
		if self.count == 0 {
			0.0
		} else {
			self.sum / self.count as f64
		}
	}

	pub fn last(&self) -> f64 {
		if self.count == 0 { 0.0 } else { self.last }
	}
}

impl Default for LossMetric {
	fn default() -> Self {
		Self::new("loss", LossAggregation::Mean)
	}
}

impl TrainingMetric for LossMetric {
	fn name(&self) -> &str {
		&self.name
	}

	fn reset(&mut self) {
		self.sum = 0.0;
		self.last = 0.0;
		self.count = 0;
	}

	fn update_step(&mut self, state: TrainingSnapshot) {
		if let Some(loss) = state.last_loss() {
			self.sum += f64::from(loss);
			self.last = f64::from(loss);
			self.count = self.count.saturating_add(1);
		}
	}

	fn result(&self) -> f64 {
		match self.aggregation {
			LossAggregation::Mean => self.mean(),
			LossAggregation::Last => self.last(),
		}
	}
}