Skip to main content

oa/ml/training/callback/
checkpoint.rs

1//! Native `.oam` checkpoint callback.
2//!
3//! Port provenance: `oa/ml/callbacks.h` (`CbCheckpoint`).
4
5use std::time::Instant;
6
7use crate::{
8	Error, Result,
9	ml::{CheckpointCriteriaState, CheckpointManager, Module, RunState},
10};
11
12use super::super::{TrainingCallback, TrainingCallbackContext, TrainingControl, TrainingSnapshot};
13use super::{ValidationMetric, write_stdout};
14
15type RunStateProvider<'owner> = Box<dyn FnMut(TrainingSnapshot) -> Result<RunState> + 'owner>;
16
17/// Epoch, interval, best-model, and restore-best checkpoint policy.
18pub struct CheckpointCallback<'owner, 'runtime> {
19	manager: &'owner mut CheckpointManager<'runtime>,
20	model: &'owner dyn Module,
21	save_every: u64,
22	validation_metric: Option<ValidationMetric>,
23	committed_monitor: Option<(String, String)>,
24	run_state_provider: Option<RunStateProvider<'owner>>,
25	restore_best: bool,
26	verbose: bool,
27	have_best: bool,
28	best_epoch: u64,
29	last_epoch: u64,
30}
31
32impl<'owner, 'runtime> CheckpointCallback<'owner, 'runtime> {
33	/// Borrow the checkpoint manager and model for one training lifecycle.
34	pub fn new(manager: &'owner mut CheckpointManager<'runtime>, model: &'owner dyn Module) -> Self {
35		Self {
36			manager,
37			model,
38			save_every: 0,
39			validation_metric: None,
40			committed_monitor: None,
41			run_state_provider: None,
42			restore_best: true,
43			verbose: true,
44			have_best: false,
45			best_epoch: 0,
46			last_epoch: 0,
47		}
48	}
49
50	/// Add a resumable mid-epoch checkpoint every `steps` completed steps.
51	///
52	/// Zero disables interval checkpoints.
53	pub fn set_save_every(&mut self, steps: u64) {
54		self.save_every = steps;
55	}
56
57	/// Select a preceding validation callback's completed metric.
58	pub fn set_validation_metric(&mut self, metric: ValidationMetric) {
59		self.validation_metric = Some(metric);
60	}
61
62	/// Monitor the latest value committed to the shared history bus under
63	/// `split`/`name` for best-epoch selection.
64	///
65	/// The committing callback must register before the checkpoint callback so
66	/// the value exists at the boundary; a missing committed value reads as
67	/// not-a-number and never improves the best epoch.
68	pub fn set_committed_monitor(&mut self, split: impl Into<String>, name: impl Into<String>) {
69		self.committed_monitor = Some((split.into(), name.into()));
70	}
71
72	/// Supply a `.runstate` provider committed atomically beside every
73	/// mid-epoch and epoch-boundary incremental checkpoint.
74	///
75	/// When the returned [`RunState`] leaves `checkpoint` as `None`, the
76	/// callback populates it with the post-comparison [`CheckpointCriteriaState`]
77	/// before writing the companion file.
78	pub fn set_run_state_provider(
79		&mut self,
80		provider: impl FnMut(TrainingSnapshot) -> Result<RunState> + 'owner,
81	) {
82		self.run_state_provider = Some(Box::new(provider));
83	}
84
85	/// Enable or disable restoring the best epoch at training end.
86	pub fn set_restore_best(&mut self, restore: bool) {
87		self.restore_best = restore;
88	}
89
90	/// Enable or suppress checkpoint status output.
91	pub fn set_verbose(&mut self, verbose: bool) {
92		self.verbose = verbose;
93	}
94
95	/// Return the one-based best epoch observed by this callback.
96	pub const fn best_epoch(&self) -> u64 {
97		self.best_epoch
98	}
99
100	/// Capture best-metric and best-epoch criteria for `.runstate` persistence.
101	pub const fn capture_state(&self) -> CheckpointCriteriaState {
102		CheckpointCriteriaState {
103			best_metric: self.manager.best_metric(),
104			best_epoch: if self.have_best {
105				Some(self.best_epoch)
106			} else {
107				None
108			},
109		}
110	}
111
112	/// Restore best-metric and best-epoch criteria from a `.runstate` companion.
113	///
114	/// # Errors
115	///
116	/// Returns an error when `best_epoch` is `Some(0)`, `best_epoch` is set
117	/// alongside a non-finite `best_metric`, or `best_metric` disagrees with
118	/// the manager's improvement direction.
119	pub fn restore_state(&mut self, state: CheckpointCriteriaState) -> Result<()> {
120		if let Some(best_epoch) = state.best_epoch {
121			if best_epoch == 0 {
122				return Err(Error::invalid_argument(
123					"restored checkpoint best epoch must be one-based",
124				));
125			}
126			if !state.best_metric.is_finite() {
127				return Err(Error::invalid_argument(
128					"restored checkpoint best epoch requires a finite best metric",
129				));
130			}
131		}
132		self.manager.restore_best_metric(state.best_metric)?;
133		match state.best_epoch {
134			Some(best_epoch) => {
135				self.have_best = true;
136				self.best_epoch = best_epoch;
137			}
138			None => {
139				self.have_best = false;
140				self.best_epoch = 0;
141			}
142		}
143		Ok(())
144	}
145
146	fn metric(&self, context: &TrainingCallbackContext<'_>) -> f64 {
147		if let Some((split, name)) = &self.committed_monitor {
148			return context.latest_committed(split, name).unwrap_or(f64::NAN);
149		}
150		let snapshot = context.snapshot();
151		self.validation_metric.as_ref().map_or_else(
152			|| {
153				if snapshot.total_epochs() > 0 {
154					snapshot.epoch_mean_loss()
155				} else {
156					snapshot.training_mean_loss()
157				}
158			},
159			ValidationMetric::result,
160		)
161	}
162
163	fn metric_name(&self) -> &str {
164		self
165			.validation_metric
166			.as_ref()
167			.map_or_else(|| self.manager.metric_name(), ValidationMetric::name)
168	}
169}
170
171impl TrainingCallback for CheckpointCallback<'_, '_> {
172	fn on_step_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
173		let snapshot = context.snapshot();
174		if self.save_every == 0
175			|| snapshot.is_epoch_boundary()
176			|| !snapshot.step_count().is_multiple_of(self.save_every)
177		{
178			return Ok(TrainingControl::Continue);
179		}
180		let metric = f64::from(snapshot.last_loss().unwrap_or(f32::NAN));
181		if self.verbose {
182			write_stdout(&format!(
183				"\nStep {}: loss = {metric:.6} — saving resumable checkpoint\n",
184				snapshot.step_count()
185			))?;
186		}
187		let criteria = self.capture_state();
188		let run_state = match self.run_state_provider.as_mut() {
189			Some(provider) => {
190				let mut state = provider(snapshot)?;
191				if state.checkpoint.is_none() {
192					state.checkpoint = Some(criteria);
193				}
194				Some(state)
195			}
196			None => None,
197		};
198		let start = Instant::now();
199		let result = self.manager.save_incremental_with_run_state(
200			self.model,
201			context.checkpoint_optimizer()?,
202			snapshot.step_count(),
203			metric,
204			Some("loss"),
205			run_state.as_ref(),
206		);
207		context.exclude_wall_time(start.elapsed());
208		result?;
209		Ok(TrainingControl::Continue)
210	}
211
212	fn on_epoch_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
213		let snapshot = context.snapshot();
214		let metric = self.metric(context);
215		let metric_name = self.metric_name().to_owned();
216		let improved = self.manager.is_better(metric);
217		let previous = self.manager.best_metric();
218		if self.verbose {
219			let message = if improved && !self.have_best {
220				format!(
221					"\nEpoch {}: {metric_name} = {metric:.6} — saving model\n",
222					snapshot.epoch()
223				)
224			} else if improved {
225				format!(
226					"\nEpoch {}: {metric_name} improved from {previous:.6} to {metric:.6} — saving model\n",
227					snapshot.epoch()
228				)
229			} else {
230				format!(
231					"\nEpoch {}: {metric_name} did not improve from {previous:.6}\n",
232					snapshot.epoch()
233				)
234			};
235			write_stdout(&message)?;
236		}
237		self.last_epoch = snapshot.epoch();
238		let next_criteria = if improved {
239			CheckpointCriteriaState {
240				best_metric: metric,
241				best_epoch: Some(snapshot.epoch().max(1)),
242			}
243		} else {
244			self.capture_state()
245		};
246		let run_state = match self.run_state_provider.as_mut() {
247			Some(provider) => {
248				let mut state = provider(snapshot)?;
249				if state.checkpoint.is_none() {
250					state.checkpoint = Some(next_criteria);
251				}
252				Some(state)
253			}
254			None => None,
255		};
256		let start = Instant::now();
257		let result = if let Some(run_state) = run_state.as_ref() {
258			self.manager.maybe_save_with_run_state(
259				self.model,
260				context.checkpoint_optimizer()?,
261				snapshot.step_count(),
262				metric,
263				true,
264				run_state,
265			)
266		} else {
267			self.manager.maybe_save(
268				self.model,
269				context.checkpoint_optimizer()?,
270				snapshot.step_count(),
271				metric,
272				true,
273			)
274		};
275		context.exclude_wall_time(start.elapsed());
276		if result? {
277			self.have_best = true;
278			self.best_epoch = snapshot.epoch();
279		}
280		Ok(TrainingControl::Continue)
281	}
282
283	fn on_train_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
284		let snapshot = context.snapshot();
285		if snapshot.total_epochs() == 0 {
286			let metric = self.metric(context);
287			let start = Instant::now();
288			let result = self.manager.maybe_save(
289				self.model,
290				context.checkpoint_optimizer()?,
291				snapshot.step_count(),
292				metric,
293				false,
294			);
295			context.exclude_wall_time(start.elapsed());
296			result?;
297			return Ok(TrainingControl::Continue);
298		}
299		if !self.restore_best {
300			if !snapshot.is_epoch_boundary() {
301				let metric = self.metric(context);
302				let improved = self.manager.is_better(metric);
303				let next_criteria = if improved {
304					CheckpointCriteriaState {
305						best_metric: metric,
306						best_epoch: Some(snapshot.epoch().max(1)),
307					}
308				} else {
309					self.capture_state()
310				};
311				let run_state = match self.run_state_provider.as_mut() {
312					Some(provider) => {
313						let mut state = provider(snapshot)?;
314						if state.checkpoint.is_none() {
315							state.checkpoint = Some(next_criteria);
316						}
317						Some(state)
318					}
319					None => None,
320				};
321				let start = Instant::now();
322				let result = if let Some(run_state) = run_state.as_ref() {
323					self.manager.maybe_save_with_run_state(
324						self.model,
325						context.checkpoint_optimizer()?,
326						snapshot.step_count(),
327						metric,
328						true,
329						run_state,
330					)
331				} else {
332					self.manager.maybe_save(
333						self.model,
334						context.checkpoint_optimizer()?,
335						snapshot.step_count(),
336						metric,
337						true,
338					)
339				};
340				context.exclude_wall_time(start.elapsed());
341				result?;
342			}
343			return Ok(TrainingControl::Continue);
344		}
345		if !self.have_best || (snapshot.is_epoch_boundary() && self.best_epoch == self.last_epoch) {
346			return Ok(TrainingControl::Continue);
347		}
348		let start = Instant::now();
349		let result = self
350			.manager
351			.load_best_into(self.model, context.checkpoint_optimizer()?);
352		context.exclude_wall_time(start.elapsed());
353		result?;
354		if self.verbose {
355			write_stdout(&format!(
356				"Restoring model weights from the end of the best epoch: {} ({} {:.6})\n",
357				self.best_epoch,
358				self.metric_name(),
359				self.manager.best_metric()
360			))?;
361		}
362		Ok(TrainingControl::Continue)
363	}
364}