Skip to main content

oa/ml/checkpoint/
manager.rs

1//! Native `.oam` checkpoint path, metric, and rotation policy.
2
3pub use crate::ml::types::CheckpointManagerConfig;
4use std::{
5	fs,
6	path::{Path, PathBuf},
7};
8
9use crate::{Error, Result, Runtime};
10
11use super::{
12	CheckpointProgress, load_checkpoint_at_step, load_checkpoint_on,
13	run_state::{RunState, load_run_state, save_run_state},
14	save_checkpoint_with_progress,
15};
16use crate::ml::model_file::ModelFile;
17use crate::ml::{CheckpointOptimizer, Module};
18
19impl Default for CheckpointManagerConfig {
20	fn default() -> Self {
21		Self {
22			directory: PathBuf::from("var/model/dev"),
23			model_name: "Module".to_owned(),
24			context: String::new(),
25			max_keep: 5,
26			save_best: true,
27			metric_name: "loss".to_owned(),
28			lower_is_better: true,
29		}
30	}
31}
32
33#[derive(Clone, Debug)]
34struct SavedCheckpoint {
35	path: PathBuf,
36	step: u64,
37}
38
39/// Stateful checkpoint selection and bounded incremental-retention policy.
40pub struct CheckpointManager<'runtime> {
41	runtime: &'runtime Runtime,
42	config: CheckpointManagerConfig,
43	best_metric: f64,
44	saved: Vec<SavedCheckpoint>,
45}
46
47impl<'runtime> CheckpointManager<'runtime> {
48	/// Construct a manager around the one execution owner.
49	///
50	/// # Errors
51	///
52	/// Returns an error when a filename component or metric name is invalid.
53	pub fn new(runtime: &'runtime Runtime, config: CheckpointManagerConfig) -> Result<Self> {
54		validate_component(&config.model_name, "model name")?;
55		if !config.context.is_empty() {
56			validate_component(&config.context, "checkpoint context")?;
57		}
58		validate_component(&config.metric_name, "checkpoint metric name")?;
59		let best_metric = if config.lower_is_better {
60			f64::INFINITY
61		} else {
62			f64::NEG_INFINITY
63		};
64		Ok(Self {
65			runtime,
66			config,
67			best_metric,
68			saved: Vec::new(),
69		})
70	}
71
72	pub(crate) const fn saves_best_loss(&self) -> bool {
73		self.config.save_best && self.config.lower_is_better
74	}
75
76	/// Return the directory containing master and incremental checkpoints.
77	pub fn model_directory(&self) -> PathBuf {
78		self.config.directory.join(&self.config.model_name)
79	}
80
81	/// Return the incremental checkpoint directory.
82	pub fn incremental_directory(&self) -> PathBuf {
83		let name = if self.config.context.is_empty() {
84			"checkpoint".to_owned()
85		} else {
86			format!("checkpoint_{}", self.config.context)
87		};
88		self.model_directory().join(name)
89	}
90
91	/// Return the master/best checkpoint path.
92	pub fn master_path(&self) -> PathBuf {
93		self
94			.model_directory()
95			.join(format!("{}.oam", self.config.model_name))
96	}
97
98	/// Return whether `metric` improves the currently retained best value.
99	pub fn is_better(&self, metric: f64) -> bool {
100		if self.config.lower_is_better {
101			metric < self.best_metric
102		} else {
103			metric > self.best_metric
104		}
105	}
106
107	/// Return the best metric admitted in this manager session.
108	pub const fn best_metric(&self) -> f64 {
109		self.best_metric
110	}
111
112	/// Restore historical best-metric selection state from an exact-resume
113	/// checkpoint companion.
114	///
115	/// Rejects NaN and an infinite sentinel whose sign disagrees with
116	/// `config.lower_is_better`.
117	///
118	/// # Errors
119	///
120	/// Returns an error when `best_metric` is NaN or carries the opposite
121	/// infinity sentinel for this manager's improvement direction.
122	pub fn restore_best_metric(&mut self, best_metric: f64) -> Result<()> {
123		if best_metric.is_nan()
124			|| (self.config.lower_is_better && best_metric == f64::NEG_INFINITY)
125			|| (!self.config.lower_is_better && best_metric == f64::INFINITY)
126		{
127			return Err(Error::invalid_argument(
128				"restored checkpoint best metric is invalid for improvement direction",
129			));
130		}
131		self.best_metric = best_metric;
132		Ok(())
133	}
134
135	/// Return the configured metric name.
136	pub fn metric_name(&self) -> &str {
137		&self.config.metric_name
138	}
139
140	/// Save an incremental checkpoint and update the master file on improvement.
141	///
142	/// When `force` is false, a non-improving metric performs no write. When it is
143	/// true, the incremental file is still written but the master changes only on
144	/// improvement.
145	///
146	/// # Errors
147	///
148	/// Returns an error for non-finite metrics, optimizer/progress mismatch,
149	/// serialization, directory creation, rotation, or filesystem failure.
150	pub fn maybe_save(
151		&mut self,
152		model: &dyn Module,
153		optimizer: &dyn CheckpointOptimizer,
154		step: u64,
155		metric: f64,
156		force: bool,
157	) -> Result<bool> {
158		validate_metric_step(optimizer, step, metric)?;
159		let improved = self.is_better(metric);
160		if !improved && !force {
161			return Ok(false);
162		}
163		self.save_incremental(model, optimizer, step, metric, None)?;
164		self.finish_maybe_save(model, optimizer, step, metric, improved)
165	}
166
167	/// `maybe_save` additionally committing exact-resume run state beside the
168	/// incremental checkpoint; see [`Self::save_incremental_with_run_state`].
169	///
170	/// # Errors
171	///
172	/// Returns the errors of [`Self::maybe_save`] plus run-state commit failure.
173	pub fn maybe_save_with_run_state(
174		&mut self,
175		model: &dyn Module,
176		optimizer: &dyn CheckpointOptimizer,
177		step: u64,
178		metric: f64,
179		force: bool,
180		run_state: &RunState,
181	) -> Result<bool> {
182		validate_metric_step(optimizer, step, metric)?;
183		let improved = self.is_better(metric);
184		if !improved && !force {
185			return Ok(false);
186		}
187		self.save_incremental_with_run_state(model, optimizer, step, metric, None, Some(run_state))?;
188		self.finish_maybe_save(model, optimizer, step, metric, improved)
189	}
190
191	fn finish_maybe_save(
192		&mut self,
193		model: &dyn Module,
194		optimizer: &dyn CheckpointOptimizer,
195		step: u64,
196		metric: f64,
197		improved: bool,
198	) -> Result<bool> {
199		if improved {
200			if self.config.save_best {
201				fs::create_dir_all(self.model_directory())
202					.map_err(|source| Error::io("create checkpoint model directory", source))?;
203				save_checkpoint_with_progress(
204					&self.master_path(),
205					model,
206					optimizer,
207					Some(self.progress(step, metric, &self.config.metric_name)),
208				)?;
209			}
210			self.best_metric = metric;
211		}
212		Ok(improved)
213	}
214
215	/// Save a resumable incremental checkpoint without changing best selection.
216	///
217	/// # Errors
218	///
219	/// Returns an error for invalid metric/progress state, serialization,
220	/// directory creation, rotation, or filesystem failure.
221	pub fn save_incremental(
222		&mut self,
223		model: &dyn Module,
224		optimizer: &dyn CheckpointOptimizer,
225		step: u64,
226		metric: f64,
227		metric_name: Option<&str>,
228	) -> Result<PathBuf> {
229		self.save_incremental_with_run_state(model, optimizer, step, metric, metric_name, None)
230	}
231
232	/// Save a resumable incremental checkpoint together with its exact-resume
233	/// run state. The `.oam` artifact writes first and the run state then
234	/// commits atomically beside it as a same-stem `.runstate` sibling;
235	/// rotation removes the pair together, so a retained checkpoint never
236	/// outlives its training-loop position. A checkpoint whose sibling is
237	/// absent or corrupt fails the resume contract clearly at load time
238	/// rather than guessing a partial position.
239	///
240	/// # Errors
241	///
242	/// Returns the errors of [`Self::save_incremental`] plus run-state
243	/// serialization and commit failures.
244	pub fn save_incremental_with_run_state(
245		&mut self,
246		model: &dyn Module,
247		optimizer: &dyn CheckpointOptimizer,
248		step: u64,
249		metric: f64,
250		metric_name: Option<&str>,
251		run_state: Option<&RunState>,
252	) -> Result<PathBuf> {
253		validate_metric_step(optimizer, step, metric)?;
254		let metric_name = metric_name.unwrap_or(&self.config.metric_name);
255		validate_component(metric_name, "checkpoint metric name")?;
256		let directory = self.incremental_directory();
257		fs::create_dir_all(&directory)
258			.map_err(|source| Error::io("create incremental checkpoint directory", source))?;
259		let filename = self.filename(step, metric, metric_name);
260		let path = directory.join(filename);
261		save_checkpoint_with_progress(
262			&path,
263			model,
264			optimizer,
265			Some(self.progress(step, metric, metric_name)),
266		)?;
267		if let Some(run_state) = run_state {
268			save_run_state(&run_state_path(&path), run_state)?;
269		}
270		self.saved.retain(|saved| saved.path != path);
271		self.saved.push(SavedCheckpoint {
272			path: path.clone(),
273			step,
274		});
275		self.rotate()?;
276		Ok(path)
277	}
278
279	/// Restore the master/best checkpoint into existing owners.
280	///
281	/// # Errors
282	///
283	/// Returns the native load, validation, allocation, or filesystem error.
284	pub fn load_best_into(
285		&self,
286		model: &dyn Module,
287		optimizer: &mut dyn CheckpointOptimizer,
288	) -> Result<()> {
289		load_checkpoint_on(self.runtime, self.master_path(), model, optimizer)
290	}
291
292	/// Restore the highest-step incremental checkpoint into existing owners.
293	///
294	/// The manager prefers files recorded in this session and otherwise scans its
295	/// incremental directory using the same strict filename grammar it writes.
296	/// The returned value is the exact completed step restored into the optimizer.
297	///
298	/// # Errors
299	///
300	/// Returns an error when no checkpoint exists or loading fails.
301	pub fn load_latest_into(
302		&self,
303		model: &dyn Module,
304		optimizer: &mut dyn CheckpointOptimizer,
305	) -> Result<u64> {
306		let path = self.latest_path()?.ok_or_else(|| {
307			Error::failed_precondition(format!(
308				"no checkpoints in {}",
309				self.incremental_directory().display()
310			))
311		})?;
312		let step = parse_step(&path)
313			.ok_or_else(|| Error::failed_precondition("latest checkpoint has no valid step segment"))?;
314		load_checkpoint_at_step(self.runtime, &path, model, optimizer, step)?;
315		Ok(step)
316	}
317
318	/// Restore the latest incremental state and recover historical best-metric
319	/// selection from the master checkpoint when it exists.
320	///
321	/// This joins model, optimizer, completed step, and best-checkpoint policy at
322	/// one restart boundary. A master file written for another metric or ordering
323	/// policy is rejected instead of silently resetting selection history.
324	///
325	/// # Errors
326	///
327	/// Returns the same errors as [`Self::load_latest_into`], plus malformed or
328	/// incompatible master progress metadata.
329	pub fn resume_latest_into(
330		&mut self,
331		model: &dyn Module,
332		optimizer: &mut dyn CheckpointOptimizer,
333	) -> Result<u64> {
334		let master = self.master_path();
335		let restored_best = if master.is_file() {
336			let file = ModelFile::load(&master)?;
337			if file.progress.metric_name != self.config.metric_name
338				|| file.progress.lower_is_better != self.config.lower_is_better
339				|| !file.progress.best_metric.is_finite()
340			{
341				return Err(Error::invalid_argument(
342					"master checkpoint progress does not match resume policy",
343				));
344			}
345			Some(f64::from(file.progress.best_metric))
346		} else {
347			None
348		};
349		let step = self.load_latest_into(model, optimizer)?;
350		if let Some(best) = restored_best {
351			self.best_metric = best;
352		}
353		Ok(step)
354	}
355
356	fn progress(&self, step: u64, metric: f64, metric_name: &str) -> CheckpointProgress {
357		CheckpointProgress {
358			step,
359			metric,
360			metric_name: metric_name.to_owned(),
361			lower_is_better: self.config.lower_is_better,
362		}
363	}
364
365	fn filename(&self, step: u64, metric: f64, metric_name: &str) -> String {
366		if self.config.context.is_empty() {
367			format!(
368				"{}_step{step}_{metric_name}{metric:.2}.oam",
369				self.config.model_name
370			)
371		} else {
372			format!(
373				"{}_{}_step{step}_{metric_name}{metric:.2}.oam",
374				self.config.model_name, self.config.context
375			)
376		}
377	}
378
379	fn rotate(&mut self) -> Result<()> {
380		if self.config.max_keep == 0 || self.saved.len() <= self.config.max_keep {
381			return Ok(());
382		}
383		self.saved.sort_unstable_by(|left, right| {
384			right
385				.step
386				.cmp(&left.step)
387				.then_with(|| right.path.cmp(&left.path))
388		});
389		while self.saved.len() > self.config.max_keep {
390			let removed = self.saved.pop().expect("retention excess exists");
391			if let Err(source) = fs::remove_file(&removed.path) {
392				self.saved.push(removed);
393				return Err(Error::io("remove rotated checkpoint", source));
394			}
395			let sibling = run_state_path(&removed.path);
396			if sibling.exists() {
397				fs::remove_file(&sibling)
398					.map_err(|source| Error::io("remove rotated run state", source))?;
399			}
400		}
401		Ok(())
402	}
403
404	/// Load the run state committed beside the latest incremental checkpoint.
405	///
406	/// # Errors
407	///
408	/// Returns an error when no incremental checkpoint exists, its sibling
409	/// run state is absent, or the state fails its format contract.
410	pub fn load_latest_run_state(&self) -> Result<RunState> {
411		let path = self
412			.latest_path()?
413			.ok_or_else(|| Error::failed_precondition("no incremental checkpoint exists"))?;
414		load_run_state(&run_state_path(&path))
415	}
416
417	fn latest_path(&self) -> Result<Option<PathBuf>> {
418		if let Some(saved) = self.saved.iter().max_by_key(|saved| saved.step) {
419			return Ok(Some(saved.path.clone()));
420		}
421		let directory = self.incremental_directory();
422		let entries = match fs::read_dir(&directory) {
423			Ok(entries) => entries,
424			Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
425			Err(source) => return Err(Error::io("scan checkpoint directory", source)),
426		};
427		let mut latest: Option<(u64, PathBuf)> = None;
428		for entry in entries {
429			let entry = entry.map_err(|source| Error::io("read checkpoint directory", source))?;
430			let path = entry.path();
431			if path.extension().and_then(|value| value.to_str()) != Some("oam") {
432				continue;
433			}
434			let Some(step) = parse_step(&path) else {
435				continue;
436			};
437			if latest.as_ref().is_none_or(|(current, _)| step > *current) {
438				latest = Some((step, path));
439			}
440		}
441		Ok(latest.map(|(_, path)| path))
442	}
443}
444
445fn validate_component(value: &str, name: &'static str) -> Result<()> {
446	if value.is_empty()
447		|| value == "."
448		|| value == ".."
449		|| !value
450			.bytes()
451			.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
452	{
453		return Err(Error::invalid_argument(format!(
454			"{name} must be a nonempty portable filename component"
455		)));
456	}
457	Ok(())
458}
459
460fn validate_metric_step(optimizer: &dyn CheckpointOptimizer, step: u64, metric: f64) -> Result<()> {
461	if !metric.is_finite() || !(metric as f32).is_finite() {
462		return Err(Error::invalid_argument("checkpoint metric must be finite"));
463	}
464	if optimizer.step_count() != step {
465		return Err(Error::invalid_argument(
466			"checkpoint step does not match optimizer state",
467		));
468	}
469	Ok(())
470}
471
472fn parse_step(path: &Path) -> Option<u64> {
473	let stem = path.file_stem()?.to_str()?;
474	let marker = stem.rfind("_step")?;
475	let digits = stem[marker + 5..].split('_').next()?;
476	(!digits.is_empty()).then(|| digits.parse().ok()).flatten()
477}
478
479/// Same-stem `.runstate` sibling of a checkpoint artifact path.
480fn run_state_path(checkpoint: &Path) -> PathBuf {
481	checkpoint.with_extension("runstate")
482}