oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Dataset-driven training over the ordinary eager update lifecycle.

use crate::{
	DType, Error, Matrix, Result,
	data::{Batch, DataLoader},
	ml::{
		CheckpointCriteriaState, CheckpointManager, GradientTape, Module, autograd::recording_active,
		capture_rng_states, matrix::detach, metric, restore_rng_states,
	},
};

use super::{CaptureEligibility, ExecutionMode, Training, TrainingOptimizer, TrainingSnapshot};
use crate::ml::optim::GradScaler;
use crate::ml::precision::{EffectivePrecision, PrecisionPolicy};
use crate::ml::types::ValidationResult;

/// A supervised evaluation summary with optional exact classification counts.
#[derive(Clone, Copy, Debug)]
pub struct EvaluationReport {
	pub summary: ValidationResult,
	pub correct: Option<u64>,
}

impl EvaluationReport {
	/// Return categorical accuracy when it was requested and the split was nonempty.
	#[must_use]
	pub fn accuracy(self) -> Option<f64> {
		self
			.correct
			.filter(|_| self.summary.samples != 0)
			.map(|correct| correct as f64 / self.summary.samples as f64)
	}
}

/// Observations for one training epoch, including a partial final epoch.
#[derive(Clone, Debug)]
pub struct TrainingEpoch {
	pub epoch: u64,
	pub batches: u64,
	pub samples: u64,
	pub loss: f64,
	pub metrics: Vec<(String, f64)>,
	pub validation: Option<EvaluationReport>,
}

/// Epoch observations and the terminal state of a managed training run.
#[derive(Clone, Debug)]
pub struct TrainingHistory {
	pub epochs: Vec<TrainingEpoch>,
	pub snapshot: TrainingSnapshot,
	pub best_epoch: Option<u64>,
	/// Effective precision planes under which this fit executed.
	pub precision: EffectivePrecision,
	/// Whole-program capture eligibility observed by this fit.
	pub capture_eligibility: CaptureEligibility,
}

/// Optional classification metrics, validation, and checkpointing for a fit.
#[derive(Default)]
pub struct TrainingFitOptions<'fit, 'runtime> {
	/// Accumulate categorical accuracy without per-batch host observation.
	pub categorical_accuracy: bool,
	/// Evaluate the held-out split after each complete epoch.
	pub validation: Option<&'fit mut dyn FnMut() -> Result<EvaluationReport>>,
	/// Save and restore the best validation loss with the native checkpoint manager.
	pub checkpoint: Option<(&'fit mut CheckpointManager<'runtime>, &'fit dyn Module)>,
	/// Microbatches per optimizer update. One preserves the per-batch update
	/// contract exactly. Above one, the loop owns the accumulation window:
	/// each microbatch objective is scaled to a per-sample sum before backward,
	/// parameter gradients accumulate across the window, the exact window
	/// denominator corrects them before the update — so incomplete tail
	/// windows remain exact rather than mean-of-means — and lifecycle update
	/// counters, completion hooks, and schedules observe one step per applied
	/// update while sample accounting counts every microbatch. Managed fits
	/// derive the parameter set from the model; caller-driven batch sources
	/// must leave this at one.
	pub accumulation_steps: u64,
	/// Exact-resume position loaded beside an incremental checkpoint. The run
	/// continues at `resume.epoch` — `epochs` remains the total epoch budget of
	/// the run, so a resumed fit executes `resume.epoch..epochs`. A nonzero
	/// loader cursor continues a partial first epoch; commits the managed fit
	/// writes itself always land on epoch boundaries, but manual loops may
	/// commit mid-epoch. Registered per-module RNG streams and checkpoint
	/// best-selection criteria carried in `resume` are restored before the
	/// resumed loop runs. When `scaler` is also provided, `resume.scaler` is
	/// restored onto it before the resumed loop runs.
	pub resume: Option<crate::ml::RunState>,
	/// Optional runtime-scoped precision policy entered for the duration of
	/// this fit and restored automatically when the fit returns.
	pub precision: Option<PrecisionPolicy>,
	/// Optional dynamic gradient scaler for mixed-precision managed fits.
	/// Required whenever the effective precision policy requires scaling
	/// (such as [`PrecisionPolicy::f16_storage`]).
	pub scaler: Option<&'fit mut GradScaler>,
}

impl TrainingFitOptions<'_, '_> {
	/// Construct default fit options.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}
}

struct ManagedStep {
	loss: Matrix,
	correct: Option<Matrix>,
	prediction: Option<Matrix>,
}

impl Training<'_, '_> {
	/// Train a supervised model over a finite loader using a sample-mean loss.
	///
	/// The loader is reset for every epoch. This consumes the training run,
	/// sets the model to training mode, and fires the ordinary lifecycle hooks.
	/// For a caller-defined batch source or objective, use [Self::fit_with].
	///
	/// # Errors
	///
	/// Returns schedule, loader, model, loss, optimizer, or callback errors.
	pub fn fit(
		self,
		model: &dyn Module,
		loader: &mut DataLoader<'_>,
		epochs: u64,
		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
	) -> Result<TrainingHistory> {
		self.fit_with_options(model, loader, epochs, &mut loss, TrainingFitOptions::new())
	}

	/// Fit a supervised model with optional metrics, validation and checkpointing.
	///
	/// Validation runs after registered epoch hooks. Checkpoint selection uses
	/// validation loss and restores the best epoch at the end of the run.
	///
	/// # Errors
	///
	/// Returns errors from the supervised fit, validation, or checkpoint policy.
	pub fn fit_with_options(
		self,
		model: &dyn Module,
		loader: &mut DataLoader<'_>,
		epochs: u64,
		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		options: TrainingFitOptions<'_, '_>,
	) -> Result<TrainingHistory> {
		model.train(true);
		// Position the loader and restore registered module RNG streams before
		// the loop: a mid-epoch resume starts above index zero, where the
		// per-epoch reset trigger never fires. Boundary resumes (cursor zero)
		// would equivalently be served by the trigger, but seeking uniformly
		// keeps one positioning path — reset_epoch and seek derive the
		// identical order for the same epoch.
		if let Some(resume) = &options.resume {
			loader.seek(resume.epoch, resume.loader_cursor)?;
			restore_rng_states(model, &resume.rng_states)?;
		}
		let managed_parameters = if options.accumulation_steps > 1 || options.scaler.is_some() {
			Some(model.all_parameters()?)
		} else {
			None
		};
		self.fit_supervised_batches_inner(
			epochs,
			loader.num_batches() as u64,
			|epoch, index| {
				if index == 0 {
					loader.reset_epoch(epoch)?;
				}
				loader
					.next_batch()?
					.ok_or_else(|| Error::failed_precondition("training loader ran out of batches"))
			},
			|x| model.forward(x),
			loss,
			options,
			managed_parameters,
		)
	}

	/// Fit supervised batches supplied by a caller-defined source.
	///
	/// The source receives zero-based epoch and batch indices. The forward
	/// function uses training mode. Validation functions select their own mode.
	///
	/// # Errors
	///
	/// Returns errors from the supervised fit, validation, or checkpoint policy.
	pub fn fit_supervised_batches(
		self,
		epochs: u64,
		batches_per_epoch: u64,
		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
		forward: impl FnMut(&Matrix) -> Result<Matrix>,
		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		options: TrainingFitOptions<'_, '_>,
	) -> Result<TrainingHistory> {
		self.fit_supervised_batches_inner(
			epochs,
			batches_per_epoch,
			batch_at,
			forward,
			loss,
			options,
			None,
		)
	}

	/// Fit supervised batches supplied by a caller-defined source with an
	/// explicit parameter set for gradient accumulation or dynamic loss scaling.
	///
	/// # Errors
	///
	/// Returns errors from the supervised fit, validation, precision scope,
	/// gradient scaling, or checkpoint policy.
	#[allow(clippy::too_many_arguments)]
	pub fn fit_supervised_batches_with_parameters(
		self,
		epochs: u64,
		batches_per_epoch: u64,
		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
		forward: impl FnMut(&Matrix) -> Result<Matrix>,
		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		parameters: &[crate::ml::Parameter],
		options: TrainingFitOptions<'_, '_>,
	) -> Result<TrainingHistory> {
		self.fit_supervised_batches_inner(
			epochs,
			batches_per_epoch,
			batch_at,
			forward,
			loss,
			options,
			Some(parameters.to_vec()),
		)
	}

	#[allow(clippy::too_many_arguments)]
	fn fit_supervised_batches_inner(
		self,
		epochs: u64,
		batches_per_epoch: u64,
		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
		mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		options: TrainingFitOptions<'_, '_>,
		accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
	) -> Result<TrainingHistory> {
		let accuracy = options.categorical_accuracy;
		self.fit_batches(
			epochs,
			batches_per_epoch,
			batch_at,
			|batch| supervised_step(batch, &mut forward, &mut loss, accuracy),
			options,
			accumulation_parameters,
		)
	}

	/// Train from a caller-defined batch source and a custom forward/loss step.
	///
	/// The batch source receives zero-based epoch and batch indices. The step
	/// returns a scalar FP32 sample-mean loss. Training owns the tape, backward,
	/// optimizer update, completion, and callbacks. Use `step` or manual
	/// completion when the caller needs to own backward. The batch source and
	/// objective run on the training Runtime's thread.
	///
	/// # Errors
	///
	/// Requires a fresh run with no configured manual step schedule or active
	/// tape, and a nonempty finite schedule. Reports source, step, and callback
	/// failures through the training lifecycle.
	pub fn fit_with(
		self,
		epochs: u64,
		batches_per_epoch: u64,
		batch_at: impl FnMut(u64, u64) -> Result<Batch>,
		mut step: impl FnMut(&Batch) -> Result<Matrix>,
	) -> Result<TrainingHistory> {
		self.fit_batches(
			epochs,
			batches_per_epoch,
			batch_at,
			|batch| {
				Ok(ManagedStep {
					loss: step(batch)?,
					correct: None,
					prediction: None,
				})
			},
			TrainingFitOptions::new(),
			None,
		)
	}

	fn fit_batches(
		mut self,
		epochs: u64,
		batches_per_epoch: u64,
		mut batch_at: impl FnMut(u64, u64) -> Result<Batch>,
		mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
		mut options: TrainingFitOptions<'_, '_>,
		accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
	) -> Result<TrainingHistory> {
		if let Some((manager, _)) = &options.checkpoint {
			if options.validation.is_none() {
				return Err(Error::invalid_argument(
					"fit checkpoint selection requires validation",
				));
			}
			if !manager.saves_best_loss() {
				return Err(Error::invalid_argument(
					"fit checkpointing requires a manager that saves the lowest validation loss",
				));
			}
			checkpoint_optimizer(&mut self.optimizer)?;
		}
		if self.started
			|| self.config.initial_step != 0
			|| self.config.total_steps != 0
			|| self.config.steps_per_epoch != 0
			|| !self.config.epoch_steps.is_empty()
		{
			return Err(Error::failed_precondition(
				"fit requires a fresh training run without a manual step schedule",
			));
		}
		if epochs == 0 || batches_per_epoch == 0 {
			return Err(Error::invalid_argument(
				"fit requires at least one epoch and batch",
			));
		}
		let start_epoch = options.resume.as_ref().map_or(0, |resume| resume.epoch);
		let start_cursor = options
			.resume
			.as_ref()
			.map_or(0, |resume| resume.loader_cursor);
		if start_epoch >= epochs {
			return Err(Error::invalid_argument(
				"fit resume epoch is outside the total epoch budget",
			));
		}
		if start_cursor < 0 || start_cursor as u64 >= batches_per_epoch {
			return Err(Error::invalid_argument(
				"fit resume cursor is outside the epoch",
			));
		}
		let mut best_epoch = None;
		if let (Some((manager, _)), Some(criteria)) = (
			options.checkpoint.as_mut(),
			options.resume.as_ref().and_then(|resume| resume.checkpoint),
		) {
			if let Some(epoch) = criteria.best_epoch {
				if epoch == 0 {
					return Err(Error::invalid_argument(
						"fit resume best epoch must be one-based",
					));
				}
				if !criteria.best_metric.is_finite() {
					return Err(Error::invalid_argument(
						"fit resume best epoch requires a finite best metric",
					));
				}
			}
			manager.restore_best_metric(criteria.best_metric)?;
			best_epoch = criteria.best_epoch;
		}
		let _precision_scope = options
			.precision
			.map(|policy| policy.enter(self.runtime))
			.transpose()?;
		let effective_precision = PrecisionPolicy::current(self.runtime);
		if effective_precision.scaler_required && options.scaler.is_none() {
			return Err(Error::failed_precondition(
				"effective precision policy requires a GradScaler in TrainingFitOptions",
			));
		}
		let window = options.accumulation_steps.max(1);
		if window > 1 && accumulation_parameters.is_none() {
			return Err(Error::invalid_argument(
				"gradient accumulation requires the managed model fit — caller-driven batch sources do not expose the parameter set",
			));
		}
		if options.scaler.is_some() && accumulation_parameters.is_none() {
			return Err(Error::invalid_argument(
				"gradient scaling requires the managed model fit — caller-driven batch sources do not expose the parameter set",
			));
		}
		if let (Some(scaler), Some(scaler_state)) = (
			options.scaler.as_deref_mut(),
			options.resume.as_ref().and_then(|resume| resume.scaler),
		) {
			scaler.restore_state(scaler_state)?;
		}
		without_active_tape()?;
		// Lifecycle steps count applied updates, not microbatches: schedules
		// and budgets advance only when an update applies.
		let updates_per_epoch = batches_per_epoch.div_ceil(window);
		self.config.total_steps = epochs
			.checked_mul(updates_per_epoch)
			.ok_or_else(|| Error::resource_exhausted("fit step budget overflows u64"))?;
		self.config.steps_per_epoch = updates_per_epoch;
		self.sample_weighted_loss = true;
		self.disable_eager_resource_reuse();
		self.select_execution_mode(ExecutionMode::Eager)?;
		if self.runtime.has_pending_work() {
			self.runtime.checkpoint()?.wait()?;
		}

		let mut history = Vec::new();
		for epoch in start_epoch..epochs {
			let before = self.snapshot();
			let mut counts = Vec::new();
			let first_index = if epoch == start_epoch {
				start_cursor as u64
			} else {
				0
			};
			let mut index = first_index;
			while index < batches_per_epoch {
				let window_end = index.saturating_add(window).min(batches_per_epoch);
				let previous_step = self.step_count;
				if !self.wait_begin_step()? {
					self.step_count = previous_step;
					break;
				}
				let result = (|| {
					self.zero_grad();
					let mut total_samples = 0_u64;
					let mut window_loss: Option<Matrix> = None;
					let mut completion_loss: Option<Matrix> = None;
					for microbatch in index..window_end {
						let batch = batch_at(epoch, microbatch)?;
						let samples = batch_samples(&batch)?;
						if !self.runtime.owns_matrix(&batch.x) {
							return Err(Error::invalid_argument("batch belongs to another Runtime"));
						}
						self.config.batch_size = self.config.batch_size.max(samples);
						let tape = GradientTape::new();
						let step = step(&batch)?;
						validate_loss(&batch, &step.loss)?;
						// Above one microbatch per update the sample-mean
						// objective scales to a per-sample sum before backward,
						// so accumulated gradients carry exact sample
						// weighting regardless of how the window tails.
						let unscaled_backward_loss = if window > 1 {
							let factor = Matrix::new_from_slice_on(self.runtime, vec![], &[samples as f32])?;
							step.loss.mul(&factor)?
						} else {
							step.loss.clone()
						};
						let backward_loss = if let Some(scaler) = options.scaler.as_deref() {
							scaler.scale_loss(&unscaled_backward_loss)?
						} else {
							unscaled_backward_loss.clone()
						};
						tape.backward(&backward_loss)?;
						// Registered prediction metrics observe the batch before the
						// step completes — completion is what fires epoch-boundary
						// commits, so feeding afterwards would drop the final batch
						// of every epoch from its count.
						if let (Some(prediction), Some(target)) = (&step.prediction, batch.y.as_ref()) {
							for metric in &mut self.metrics {
								metric.observe_batch(prediction, target)?;
							}
						}
						total_samples = total_samples
							.checked_add(samples)
							.ok_or_else(|| Error::resource_exhausted("accumulated samples overflow u64"))?;
						if window > 1 {
							let detached = detach(&unscaled_backward_loss)?;
							window_loss = Some(match window_loss {
								None => detached,
								Some(acc) => acc.add(&detached)?,
							});
						} else {
							completion_loss = Some(step.loss.clone());
						}
						counts.extend(step.correct);
					}
					self.pending_step_samples = Some(total_samples);
					let completion_loss = if window > 1 {
						// The exact window denominator corrects the summed
						// gradients before the update — incomplete tail windows
						// stay exact rather than mean-of-means.
						#[allow(clippy::cast_precision_loss)]
						let inverse = Matrix::new_from_slice_on(self.runtime, vec![], &[1.0 / total_samples as f32])?;
						for parameter in accumulation_parameters.as_deref().unwrap_or(&[]) {
							if let Some(gradient) = parameter.gradient() {
								parameter.set_gradient(detach(&gradient.mul(&inverse)?)?);
							}
						}
						window_loss
							.expect("a window runs at least one microbatch")
							.mul(&inverse)?
					} else {
						completion_loss.expect("a window runs at least one microbatch")
					};
					if let Some(scaler) = options.scaler.as_deref_mut() {
						let check =
							scaler.unscale_gradients(accumulation_parameters.as_deref().unwrap_or(&[]))?;
						self.complete_step_scaled(&completion_loss, &check, scaler)?;
					} else {
						self.complete_step(&completion_loss)?;
					}
					Ok(())
				})();
				if let Err(error) = result {
					self.runtime.abort_pending_work();
					return self.fail(error);
				}
				index = window_end;
			}

			let after = self.snapshot();
			let batches = after.step_count() - before.step_count();
			let samples = after.total_samples() - before.total_samples();
			if batches > 0 {
				let start = std::time::Instant::now();
				let observation = (|| {
					let mut metrics: Vec<_> = self
						.metrics
						.iter()
						.map(|metric| (metric.name().to_owned(), metric.result()))
						.collect();
					if options.categorical_accuracy {
						metrics.push((
							"accuracy".to_owned(),
							count_correct(&counts)? as f64 / samples as f64,
						));
					}
					let expected_updates = (batches_per_epoch - first_index).div_ceil(window);
					let validation = if batches == expected_updates {
						options
							.validation
							.as_mut()
							.map(|evaluate| evaluate())
							.transpose()?
					} else {
						None
					};
					if let (Some(validation), Some((manager, model))) =
						(validation, options.checkpoint.as_mut())
					{
						let optimizer = checkpoint_optimizer(&mut self.optimizer)?;
						let improved = manager.is_better(validation.summary.loss);
						let next_best_metric = if improved {
							validation.summary.loss
						} else {
							manager.best_metric()
						};
						let next_best_epoch = if improved {
							Some(epoch + 1)
						} else {
							best_epoch
						};
						// Commits land on epoch boundaries: the next position is
						// the first batch of the following epoch. When a GradScaler
						// drives the fit, persist its dynamic scale and growth
						// counter alongside the checkpoint. Always persist the
						// incremental checkpoint and companion run state
						// (`force = true`) so non-improving epochs still record
						// current weights, optimizer state, RNG positions, and
						// preserved best criteria without overwriting master.
						let scaler_state = options
							.scaler
							.as_deref()
							.map(GradScaler::capture_state)
							.transpose()?;
						let run_state = crate::ml::RunState {
							epoch: epoch + 1,
							loader_cursor: 0,
							scaler: scaler_state,
							rng_states: capture_rng_states(*model)?,
							checkpoint: Some(CheckpointCriteriaState {
								best_metric: next_best_metric,
								best_epoch: next_best_epoch,
							}),
							early_stopping: None,
						};
						if manager.maybe_save_with_run_state(
							*model,
							optimizer,
							optimizer.step_count(),
							validation.summary.loss,
							true,
							&run_state,
						)? {
							best_epoch = Some(epoch + 1);
						}
					}
					Ok((metrics, validation))
				})();
				self.exclude_wall_time(start.elapsed());
				let (metrics, validation) = match observation {
					Ok(observation) => observation,
					Err(error) => return self.fail(error),
				};
				history.push(TrainingEpoch {
					epoch: epoch + 1,
					batches,
					samples,
					loss: after.epoch_mean_loss(),
					metrics,
					validation,
				});
			}
			if batches < (batches_per_epoch - first_index).div_ceil(window) || self.stop_requested() {
				break;
			}
		}
		if let (Some(best), Some((manager, model))) = (best_epoch, options.checkpoint)
			&& history.last().is_some_and(|epoch| epoch.epoch != best)
		{
			let start = std::time::Instant::now();
			let restore = checkpoint_optimizer(&mut self.optimizer)
				.and_then(|optimizer| manager.load_best_into(model, optimizer));
			self.exclude_wall_time(start.elapsed());
			if let Err(error) = restore {
				return self.fail(error);
			}
		}
		let capture_eligibility = self.capture_eligibility();
		Ok(TrainingHistory {
			epochs: history,
			snapshot: self.finish()?,
			best_epoch,
			precision: effective_precision,
			capture_eligibility,
		})
	}

	/// Evaluate a supervised model and return sample-weighted mean loss.
	///
	/// Resets the loader and restores the model's prior modes, even on error.
	/// An empty split returns [ValidationResult::default].
	///
	/// # Errors
	///
	/// Returns loader, model, loss, and observation errors. Evaluation requires
	/// no active gradient tape.
	pub fn evaluate(
		model: &dyn Module,
		loader: &mut DataLoader<'_>,
		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
	) -> Result<ValidationResult> {
		Self::evaluate_supervised(model, loader, &mut loss, false).map(|report| report.summary)
	}

	/// Evaluate a model with optional categorical accuracy.
	///
	/// Resets the loader and restores all prior module modes.
	///
	/// # Errors
	///
	/// Returns loader, model, loss, and metric errors.
	pub fn evaluate_supervised(
		model: &dyn Module,
		loader: &mut DataLoader<'_>,
		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		categorical_accuracy: bool,
	) -> Result<EvaluationReport> {
		let _mode = model.scoped_eval();
		Self::evaluate_prediction_batches(loader, |x| model.forward(x), loss, categorical_accuracy)
	}

	/// Evaluate a prediction function on a reset loader.
	///
	/// # Errors
	///
	/// Returns loader, model, loss, and metric errors.
	pub fn evaluate_prediction_batches(
		loader: &mut DataLoader<'_>,
		forward: impl FnMut(&Matrix) -> Result<Matrix>,
		loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		categorical_accuracy: bool,
	) -> Result<EvaluationReport> {
		loader.reset()?;
		Self::evaluate_predictions(
			std::iter::from_fn(|| loader.next_batch().transpose()),
			forward,
			loss,
			categorical_accuracy,
		)
	}

	/// Evaluate a supervised prediction function in caller-selected inference mode.
	///
	/// # Errors
	///
	/// Returns source, loss, prediction, and observation errors.
	pub fn evaluate_predictions(
		batches: impl IntoIterator<Item = Result<Batch>>,
		mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
		mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
		categorical_accuracy: bool,
	) -> Result<EvaluationReport> {
		Self::evaluate_batches(
			batches,
			|batch| supervised_step(batch, &mut forward, &mut loss, categorical_accuracy),
			categorical_accuracy,
		)
	}

	/// Evaluate a caller-defined objective on a stream of batches.
	///
	/// The caller selects inference mode for any model used in `step`. Losses
	/// must be scalar FP32 batch means. Reading each scalar waits for its work.
	///
	/// # Errors
	///
	/// Returns source, step, validation, or observation errors.
	pub fn evaluate_with(
		batches: impl IntoIterator<Item = Result<Batch>>,
		mut step: impl FnMut(&Batch) -> Result<Matrix>,
	) -> Result<ValidationResult> {
		Self::evaluate_batches(
			batches,
			|batch| {
				Ok(ManagedStep {
					loss: step(batch)?,
					correct: None,
					prediction: None,
				})
			},
			false,
		)
		.map(|report| report.summary)
	}

	fn evaluate_batches(
		batches: impl IntoIterator<Item = Result<Batch>>,
		mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
		categorical_accuracy: bool,
	) -> Result<EvaluationReport> {
		without_active_tape()?;
		let mut result = ValidationResult::new();
		let mut weighted_loss = 0.0;
		let mut counts = Vec::new();
		for batch in batches {
			let batch = batch?;
			let count = batch_samples(&batch)?;
			let step = step(&batch)?;
			validate_loss(&batch, &step.loss)?;
			weighted_loss += f64::from(metric::scalar_loss(&step.loss)?) * count as f64;
			counts.extend(step.correct);
			result.batches += 1;
			result.samples = result
				.samples
				.checked_add(count)
				.ok_or_else(|| Error::resource_exhausted("evaluation sample count overflows u64"))?;
		}
		if result.samples > 0 {
			result.loss = weighted_loss / result.samples as f64;
		}
		let correct = if categorical_accuracy {
			Some(count_correct(&counts)?)
		} else {
			None
		};
		Ok(EvaluationReport {
			summary: result,
			correct,
		})
	}
}

fn checkpoint_optimizer<'a>(
	optimizer: &'a mut TrainingOptimizer<'_>,
) -> Result<&'a mut dyn crate::ml::CheckpointOptimizer> {
	match optimizer {
		TrainingOptimizer::AdamW(optimizer) => Ok(*optimizer),
		TrainingOptimizer::Checkpointable(optimizer) => Ok(*optimizer),
		TrainingOptimizer::Eager(_) => Err(Error::failed_precondition(
			"fit requires a checkpointable optimizer when checkpointing is configured",
		)),
	}
}

fn count_correct(counts: &[Matrix]) -> Result<u64> {
	// Combine the device counts in bounded groups for host observation.
	let mut total = 0;
	for group in counts.chunks(128) {
		let values = crate::matrix::concat(group, 0)?.read::<u32>()?;
		total += values.into_iter().map(u64::from).sum::<u64>();
	}
	Ok(total)
}

fn supervised_step(
	batch: &Batch,
	forward: impl FnOnce(&Matrix) -> Result<Matrix>,
	loss: impl FnOnce(&Matrix, &Matrix) -> Result<Matrix>,
	categorical_accuracy: bool,
) -> Result<ManagedStep> {
	let target = batch
		.y
		.as_ref()
		.ok_or_else(|| Error::invalid_argument("supervised training and evaluation require labels"))?;
	let prediction = forward(&batch.x)?;
	let loss = loss(&prediction, target)?;
	let correct = if categorical_accuracy {
		if target.shape().len() != 1 {
			return Err(Error::invalid_argument(
				"categorical accuracy requires one target per sample",
			));
		}
		Some(prediction.categorical_accuracy_count(target)?)
	} else {
		None
	};
	Ok(ManagedStep {
		loss,
		correct,
		prediction: Some(prediction),
	})
}

fn batch_samples(batch: &Batch) -> Result<u64> {
	let count = batch.x.shape().first().copied().unwrap_or(0);
	if count == 0 {
		return Err(Error::invalid_argument(
			"a batch requires a nonempty leading sample axis",
		));
	}
	if let Some(target) = &batch.y
		&& (target.shape().first() != Some(&count) || !target.runtime().same_as(batch.x.runtime()))
	{
		return Err(Error::invalid_argument(
			"batch targets must match input samples and Runtime",
		));
	}
	Ok(count as u64)
}

fn validate_loss(batch: &Batch, loss: &Matrix) -> Result<()> {
	if loss.dtype() != DType::F32 || !loss.shape().is_empty() {
		return Err(Error::invalid_argument("batch loss must be an FP32 scalar"));
	}
	if !loss.runtime().same_as(batch.x.runtime()) {
		return Err(Error::invalid_argument(
			"batch loss and inputs must share a Runtime",
		));
	}
	Ok(())
}

fn without_active_tape() -> Result<()> {
	if recording_active() {
		return Err(Error::failed_precondition(
			"managed training and evaluation require no active GradientTape",
		));
	}
	Ok(())
}