oarust 0.20.1

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
//! Native `.oam` checkpoint path, metric, and rotation policy.

pub use crate::ml::types::CheckpointManagerConfig;
use std::{
	fs,
	path::{Path, PathBuf},
};

use crate::{Error, Result, Runtime};

use super::{
	CheckpointProgress, load_checkpoint_at_step, load_checkpoint_on,
	run_state::{RunState, load_run_state, save_run_state},
	save_checkpoint_with_progress,
};
use crate::ml::model_file::ModelFile;
use crate::ml::{CheckpointOptimizer, Module};

impl Default for CheckpointManagerConfig {
	fn default() -> Self {
		Self {
			directory: PathBuf::from("var/model/dev"),
			model_name: "Module".to_owned(),
			context: String::new(),
			max_keep: 5,
			save_best: true,
			metric_name: "loss".to_owned(),
			lower_is_better: true,
		}
	}
}

#[derive(Clone, Debug)]
struct SavedCheckpoint {
	path: PathBuf,
	step: u64,
}

/// Stateful checkpoint selection and bounded incremental-retention policy.
pub struct CheckpointManager<'runtime> {
	runtime: &'runtime Runtime,
	config: CheckpointManagerConfig,
	best_metric: f64,
	saved: Vec<SavedCheckpoint>,
}

impl<'runtime> CheckpointManager<'runtime> {
	/// Construct a manager around the one execution owner.
	///
	/// # Errors
	///
	/// Returns an error when a filename component or metric name is invalid.
	pub fn new(runtime: &'runtime Runtime, config: CheckpointManagerConfig) -> Result<Self> {
		validate_component(&config.model_name, "model name")?;
		if !config.context.is_empty() {
			validate_component(&config.context, "checkpoint context")?;
		}
		validate_component(&config.metric_name, "checkpoint metric name")?;
		let best_metric = if config.lower_is_better {
			f64::INFINITY
		} else {
			f64::NEG_INFINITY
		};
		Ok(Self {
			runtime,
			config,
			best_metric,
			saved: Vec::new(),
		})
	}

	pub(crate) const fn saves_best_loss(&self) -> bool {
		self.config.save_best && self.config.lower_is_better
	}

	/// Return the directory containing master and incremental checkpoints.
	pub fn model_directory(&self) -> PathBuf {
		self.config.directory.join(&self.config.model_name)
	}

	/// Return the incremental checkpoint directory.
	pub fn incremental_directory(&self) -> PathBuf {
		let name = if self.config.context.is_empty() {
			"checkpoint".to_owned()
		} else {
			format!("checkpoint_{}", self.config.context)
		};
		self.model_directory().join(name)
	}

	/// Return the master/best checkpoint path.
	pub fn master_path(&self) -> PathBuf {
		self
			.model_directory()
			.join(format!("{}.oam", self.config.model_name))
	}

	/// Return whether `metric` improves the currently retained best value.
	pub fn is_better(&self, metric: f64) -> bool {
		if self.config.lower_is_better {
			metric < self.best_metric
		} else {
			metric > self.best_metric
		}
	}

	/// Return the best metric admitted in this manager session.
	pub const fn best_metric(&self) -> f64 {
		self.best_metric
	}

	/// Restore historical best-metric selection state from an exact-resume
	/// checkpoint companion.
	///
	/// Rejects NaN and an infinite sentinel whose sign disagrees with
	/// `config.lower_is_better`.
	///
	/// # Errors
	///
	/// Returns an error when `best_metric` is NaN or carries the opposite
	/// infinity sentinel for this manager's improvement direction.
	pub fn restore_best_metric(&mut self, best_metric: f64) -> Result<()> {
		if best_metric.is_nan()
			|| (self.config.lower_is_better && best_metric == f64::NEG_INFINITY)
			|| (!self.config.lower_is_better && best_metric == f64::INFINITY)
		{
			return Err(Error::invalid_argument(
				"restored checkpoint best metric is invalid for improvement direction",
			));
		}
		self.best_metric = best_metric;
		Ok(())
	}

	/// Return the configured metric name.
	pub fn metric_name(&self) -> &str {
		&self.config.metric_name
	}

	/// Save an incremental checkpoint and update the master file on improvement.
	///
	/// When `force` is false, a non-improving metric performs no write. When it is
	/// true, the incremental file is still written but the master changes only on
	/// improvement.
	///
	/// # Errors
	///
	/// Returns an error for non-finite metrics, optimizer/progress mismatch,
	/// serialization, directory creation, rotation, or filesystem failure.
	pub fn maybe_save(
		&mut self,
		model: &dyn Module,
		optimizer: &dyn CheckpointOptimizer,
		step: u64,
		metric: f64,
		force: bool,
	) -> Result<bool> {
		validate_metric_step(optimizer, step, metric)?;
		let improved = self.is_better(metric);
		if !improved && !force {
			return Ok(false);
		}
		self.save_incremental(model, optimizer, step, metric, None)?;
		self.finish_maybe_save(model, optimizer, step, metric, improved)
	}

	/// `maybe_save` additionally committing exact-resume run state beside the
	/// incremental checkpoint; see [`Self::save_incremental_with_run_state`].
	///
	/// # Errors
	///
	/// Returns the errors of [`Self::maybe_save`] plus run-state commit failure.
	pub fn maybe_save_with_run_state(
		&mut self,
		model: &dyn Module,
		optimizer: &dyn CheckpointOptimizer,
		step: u64,
		metric: f64,
		force: bool,
		run_state: &RunState,
	) -> Result<bool> {
		validate_metric_step(optimizer, step, metric)?;
		let improved = self.is_better(metric);
		if !improved && !force {
			return Ok(false);
		}
		self.save_incremental_with_run_state(model, optimizer, step, metric, None, Some(run_state))?;
		self.finish_maybe_save(model, optimizer, step, metric, improved)
	}

	fn finish_maybe_save(
		&mut self,
		model: &dyn Module,
		optimizer: &dyn CheckpointOptimizer,
		step: u64,
		metric: f64,
		improved: bool,
	) -> Result<bool> {
		if improved {
			if self.config.save_best {
				fs::create_dir_all(self.model_directory())
					.map_err(|source| Error::io("create checkpoint model directory", source))?;
				save_checkpoint_with_progress(
					&self.master_path(),
					model,
					optimizer,
					Some(self.progress(step, metric, &self.config.metric_name)),
				)?;
			}
			self.best_metric = metric;
		}
		Ok(improved)
	}

	/// Save a resumable incremental checkpoint without changing best selection.
	///
	/// # Errors
	///
	/// Returns an error for invalid metric/progress state, serialization,
	/// directory creation, rotation, or filesystem failure.
	pub fn save_incremental(
		&mut self,
		model: &dyn Module,
		optimizer: &dyn CheckpointOptimizer,
		step: u64,
		metric: f64,
		metric_name: Option<&str>,
	) -> Result<PathBuf> {
		self.save_incremental_with_run_state(model, optimizer, step, metric, metric_name, None)
	}

	/// Save a resumable incremental checkpoint together with its exact-resume
	/// run state. The `.oam` artifact writes first and the run state then
	/// commits atomically beside it as a same-stem `.runstate` sibling;
	/// rotation removes the pair together, so a retained checkpoint never
	/// outlives its training-loop position. A checkpoint whose sibling is
	/// absent or corrupt fails the resume contract clearly at load time
	/// rather than guessing a partial position.
	///
	/// # Errors
	///
	/// Returns the errors of [`Self::save_incremental`] plus run-state
	/// serialization and commit failures.
	pub fn save_incremental_with_run_state(
		&mut self,
		model: &dyn Module,
		optimizer: &dyn CheckpointOptimizer,
		step: u64,
		metric: f64,
		metric_name: Option<&str>,
		run_state: Option<&RunState>,
	) -> Result<PathBuf> {
		validate_metric_step(optimizer, step, metric)?;
		let metric_name = metric_name.unwrap_or(&self.config.metric_name);
		validate_component(metric_name, "checkpoint metric name")?;
		let directory = self.incremental_directory();
		fs::create_dir_all(&directory)
			.map_err(|source| Error::io("create incremental checkpoint directory", source))?;
		let filename = self.filename(step, metric, metric_name);
		let path = directory.join(filename);
		save_checkpoint_with_progress(
			&path,
			model,
			optimizer,
			Some(self.progress(step, metric, metric_name)),
		)?;
		if let Some(run_state) = run_state {
			save_run_state(&run_state_path(&path), run_state)?;
		}
		self.saved.retain(|saved| saved.path != path);
		self.saved.push(SavedCheckpoint {
			path: path.clone(),
			step,
		});
		self.rotate()?;
		Ok(path)
	}

	/// Restore the master/best checkpoint into existing owners.
	///
	/// # Errors
	///
	/// Returns the native load, validation, allocation, or filesystem error.
	pub fn load_best_into(
		&self,
		model: &dyn Module,
		optimizer: &mut dyn CheckpointOptimizer,
	) -> Result<()> {
		load_checkpoint_on(self.runtime, self.master_path(), model, optimizer)
	}

	/// Restore the highest-step incremental checkpoint into existing owners.
	///
	/// The manager prefers files recorded in this session and otherwise scans its
	/// incremental directory using the same strict filename grammar it writes.
	/// The returned value is the exact completed step restored into the optimizer.
	///
	/// # Errors
	///
	/// Returns an error when no checkpoint exists or loading fails.
	pub fn load_latest_into(
		&self,
		model: &dyn Module,
		optimizer: &mut dyn CheckpointOptimizer,
	) -> Result<u64> {
		let path = self.latest_path()?.ok_or_else(|| {
			Error::failed_precondition(format!(
				"no checkpoints in {}",
				self.incremental_directory().display()
			))
		})?;
		let step = parse_step(&path)
			.ok_or_else(|| Error::failed_precondition("latest checkpoint has no valid step segment"))?;
		load_checkpoint_at_step(self.runtime, &path, model, optimizer, step)?;
		Ok(step)
	}

	/// Restore the latest incremental state and recover historical best-metric
	/// selection from the master checkpoint when it exists.
	///
	/// This joins model, optimizer, completed step, and best-checkpoint policy at
	/// one restart boundary. A master file written for another metric or ordering
	/// policy is rejected instead of silently resetting selection history.
	///
	/// # Errors
	///
	/// Returns the same errors as [`Self::load_latest_into`], plus malformed or
	/// incompatible master progress metadata.
	pub fn resume_latest_into(
		&mut self,
		model: &dyn Module,
		optimizer: &mut dyn CheckpointOptimizer,
	) -> Result<u64> {
		let master = self.master_path();
		let restored_best = if master.is_file() {
			let file = ModelFile::load(&master)?;
			if file.progress.metric_name != self.config.metric_name
				|| file.progress.lower_is_better != self.config.lower_is_better
				|| !file.progress.best_metric.is_finite()
			{
				return Err(Error::invalid_argument(
					"master checkpoint progress does not match resume policy",
				));
			}
			Some(f64::from(file.progress.best_metric))
		} else {
			None
		};
		let step = self.load_latest_into(model, optimizer)?;
		if let Some(best) = restored_best {
			self.best_metric = best;
		}
		Ok(step)
	}

	fn progress(&self, step: u64, metric: f64, metric_name: &str) -> CheckpointProgress {
		CheckpointProgress {
			step,
			metric,
			metric_name: metric_name.to_owned(),
			lower_is_better: self.config.lower_is_better,
		}
	}

	fn filename(&self, step: u64, metric: f64, metric_name: &str) -> String {
		if self.config.context.is_empty() {
			format!(
				"{}_step{step}_{metric_name}{metric:.2}.oam",
				self.config.model_name
			)
		} else {
			format!(
				"{}_{}_step{step}_{metric_name}{metric:.2}.oam",
				self.config.model_name, self.config.context
			)
		}
	}

	fn rotate(&mut self) -> Result<()> {
		if self.config.max_keep == 0 || self.saved.len() <= self.config.max_keep {
			return Ok(());
		}
		self.saved.sort_unstable_by(|left, right| {
			right
				.step
				.cmp(&left.step)
				.then_with(|| right.path.cmp(&left.path))
		});
		while self.saved.len() > self.config.max_keep {
			let removed = self.saved.pop().expect("retention excess exists");
			if let Err(source) = fs::remove_file(&removed.path) {
				self.saved.push(removed);
				return Err(Error::io("remove rotated checkpoint", source));
			}
			let sibling = run_state_path(&removed.path);
			if sibling.exists() {
				fs::remove_file(&sibling)
					.map_err(|source| Error::io("remove rotated run state", source))?;
			}
		}
		Ok(())
	}

	/// Load the run state committed beside the latest incremental checkpoint.
	///
	/// # Errors
	///
	/// Returns an error when no incremental checkpoint exists, its sibling
	/// run state is absent, or the state fails its format contract.
	pub fn load_latest_run_state(&self) -> Result<RunState> {
		let path = self
			.latest_path()?
			.ok_or_else(|| Error::failed_precondition("no incremental checkpoint exists"))?;
		load_run_state(&run_state_path(&path))
	}

	fn latest_path(&self) -> Result<Option<PathBuf>> {
		if let Some(saved) = self.saved.iter().max_by_key(|saved| saved.step) {
			return Ok(Some(saved.path.clone()));
		}
		let directory = self.incremental_directory();
		let entries = match fs::read_dir(&directory) {
			Ok(entries) => entries,
			Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
			Err(source) => return Err(Error::io("scan checkpoint directory", source)),
		};
		let mut latest: Option<(u64, PathBuf)> = None;
		for entry in entries {
			let entry = entry.map_err(|source| Error::io("read checkpoint directory", source))?;
			let path = entry.path();
			if path.extension().and_then(|value| value.to_str()) != Some("oam") {
				continue;
			}
			let Some(step) = parse_step(&path) else {
				continue;
			};
			if latest.as_ref().is_none_or(|(current, _)| step > *current) {
				latest = Some((step, path));
			}
		}
		Ok(latest.map(|(_, path)| path))
	}
}

fn validate_component(value: &str, name: &'static str) -> Result<()> {
	if value.is_empty()
		|| value == "."
		|| value == ".."
		|| !value
			.bytes()
			.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
	{
		return Err(Error::invalid_argument(format!(
			"{name} must be a nonempty portable filename component"
		)));
	}
	Ok(())
}

fn validate_metric_step(optimizer: &dyn CheckpointOptimizer, step: u64, metric: f64) -> Result<()> {
	if !metric.is_finite() || !(metric as f32).is_finite() {
		return Err(Error::invalid_argument("checkpoint metric must be finite"));
	}
	if optimizer.step_count() != step {
		return Err(Error::invalid_argument(
			"checkpoint step does not match optimizer state",
		));
	}
	Ok(())
}

fn parse_step(path: &Path) -> Option<u64> {
	let stem = path.file_stem()?.to_str()?;
	let marker = stem.rfind("_step")?;
	let digits = stem[marker + 5..].split('_').next()?;
	(!digits.is_empty()).then(|| digits.parse().ok()).flatten()
}

/// Same-stem `.runstate` sibling of a checkpoint artifact path.
fn run_state_path(checkpoint: &Path) -> PathBuf {
	checkpoint.with_extension("runstate")
}