Skip to main content

oa/ml/training/callback/
validation.rs

1//! Completed-boundary validation callback.
2//!
3//! Port provenance: `oa/ml/callbacks.h` (`CbValidation`).
4
5pub use crate::ml::types::ValidationResult;
6use std::{
7	cell::Cell,
8	rc::Rc,
9	time::{Duration, Instant},
10};
11
12use crate::{Error, Result};
13
14use super::super::{TrainingCallback, TrainingCallbackContext, TrainingControl, TrainingSnapshot};
15use super::write_stdout;
16
17impl Default for ValidationResult {
18	fn default() -> Self {
19		Self {
20			loss: f64::NAN,
21			batches: 0,
22			samples: 0,
23		}
24	}
25}
26
27/// Cloneable observation handle for the latest completed validation loss.
28///
29/// Clones share one thread-affine value so checkpoint, summary, and early-stop
30/// callbacks can observe the result without owning or rerunning validation.
31#[derive(Clone)]
32pub struct ValidationMetric {
33	name: Rc<str>,
34	value: Rc<Cell<Option<f64>>>,
35}
36
37impl ValidationMetric {
38	fn new(name: String) -> Self {
39		Self {
40			name: Rc::from(name),
41			value: Rc::new(Cell::new(None)),
42		}
43	}
44
45	/// Return the stable display name.
46	pub fn name(&self) -> &str {
47		&self.name
48	}
49
50	/// Return the latest finite validation loss.
51	pub fn value(&self) -> Option<f64> {
52		self.value.get()
53	}
54
55	/// Return the latest validation loss, or NaN before a valid evaluation.
56	pub fn result(&self) -> f64 {
57		self.value().unwrap_or(f64::NAN)
58	}
59
60	fn replace(&self, value: Option<f64>) {
61		self.value.set(value);
62	}
63}
64
65/// Runs application-owned inference validation at completed lifecycle boundaries.
66///
67/// Epoch-based training evaluates once at every epoch end. Step-only training
68/// evaluates at each non-zero configured interval and once at train end when
69/// the final step was not already evaluated. Evaluation wall time is excluded
70/// from training throughput and the callback never submits work on its own.
71pub struct ValidationCallback<'eval> {
72	evaluate: Box<dyn FnMut(TrainingSnapshot) -> Result<ValidationResult> + 'eval>,
73	metric: ValidationMetric,
74	step_interval: u64,
75	last_result: ValidationResult,
76	last_duration: Duration,
77	last_eval_step: Option<u64>,
78}
79
80impl<'eval> ValidationCallback<'eval> {
81	/// Construct a validation callback.
82	///
83	/// `step_interval` applies only to step-only training. Zero disables periodic
84	/// evaluation while retaining the final train-end evaluation.
85	///
86	/// # Errors
87	///
88	/// Returns an error when `metric_name` is empty.
89	pub fn new(
90		evaluate: impl FnMut(TrainingSnapshot) -> Result<ValidationResult> + 'eval,
91		metric_name: impl Into<String>,
92		step_interval: u64,
93	) -> Result<Self> {
94		let metric_name = metric_name.into();
95		if metric_name.is_empty() {
96			return Err(Error::invalid_argument(
97				"validation metric name must not be empty",
98			));
99		}
100		Ok(Self {
101			evaluate: Box::new(evaluate),
102			metric: ValidationMetric::new(metric_name),
103			step_interval,
104			last_result: ValidationResult::default(),
105			last_duration: Duration::ZERO,
106			last_eval_step: None,
107		})
108	}
109
110	/// Clone the shared metric observation handle.
111	pub fn metric(&self) -> ValidationMetric {
112		self.metric.clone()
113	}
114
115	/// Return the most recent raw evaluation result.
116	pub const fn last_result(&self) -> ValidationResult {
117		self.last_result
118	}
119
120	/// Return the wall duration of the most recent evaluation.
121	pub const fn last_duration(&self) -> Duration {
122		self.last_duration
123	}
124
125	fn run(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<()> {
126		let snapshot = context.snapshot();
127		let begin = Instant::now();
128		let result = (self.evaluate)(snapshot);
129		let duration = begin.elapsed();
130		context.exclude_wall_time(duration);
131		let result = result?;
132
133		self.last_result = result;
134		self.last_duration = duration;
135		self.last_eval_step = Some(snapshot.step_count());
136		let value = (result.loss.is_finite() && result.batches > 0).then_some(result.loss);
137		self.metric.replace(value);
138
139		if let Some(loss) = value {
140			let name = self.metric.name().to_owned();
141			context.commit_metric("validation", &name, loss);
142			write_stdout(&format!(
143				"Validation: {} {:.6} · {} batches · {} samples · {:.2}s\n",
144				self.metric.name(),
145				loss,
146				result.batches,
147				result.samples,
148				duration.as_secs_f64(),
149			))
150		} else {
151			write_stdout(&format!(
152				"Validation: {} n/a · {:.2}s\n",
153				self.metric.name(),
154				duration.as_secs_f64(),
155			))
156		}
157	}
158}
159
160impl TrainingCallback for ValidationCallback<'_> {
161	fn on_step_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
162		let snapshot = context.snapshot();
163		if snapshot.total_epochs() == 0
164			&& self.step_interval > 0
165			&& snapshot.step_count().is_multiple_of(self.step_interval)
166		{
167			self.run(context)?;
168		}
169		Ok(TrainingControl::Continue)
170	}
171
172	fn on_epoch_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
173		self.run(context)?;
174		Ok(TrainingControl::Continue)
175	}
176
177	fn on_train_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
178		let snapshot = context.snapshot();
179		if snapshot.total_epochs() == 0 && self.last_eval_step != Some(snapshot.step_count()) {
180			self.run(context)?;
181		}
182		Ok(TrainingControl::Continue)
183	}
184}