Skip to main content

oa/ml/training/
fit.rs

1//! Dataset-driven training over the ordinary eager update lifecycle.
2
3use crate::{
4	DType, Error, Matrix, Result,
5	data::{Batch, DataLoader},
6	ml::{
7		CheckpointCriteriaState, CheckpointManager, GradientTape, Module, autograd::recording_active,
8		capture_rng_states, matrix::detach, metric, restore_rng_states,
9	},
10};
11
12use super::{CaptureEligibility, ExecutionMode, Training, TrainingOptimizer, TrainingSnapshot};
13use crate::ml::optim::GradScaler;
14use crate::ml::precision::{EffectivePrecision, PrecisionPolicy};
15use crate::ml::types::ValidationResult;
16
17/// A supervised evaluation summary with optional exact classification counts.
18#[derive(Clone, Copy, Debug)]
19pub struct EvaluationReport {
20	pub summary: ValidationResult,
21	pub correct: Option<u64>,
22}
23
24impl EvaluationReport {
25	/// Return categorical accuracy when it was requested and the split was nonempty.
26	#[must_use]
27	pub fn accuracy(self) -> Option<f64> {
28		self
29			.correct
30			.filter(|_| self.summary.samples != 0)
31			.map(|correct| correct as f64 / self.summary.samples as f64)
32	}
33}
34
35/// Observations for one training epoch, including a partial final epoch.
36#[derive(Clone, Debug)]
37pub struct TrainingEpoch {
38	pub epoch: u64,
39	pub batches: u64,
40	pub samples: u64,
41	pub loss: f64,
42	pub metrics: Vec<(String, f64)>,
43	pub validation: Option<EvaluationReport>,
44}
45
46/// Epoch observations and the terminal state of a managed training run.
47#[derive(Clone, Debug)]
48pub struct TrainingHistory {
49	pub epochs: Vec<TrainingEpoch>,
50	pub snapshot: TrainingSnapshot,
51	pub best_epoch: Option<u64>,
52	/// Effective precision planes under which this fit executed.
53	pub precision: EffectivePrecision,
54	/// Whole-program capture eligibility observed by this fit.
55	pub capture_eligibility: CaptureEligibility,
56}
57
58/// Optional classification metrics, validation, and checkpointing for a fit.
59#[derive(Default)]
60pub struct TrainingFitOptions<'fit, 'runtime> {
61	/// Accumulate categorical accuracy without per-batch host observation.
62	pub categorical_accuracy: bool,
63	/// Evaluate the held-out split after each complete epoch.
64	pub validation: Option<&'fit mut dyn FnMut() -> Result<EvaluationReport>>,
65	/// Save and restore the best validation loss with the native checkpoint manager.
66	pub checkpoint: Option<(&'fit mut CheckpointManager<'runtime>, &'fit dyn Module)>,
67	/// Microbatches per optimizer update. One preserves the per-batch update
68	/// contract exactly. Above one, the loop owns the accumulation window:
69	/// each microbatch objective is scaled to a per-sample sum before backward,
70	/// parameter gradients accumulate across the window, the exact window
71	/// denominator corrects them before the update — so incomplete tail
72	/// windows remain exact rather than mean-of-means — and lifecycle update
73	/// counters, completion hooks, and schedules observe one step per applied
74	/// update while sample accounting counts every microbatch. Managed fits
75	/// derive the parameter set from the model; caller-driven batch sources
76	/// must leave this at one.
77	pub accumulation_steps: u64,
78	/// Exact-resume position loaded beside an incremental checkpoint. The run
79	/// continues at `resume.epoch` — `epochs` remains the total epoch budget of
80	/// the run, so a resumed fit executes `resume.epoch..epochs`. A nonzero
81	/// loader cursor continues a partial first epoch; commits the managed fit
82	/// writes itself always land on epoch boundaries, but manual loops may
83	/// commit mid-epoch. Registered per-module RNG streams and checkpoint
84	/// best-selection criteria carried in `resume` are restored before the
85	/// resumed loop runs. When `scaler` is also provided, `resume.scaler` is
86	/// restored onto it before the resumed loop runs.
87	pub resume: Option<crate::ml::RunState>,
88	/// Optional runtime-scoped precision policy entered for the duration of
89	/// this fit and restored automatically when the fit returns.
90	pub precision: Option<PrecisionPolicy>,
91	/// Optional dynamic gradient scaler for mixed-precision managed fits.
92	/// Required whenever the effective precision policy requires scaling
93	/// (such as [`PrecisionPolicy::f16_storage`]).
94	pub scaler: Option<&'fit mut GradScaler>,
95}
96
97impl TrainingFitOptions<'_, '_> {
98	/// Construct default fit options.
99	#[inline]
100	#[must_use]
101	pub fn new() -> Self {
102		Self::default()
103	}
104}
105
106struct ManagedStep {
107	loss: Matrix,
108	correct: Option<Matrix>,
109	prediction: Option<Matrix>,
110}
111
112impl Training<'_, '_> {
113	/// Train a supervised model over a finite loader using a sample-mean loss.
114	///
115	/// The loader is reset for every epoch. This consumes the training run,
116	/// sets the model to training mode, and fires the ordinary lifecycle hooks.
117	/// For a caller-defined batch source or objective, use [Self::fit_with].
118	///
119	/// # Errors
120	///
121	/// Returns schedule, loader, model, loss, optimizer, or callback errors.
122	pub fn fit(
123		self,
124		model: &dyn Module,
125		loader: &mut DataLoader<'_>,
126		epochs: u64,
127		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
128	) -> Result<TrainingHistory> {
129		self.fit_with_options(model, loader, epochs, &mut loss, TrainingFitOptions::new())
130	}
131
132	/// Fit a supervised model with optional metrics, validation and checkpointing.
133	///
134	/// Validation runs after registered epoch hooks. Checkpoint selection uses
135	/// validation loss and restores the best epoch at the end of the run.
136	///
137	/// # Errors
138	///
139	/// Returns errors from the supervised fit, validation, or checkpoint policy.
140	pub fn fit_with_options(
141		self,
142		model: &dyn Module,
143		loader: &mut DataLoader<'_>,
144		epochs: u64,
145		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
146		options: TrainingFitOptions<'_, '_>,
147	) -> Result<TrainingHistory> {
148		model.train(true);
149		// Position the loader and restore registered module RNG streams before
150		// the loop: a mid-epoch resume starts above index zero, where the
151		// per-epoch reset trigger never fires. Boundary resumes (cursor zero)
152		// would equivalently be served by the trigger, but seeking uniformly
153		// keeps one positioning path — reset_epoch and seek derive the
154		// identical order for the same epoch.
155		if let Some(resume) = &options.resume {
156			loader.seek(resume.epoch, resume.loader_cursor)?;
157			restore_rng_states(model, &resume.rng_states)?;
158		}
159		let managed_parameters = if options.accumulation_steps > 1 || options.scaler.is_some() {
160			Some(model.all_parameters()?)
161		} else {
162			None
163		};
164		self.fit_supervised_batches_inner(
165			epochs,
166			loader.num_batches() as u64,
167			|epoch, index| {
168				if index == 0 {
169					loader.reset_epoch(epoch)?;
170				}
171				loader
172					.next_batch()?
173					.ok_or_else(|| Error::failed_precondition("training loader ran out of batches"))
174			},
175			|x| model.forward(x),
176			loss,
177			options,
178			managed_parameters,
179		)
180	}
181
182	/// Fit supervised batches supplied by a caller-defined source.
183	///
184	/// The source receives zero-based epoch and batch indices. The forward
185	/// function uses training mode. Validation functions select their own mode.
186	///
187	/// # Errors
188	///
189	/// Returns errors from the supervised fit, validation, or checkpoint policy.
190	pub fn fit_supervised_batches(
191		self,
192		epochs: u64,
193		batches_per_epoch: u64,
194		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
195		forward: impl FnMut(&Matrix) -> Result<Matrix>,
196		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
197		options: TrainingFitOptions<'_, '_>,
198	) -> Result<TrainingHistory> {
199		self.fit_supervised_batches_inner(
200			epochs,
201			batches_per_epoch,
202			batch_at,
203			forward,
204			loss,
205			options,
206			None,
207		)
208	}
209
210	/// Fit supervised batches supplied by a caller-defined source with an
211	/// explicit parameter set for gradient accumulation or dynamic loss scaling.
212	///
213	/// # Errors
214	///
215	/// Returns errors from the supervised fit, validation, precision scope,
216	/// gradient scaling, or checkpoint policy.
217	#[allow(clippy::too_many_arguments)]
218	pub fn fit_supervised_batches_with_parameters(
219		self,
220		epochs: u64,
221		batches_per_epoch: u64,
222		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
223		forward: impl FnMut(&Matrix) -> Result<Matrix>,
224		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
225		parameters: &[crate::ml::Parameter],
226		options: TrainingFitOptions<'_, '_>,
227	) -> Result<TrainingHistory> {
228		self.fit_supervised_batches_inner(
229			epochs,
230			batches_per_epoch,
231			batch_at,
232			forward,
233			loss,
234			options,
235			Some(parameters.to_vec()),
236		)
237	}
238
239	#[allow(clippy::too_many_arguments)]
240	fn fit_supervised_batches_inner(
241		self,
242		epochs: u64,
243		batches_per_epoch: u64,
244		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
245		mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
246		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
247		options: TrainingFitOptions<'_, '_>,
248		accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
249	) -> Result<TrainingHistory> {
250		let accuracy = options.categorical_accuracy;
251		self.fit_batches(
252			epochs,
253			batches_per_epoch,
254			batch_at,
255			|batch| supervised_step(batch, &mut forward, &mut loss, accuracy),
256			options,
257			accumulation_parameters,
258		)
259	}
260
261	/// Train from a caller-defined batch source and a custom forward/loss step.
262	///
263	/// The batch source receives zero-based epoch and batch indices. The step
264	/// returns a scalar FP32 sample-mean loss. Training owns the tape, backward,
265	/// optimizer update, completion, and callbacks. Use `step` or manual
266	/// completion when the caller needs to own backward. The batch source and
267	/// objective run on the training Runtime's thread.
268	///
269	/// # Errors
270	///
271	/// Requires a fresh run with no configured manual step schedule or active
272	/// tape, and a nonempty finite schedule. Reports source, step, and callback
273	/// failures through the training lifecycle.
274	pub fn fit_with(
275		self,
276		epochs: u64,
277		batches_per_epoch: u64,
278		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
279		mut step: impl FnMut(&Batch) -> Result<Matrix>,
280	) -> Result<TrainingHistory> {
281		self.fit_batches(
282			epochs,
283			batches_per_epoch,
284			batch_at,
285			|batch| {
286				Ok(ManagedStep {
287					loss: step(batch)?,
288					correct: None,
289					prediction: None,
290				})
291			},
292			TrainingFitOptions::new(),
293			None,
294		)
295	}
296
297	fn fit_batches(
298		mut self,
299		epochs: u64,
300		batches_per_epoch: u64,
301		mut batch_at: impl FnMut(u64, u64) -> Result<Batch>,
302		mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
303		mut options: TrainingFitOptions<'_, '_>,
304		accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
305	) -> Result<TrainingHistory> {
306		if let Some((manager, _)) = &options.checkpoint {
307			if options.validation.is_none() {
308				return Err(Error::invalid_argument(
309					"fit checkpoint selection requires validation",
310				));
311			}
312			if !manager.saves_best_loss() {
313				return Err(Error::invalid_argument(
314					"fit checkpointing requires a manager that saves the lowest validation loss",
315				));
316			}
317			checkpoint_optimizer(&mut self.optimizer)?;
318		}
319		if self.started
320			|| self.config.initial_step != 0
321			|| self.config.total_steps != 0
322			|| self.config.steps_per_epoch != 0
323			|| !self.config.epoch_steps.is_empty()
324		{
325			return Err(Error::failed_precondition(
326				"fit requires a fresh training run without a manual step schedule",
327			));
328		}
329		if epochs == 0 || batches_per_epoch == 0 {
330			return Err(Error::invalid_argument(
331				"fit requires at least one epoch and batch",
332			));
333		}
334		let start_epoch = options.resume.as_ref().map_or(0, |resume| resume.epoch);
335		let start_cursor = options
336			.resume
337			.as_ref()
338			.map_or(0, |resume| resume.loader_cursor);
339		if start_epoch >= epochs {
340			return Err(Error::invalid_argument(
341				"fit resume epoch is outside the total epoch budget",
342			));
343		}
344		if start_cursor < 0 || start_cursor as u64 >= batches_per_epoch {
345			return Err(Error::invalid_argument(
346				"fit resume cursor is outside the epoch",
347			));
348		}
349		let mut best_epoch = None;
350		if let (Some((manager, _)), Some(criteria)) = (
351			options.checkpoint.as_mut(),
352			options.resume.as_ref().and_then(|resume| resume.checkpoint),
353		) {
354			if let Some(epoch) = criteria.best_epoch {
355				if epoch == 0 {
356					return Err(Error::invalid_argument(
357						"fit resume best epoch must be one-based",
358					));
359				}
360				if !criteria.best_metric.is_finite() {
361					return Err(Error::invalid_argument(
362						"fit resume best epoch requires a finite best metric",
363					));
364				}
365			}
366			manager.restore_best_metric(criteria.best_metric)?;
367			best_epoch = criteria.best_epoch;
368		}
369		let _precision_scope = options
370			.precision
371			.map(|policy| policy.enter(self.runtime))
372			.transpose()?;
373		let effective_precision = PrecisionPolicy::current(self.runtime);
374		if effective_precision.scaler_required && options.scaler.is_none() {
375			return Err(Error::failed_precondition(
376				"effective precision policy requires a GradScaler in TrainingFitOptions",
377			));
378		}
379		let window = options.accumulation_steps.max(1);
380		if window > 1 && accumulation_parameters.is_none() {
381			return Err(Error::invalid_argument(
382				"gradient accumulation requires the managed model fit — caller-driven batch sources do not expose the parameter set",
383			));
384		}
385		if options.scaler.is_some() && accumulation_parameters.is_none() {
386			return Err(Error::invalid_argument(
387				"gradient scaling requires the managed model fit — caller-driven batch sources do not expose the parameter set",
388			));
389		}
390		if let (Some(scaler), Some(scaler_state)) = (
391			options.scaler.as_deref_mut(),
392			options.resume.as_ref().and_then(|resume| resume.scaler),
393		) {
394			scaler.restore_state(scaler_state)?;
395		}
396		without_active_tape()?;
397		// Lifecycle steps count applied updates, not microbatches: schedules
398		// and budgets advance only when an update applies.
399		let updates_per_epoch = batches_per_epoch.div_ceil(window);
400		self.config.total_steps = epochs
401			.checked_mul(updates_per_epoch)
402			.ok_or_else(|| Error::resource_exhausted("fit step budget overflows u64"))?;
403		self.config.steps_per_epoch = updates_per_epoch;
404		self.sample_weighted_loss = true;
405		self.disable_eager_resource_reuse();
406		self.select_execution_mode(ExecutionMode::Eager)?;
407		if self.runtime.has_pending_work() {
408			self.runtime.checkpoint()?.wait()?;
409		}
410
411		let mut history = Vec::new();
412		for epoch in start_epoch..epochs {
413			let before = self.snapshot();
414			let mut counts = Vec::new();
415			let first_index = if epoch == start_epoch {
416				start_cursor as u64
417			} else {
418				0
419			};
420			let mut index = first_index;
421			while index < batches_per_epoch {
422				let window_end = index.saturating_add(window).min(batches_per_epoch);
423				let previous_step = self.step_count;
424				if !self.wait_begin_step()? {
425					self.step_count = previous_step;
426					break;
427				}
428				let result = (|| {
429					self.zero_grad();
430					let mut total_samples = 0_u64;
431					let mut window_loss: Option<Matrix> = None;
432					let mut completion_loss: Option<Matrix> = None;
433					for microbatch in index..window_end {
434						let batch = batch_at(epoch, microbatch)?;
435						let samples = batch_samples(&batch)?;
436						if !self.runtime.owns_matrix(&batch.x) {
437							return Err(Error::invalid_argument("batch belongs to another Runtime"));
438						}
439						self.config.batch_size = self.config.batch_size.max(samples);
440						let tape = GradientTape::new();
441						let step = step(&batch)?;
442						validate_loss(&batch, &step.loss)?;
443						// Above one microbatch per update the sample-mean
444						// objective scales to a per-sample sum before backward,
445						// so accumulated gradients carry exact sample
446						// weighting regardless of how the window tails.
447						let unscaled_backward_loss = if window > 1 {
448							let factor = Matrix::new_from_slice_on(self.runtime, vec![], &[samples as f32])?;
449							step.loss.mul(&factor)?
450						} else {
451							step.loss.clone()
452						};
453						let backward_loss = if let Some(scaler) = options.scaler.as_deref() {
454							scaler.scale_loss(&unscaled_backward_loss)?
455						} else {
456							unscaled_backward_loss.clone()
457						};
458						tape.backward(&backward_loss)?;
459						// Registered prediction metrics observe the batch before the
460						// step completes — completion is what fires epoch-boundary
461						// commits, so feeding afterwards would drop the final batch
462						// of every epoch from its count.
463						if let (Some(prediction), Some(target)) = (&step.prediction, batch.y.as_ref()) {
464							for metric in &mut self.metrics {
465								metric.observe_batch(prediction, target)?;
466							}
467						}
468						total_samples = total_samples
469							.checked_add(samples)
470							.ok_or_else(|| Error::resource_exhausted("accumulated samples overflow u64"))?;
471						if window > 1 {
472							let detached = detach(&unscaled_backward_loss)?;
473							window_loss = Some(match window_loss {
474								None => detached,
475								Some(acc) => acc.add(&detached)?,
476							});
477						} else {
478							completion_loss = Some(step.loss.clone());
479						}
480						counts.extend(step.correct);
481					}
482					self.pending_step_samples = Some(total_samples);
483					let completion_loss = if window > 1 {
484						// The exact window denominator corrects the summed
485						// gradients before the update — incomplete tail windows
486						// stay exact rather than mean-of-means.
487						#[allow(clippy::cast_precision_loss)]
488						let inverse = Matrix::new_from_slice_on(self.runtime, vec![], &[1.0 / total_samples as f32])?;
489						for parameter in accumulation_parameters.as_deref().unwrap_or(&[]) {
490							if let Some(gradient) = parameter.gradient() {
491								parameter.set_gradient(detach(&gradient.mul(&inverse)?)?);
492							}
493						}
494						window_loss
495							.expect("a window runs at least one microbatch")
496							.mul(&inverse)?
497					} else {
498						completion_loss.expect("a window runs at least one microbatch")
499					};
500					if let Some(scaler) = options.scaler.as_deref_mut() {
501						let check =
502							scaler.unscale_gradients(accumulation_parameters.as_deref().unwrap_or(&[]))?;
503						self.complete_step_scaled(&completion_loss, &check, scaler)?;
504					} else {
505						self.complete_step(&completion_loss)?;
506					}
507					Ok(())
508				})();
509				if let Err(error) = result {
510					self.runtime.abort_pending_work();
511					return self.fail(error);
512				}
513				index = window_end;
514			}
515
516			let after = self.snapshot();
517			let batches = after.step_count() - before.step_count();
518			let samples = after.total_samples() - before.total_samples();
519			if batches > 0 {
520				let start = std::time::Instant::now();
521				let observation = (|| {
522					let mut metrics: Vec<_> = self
523						.metrics
524						.iter()
525						.map(|metric| (metric.name().to_owned(), metric.result()))
526						.collect();
527					if options.categorical_accuracy {
528						metrics.push((
529							"accuracy".to_owned(),
530							count_correct(&counts)? as f64 / samples as f64,
531						));
532					}
533					let expected_updates = (batches_per_epoch - first_index).div_ceil(window);
534					let validation = if batches == expected_updates {
535						options
536							.validation
537							.as_mut()
538							.map(|evaluate| evaluate())
539							.transpose()?
540					} else {
541						None
542					};
543					if let (Some(validation), Some((manager, model))) =
544						(validation, options.checkpoint.as_mut())
545					{
546						let optimizer = checkpoint_optimizer(&mut self.optimizer)?;
547						let improved = manager.is_better(validation.summary.loss);
548						let next_best_metric = if improved {
549							validation.summary.loss
550						} else {
551							manager.best_metric()
552						};
553						let next_best_epoch = if improved {
554							Some(epoch + 1)
555						} else {
556							best_epoch
557						};
558						// Commits land on epoch boundaries: the next position is
559						// the first batch of the following epoch. When a GradScaler
560						// drives the fit, persist its dynamic scale and growth
561						// counter alongside the checkpoint. Always persist the
562						// incremental checkpoint and companion run state
563						// (`force = true`) so non-improving epochs still record
564						// current weights, optimizer state, RNG positions, and
565						// preserved best criteria without overwriting master.
566						let scaler_state = options
567							.scaler
568							.as_deref()
569							.map(GradScaler::capture_state)
570							.transpose()?;
571						let run_state = crate::ml::RunState {
572							epoch: epoch + 1,
573							loader_cursor: 0,
574							scaler: scaler_state,
575							rng_states: capture_rng_states(*model)?,
576							checkpoint: Some(CheckpointCriteriaState {
577								best_metric: next_best_metric,
578								best_epoch: next_best_epoch,
579							}),
580							early_stopping: None,
581						};
582						if manager.maybe_save_with_run_state(
583							*model,
584							optimizer,
585							optimizer.step_count(),
586							validation.summary.loss,
587							true,
588							&run_state,
589						)? {
590							best_epoch = Some(epoch + 1);
591						}
592					}
593					Ok((metrics, validation))
594				})();
595				self.exclude_wall_time(start.elapsed());
596				let (metrics, validation) = match observation {
597					Ok(observation) => observation,
598					Err(error) => return self.fail(error),
599				};
600				history.push(TrainingEpoch {
601					epoch: epoch + 1,
602					batches,
603					samples,
604					loss: after.epoch_mean_loss(),
605					metrics,
606					validation,
607				});
608			}
609			if batches < (batches_per_epoch - first_index).div_ceil(window) || self.stop_requested() {
610				break;
611			}
612		}
613		if let (Some(best), Some((manager, model))) = (best_epoch, options.checkpoint)
614			&& history.last().is_some_and(|epoch| epoch.epoch != best)
615		{
616			let start = std::time::Instant::now();
617			let restore = checkpoint_optimizer(&mut self.optimizer)
618				.and_then(|optimizer| manager.load_best_into(model, optimizer));
619			self.exclude_wall_time(start.elapsed());
620			if let Err(error) = restore {
621				return self.fail(error);
622			}
623		}
624		let capture_eligibility = self.capture_eligibility();
625		Ok(TrainingHistory {
626			epochs: history,
627			snapshot: self.finish()?,
628			best_epoch,
629			precision: effective_precision,
630			capture_eligibility,
631		})
632	}
633
634	/// Evaluate a supervised model and return sample-weighted mean loss.
635	///
636	/// Resets the loader and restores the model's prior modes, even on error.
637	/// An empty split returns [ValidationResult::default].
638	///
639	/// # Errors
640	///
641	/// Returns loader, model, loss, and observation errors. Evaluation requires
642	/// no active gradient tape.
643	pub fn evaluate(
644		model: &dyn Module,
645		loader: &mut DataLoader<'_>,
646		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
647	) -> Result<ValidationResult> {
648		Self::evaluate_supervised(model, loader, &mut loss, false).map(|report| report.summary)
649	}
650
651	/// Evaluate a model with optional categorical accuracy.
652	///
653	/// Resets the loader and restores all prior module modes.
654	///
655	/// # Errors
656	///
657	/// Returns loader, model, loss, and metric errors.
658	pub fn evaluate_supervised(
659		model: &dyn Module,
660		loader: &mut DataLoader<'_>,
661		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
662		categorical_accuracy: bool,
663	) -> Result<EvaluationReport> {
664		let _mode = model.scoped_eval();
665		Self::evaluate_prediction_batches(loader, |x| model.forward(x), loss, categorical_accuracy)
666	}
667
668	/// Evaluate a prediction function on a reset loader.
669	///
670	/// # Errors
671	///
672	/// Returns loader, model, loss, and metric errors.
673	pub fn evaluate_prediction_batches(
674		loader: &mut DataLoader<'_>,
675		forward: impl FnMut(&Matrix) -> Result<Matrix>,
676		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
677		categorical_accuracy: bool,
678	) -> Result<EvaluationReport> {
679		loader.reset()?;
680		Self::evaluate_predictions(
681			std::iter::from_fn(|| loader.next_batch().transpose()),
682			forward,
683			loss,
684			categorical_accuracy,
685		)
686	}
687
688	/// Evaluate a supervised prediction function in caller-selected inference mode.
689	///
690	/// # Errors
691	///
692	/// Returns source, loss, prediction, and observation errors.
693	pub fn evaluate_predictions(
694		batches: impl IntoIterator<Item = Result<Batch>>,
695		mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
696		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
697		categorical_accuracy: bool,
698	) -> Result<EvaluationReport> {
699		Self::evaluate_batches(
700			batches,
701			|batch| supervised_step(batch, &mut forward, &mut loss, categorical_accuracy),
702			categorical_accuracy,
703		)
704	}
705
706	/// Evaluate a caller-defined objective on a stream of batches.
707	///
708	/// The caller selects inference mode for any model used in `step`. Losses
709	/// must be scalar FP32 batch means. Reading each scalar waits for its work.
710	///
711	/// # Errors
712	///
713	/// Returns source, step, validation, or observation errors.
714	pub fn evaluate_with(
715		batches: impl IntoIterator<Item = Result<Batch>>,
716		mut step: impl FnMut(&Batch) -> Result<Matrix>,
717	) -> Result<ValidationResult> {
718		Self::evaluate_batches(
719			batches,
720			|batch| {
721				Ok(ManagedStep {
722					loss: step(batch)?,
723					correct: None,
724					prediction: None,
725				})
726			},
727			false,
728		)
729		.map(|report| report.summary)
730	}
731
732	fn evaluate_batches(
733		batches: impl IntoIterator<Item = Result<Batch>>,
734		mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
735		categorical_accuracy: bool,
736	) -> Result<EvaluationReport> {
737		without_active_tape()?;
738		let mut result = ValidationResult::new();
739		let mut weighted_loss = 0.0;
740		let mut counts = Vec::new();
741		for batch in batches {
742			let batch = batch?;
743			let count = batch_samples(&batch)?;
744			let step = step(&batch)?;
745			validate_loss(&batch, &step.loss)?;
746			weighted_loss += f64::from(metric::scalar_loss(&step.loss)?) * count as f64;
747			counts.extend(step.correct);
748			result.batches += 1;
749			result.samples = result
750				.samples
751				.checked_add(count)
752				.ok_or_else(|| Error::resource_exhausted("evaluation sample count overflows u64"))?;
753		}
754		if result.samples > 0 {
755			result.loss = weighted_loss / result.samples as f64;
756		}
757		let correct = if categorical_accuracy {
758			Some(count_correct(&counts)?)
759		} else {
760			None
761		};
762		Ok(EvaluationReport {
763			summary: result,
764			correct,
765		})
766	}
767}
768
769fn checkpoint_optimizer<'a>(
770	optimizer: &'a mut TrainingOptimizer<'_>,
771) -> Result<&'a mut dyn crate::ml::CheckpointOptimizer> {
772	match optimizer {
773		TrainingOptimizer::AdamW(optimizer) => Ok(*optimizer),
774		TrainingOptimizer::Checkpointable(optimizer) => Ok(*optimizer),
775		TrainingOptimizer::Eager(_) => Err(Error::failed_precondition(
776			"fit requires a checkpointable optimizer when checkpointing is configured",
777		)),
778	}
779}
780
781fn count_correct(counts: &[Matrix]) -> Result<u64> {
782	// Combine the device counts in bounded groups for host observation.
783	let mut total = 0;
784	for group in counts.chunks(128) {
785		let values = crate::matrix::concat(group, 0)?.read::<u32>()?;
786		total += values.into_iter().map(u64::from).sum::<u64>();
787	}
788	Ok(total)
789}
790
791fn supervised_step(
792	batch: &Batch,
793	forward: impl FnOnce(&Matrix) -> Result<Matrix>,
794	loss: impl FnOnce(&Matrix, &Matrix) -> Result<Matrix>,
795	categorical_accuracy: bool,
796) -> Result<ManagedStep> {
797	let target = batch
798		.y
799		.as_ref()
800		.ok_or_else(|| Error::invalid_argument("supervised training and evaluation require labels"))?;
801	let prediction = forward(&batch.x)?;
802	let loss = loss(&prediction, target)?;
803	let correct = if categorical_accuracy {
804		if target.shape().len() != 1 {
805			return Err(Error::invalid_argument(
806				"categorical accuracy requires one target per sample",
807			));
808		}
809		Some(prediction.categorical_accuracy_count(target)?)
810	} else {
811		None
812	};
813	Ok(ManagedStep {
814		loss,
815		correct,
816		prediction: Some(prediction),
817	})
818}
819
820fn batch_samples(batch: &Batch) -> Result<u64> {
821	let count = batch.x.shape().first().copied().unwrap_or(0);
822	if count == 0 {
823		return Err(Error::invalid_argument(
824			"a batch requires a nonempty leading sample axis",
825		));
826	}
827	if let Some(target) = &batch.y
828		&& (target.shape().first() != Some(&count) || !target.runtime().same_as(batch.x.runtime()))
829	{
830		return Err(Error::invalid_argument(
831			"batch targets must match input samples and Runtime",
832		));
833	}
834	Ok(count as u64)
835}
836
837fn validate_loss(batch: &Batch, loss: &Matrix) -> Result<()> {
838	if loss.dtype() != DType::F32 || !loss.shape().is_empty() {
839		return Err(Error::invalid_argument("batch loss must be an FP32 scalar"));
840	}
841	if !loss.runtime().same_as(batch.x.runtime()) {
842		return Err(Error::invalid_argument(
843			"batch loss and inputs must share a Runtime",
844		));
845	}
846	Ok(())
847}
848
849fn without_active_tape() -> Result<()> {
850	if recording_active() {
851		return Err(Error::failed_precondition(
852			"managed training and evaluation require no active GradientTape",
853		));
854	}
855	Ok(())
856}