Skip to main content

oa/ml/training/
metric.rs

1//! Running metrics over completed training steps.
2
3use crate::{Matrix, Result, ml::matrix::training_accumulate};
4
5use super::{TrainingCallbackContext, TrainingSnapshot};
6
7/// Stateful metric updated once after each completed step.
8///
9/// Snapshot-only loss-style metrics implement the four legacy methods.
10/// Prediction metrics need batch tensors the snapshot does not carry: they
11/// instead observe batches inside the step's record closure
12/// ([`AccuracyObserver::observe`]) and commit their epoch result to the shared
13/// history bus through [`TrainingMetric::commit_epoch`]. New code should not
14/// add snapshot-only metrics; the snapshot path exists for scalars the
15/// lifecycle itself produces.
16pub trait TrainingMetric {
17	fn name(&self) -> &str;
18	fn reset(&mut self);
19	fn update_step(&mut self, state: TrainingSnapshot);
20	fn result(&self) -> f64;
21
22	/// Commit the completed epoch's result to the shared history bus.
23	///
24	/// The lifecycle invokes this at the epoch boundary after its own
25	/// training-loss commit and before any epoch-end callback fires, so
26	/// training metrics land in the bus before validation results.
27	/// Snapshot-only legacy metrics use the default no-op.
28	fn commit_epoch(&mut self, _context: &mut TrainingCallbackContext<'_>) -> Result<()> {
29		Ok(())
30	}
31
32	/// Observe one batch's prediction and target inside a managed fit.
33	///
34	/// The managed classification route supplies both automatically before
35	/// the step completes, so registered prediction metrics are fed without
36	/// user wiring. Custom-step lifecycles use the metric's observer handle
37	/// inside the record closure instead. Snapshot-only metrics use the
38	/// default no-op.
39	fn observe_batch(&mut self, _prediction: &Matrix, _target: &Matrix) -> Result<()> {
40		Ok(())
41	}
42}
43
44/// Device-resident training accuracy for classification steps.
45///
46/// The metric owns a persistent accumulator: each [`AccuracyObserver::observe`]
47/// call inside the step's record closure records the correctness count, its
48/// cast, and its accumulation — operations that capture into the training
49/// program and execute on every replay, so no per-step accuracy readback
50/// exists. The single observation is one readback per epoch boundary inside
51/// `commit_epoch`. Epoch isolation is exact cumulative differencing of both
52/// the device correct-count and the lifecycle's exact sample accounting;
53/// integer counts in F32 are exact far beyond any training run (2^24
54/// samples), so the counter never resets.
55pub struct AccuracyMetric {
56	name: String,
57	accumulator: Matrix,
58	cursor: Matrix,
59	previous_correct: u64,
60	previous_samples: u64,
61	last: f64,
62}
63
64impl AccuracyMetric {
65	/// Allocate the persistent device state for one training run.
66	///
67	/// The buffers belong to the run, never the model registry, and never
68	/// enter checkpoints. Host mutation is forbidden while a captured program
69	/// borrows them, matching the mutable-output-slot rules.
70	///
71	/// # Errors
72	///
73	/// Returns device allocation errors from the owning runtime.
74	pub fn new(name: impl Into<String>) -> Result<Self> {
75		Self::new_with_runtime(&crate::Runtime::current()?, name)
76	}
77
78	/// Allocate the persistent device state on an explicit runtime.
79	///
80	/// The runtime must own the training run's matrices; accumulation
81	/// validates runtime ownership on every observation.
82	///
83	/// # Errors
84	///
85	/// Returns device allocation errors from `runtime`.
86	pub fn new_with_runtime(runtime: &crate::Runtime, name: impl Into<String>) -> Result<Self> {
87		Ok(Self {
88			name: name.into(),
89			accumulator: Matrix::new_from_f32_on(runtime, [1], &[0.0])?,
90			cursor: Matrix::new_from_slice_on(runtime, [2], &[0_u32, 0])?,
91			previous_correct: 0,
92			previous_samples: 0,
93			last: f64::NAN,
94		})
95	}
96
97	/// Return the recording handle for the step's record closure.
98	///
99	/// The lifecycle holds the metric mutably once registered, so observation
100	/// flows through this cloneable handle: it shares the device state but
101	/// borrows nothing, and the record closure may own it for the whole run.
102	pub fn observer(&self) -> AccuracyObserver {
103		AccuracyObserver {
104			accumulator: self.accumulator.clone(),
105			cursor: self.cursor.clone(),
106		}
107	}
108}
109
110/// Cloneable recording handle for one [`AccuracyMetric`].
111///
112/// Call [`AccuracyObserver::observe`] exactly once per step inside the record
113/// closure; in the captured plane the operations record once and execute on
114/// every replay, so no per-step accuracy readback exists.
115#[derive(Clone)]
116pub struct AccuracyObserver {
117	accumulator: Matrix,
118	cursor: Matrix,
119}
120
121impl AccuracyObserver {
122	/// Record the batch's correctness count into the device accumulator.
123	///
124	/// # Errors
125	///
126	/// Returns shape, dtype, and runtime-ownership errors from the counting,
127	/// cast, and accumulation operations.
128	pub fn observe(&self, logits: &Matrix, targets: &Matrix) -> Result<()> {
129		let correct = logits.categorical_accuracy_count(targets)?;
130		let correct_f32 = correct.cast_i32_f32()?;
131		training_accumulate(&self.accumulator, &correct_f32, &self.cursor, 1.0)
132	}
133}
134
135impl TrainingMetric for AccuracyMetric {
136	fn name(&self) -> &str {
137		&self.name
138	}
139
140	fn reset(&mut self) {
141		// The lifecycle resets metrics at every epoch begin. The cumulative
142		// baselines mirror device state that never resets — integer-exact
143		// differencing is this metric's epoch isolation — so only the
144		// observed-result cache clears here.
145		self.last = f64::NAN;
146	}
147
148	fn update_step(&mut self, _state: TrainingSnapshot) {}
149
150	fn result(&self) -> f64 {
151		self.last
152	}
153
154	fn observe_batch(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
155		self.observer().observe(prediction, target)
156	}
157
158	fn commit_epoch(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<()> {
159		let cumulative = self.accumulator.read_f32()?[0] as u64;
160		let correct = cumulative - self.previous_correct;
161		self.previous_correct = cumulative;
162		let total_samples = context.snapshot().total_samples();
163		let samples = total_samples - self.previous_samples;
164		self.previous_samples = total_samples;
165		self.last = if samples == 0 {
166			f64::NAN
167		} else {
168			correct as f64 / samples as f64
169		};
170		context.commit_metric("train", &self.name.clone(), self.last);
171		Ok(())
172	}
173}
174
175/// Aggregation policy for [`LossMetric`].
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177pub enum LossAggregation {
178	#[default]
179	Mean,
180	Last,
181}
182
183/// Running completed-step loss metric.
184pub struct LossMetric {
185	name: String,
186	aggregation: LossAggregation,
187	sum: f64,
188	last: f64,
189	count: u64,
190}
191
192impl LossMetric {
193	pub fn new(name: impl Into<String>, aggregation: LossAggregation) -> Self {
194		Self {
195			name: name.into(),
196			aggregation,
197			sum: 0.0,
198			last: 0.0,
199			count: 0,
200		}
201	}
202
203	pub const fn count(&self) -> u64 {
204		self.count
205	}
206
207	pub fn mean(&self) -> f64 {
208		if self.count == 0 {
209			0.0
210		} else {
211			self.sum / self.count as f64
212		}
213	}
214
215	pub fn last(&self) -> f64 {
216		if self.count == 0 { 0.0 } else { self.last }
217	}
218}
219
220impl Default for LossMetric {
221	fn default() -> Self {
222		Self::new("loss", LossAggregation::Mean)
223	}
224}
225
226impl TrainingMetric for LossMetric {
227	fn name(&self) -> &str {
228		&self.name
229	}
230
231	fn reset(&mut self) {
232		self.sum = 0.0;
233		self.last = 0.0;
234		self.count = 0;
235	}
236
237	fn update_step(&mut self, state: TrainingSnapshot) {
238		if let Some(loss) = state.last_loss() {
239			self.sum += f64::from(loss);
240			self.last = f64::from(loss);
241			self.count = self.count.saturating_add(1);
242		}
243	}
244
245	fn result(&self) -> f64 {
246		match self.aggregation {
247			LossAggregation::Mean => self.mean(),
248			LossAggregation::Last => self.last(),
249		}
250	}
251}