Skip to main content

oa/ml/checkpoint/
run_state.rs

1//! Versioned exact-resume run state committed beside incremental checkpoints.
2//!
3//! Native `.oam` artifacts carry parameters, persistent buffers, optimizer
4//! state, and progress — everything needed to reconstruct the model. Exact
5//! resume additionally needs the training loop's own position: which epoch
6//! and loader cursor come next, where dynamic loss scaling stands, per-module
7//! stochastic stream draw positions, and active callback criteria (checkpoint
8//! best-metric / epoch and early-stopping patience). That state is
9//! deliberately separate from the model artifact: best-model and deployable
10//! weights files do not descend from a particular loop position, and loop
11//! state follows the training session rather than model ownership.
12
13use std::{
14	collections::HashSet,
15	fs,
16	io::Write,
17	path::{Path, PathBuf},
18};
19
20use crate::{Error, Result};
21
22const MAGIC: u32 = 0x4f41_5253; // "OARS" — OA run state
23const VERSION_V1: u32 = 1;
24const VERSION_V2: u32 = 2;
25const HEADER_LEN: usize = 8;
26const V1_BODY_LEN: usize = 8 + 8 + 1 + 4 + 8;
27
28/// One registered module RNG stream position keyed by its deterministic
29/// registration-derived dotted path (for example `"dropout.draw"` or
30/// `"block.attn.dropout_draw"`).
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct RngStreamPosition {
33	/// Registration-derived dotted path within the owning module tree.
34	pub path: String,
35	/// Number of draws (eager forwards or captured replays) already consumed.
36	pub draw: u64,
37}
38
39/// Persisted best-checkpoint selection criteria for exact resume.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct CheckpointCriteriaState {
42	/// Best monitored metric value admitted so far (`f64::INFINITY` or
43	/// `f64::NEG_INFINITY` when no epoch has been admitted yet).
44	pub best_metric: f64,
45	/// One-based epoch that produced `best_metric`, when one has been admitted.
46	pub best_epoch: Option<u64>,
47}
48
49/// Persisted early-stopping patience criteria for exact resume.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct EarlyStoppingState {
52	/// Best monitored metric value observed so far (`f64::INFINITY` or
53	/// `f64::NEG_INFINITY` when no epoch has been observed yet).
54	pub best: f64,
55	/// Consecutive non-improving epochs observed since the last improvement.
56	pub bad_epochs: u64,
57}
58
59/// Exact-resume training-loop position committed at a completed update
60/// boundary.
61///
62/// `epoch` and `loader_cursor` restore the data pass through
63/// `DataLoader::seek`; `scaler` restores dynamic loss scaling through
64/// `GradScaler::restore_state`; `rng_states` restores per-module stochastic
65/// draw positions through [`restore_rng_states`]; `checkpoint` and
66/// `early_stopping` restore callback selection and patience state. Schedulers
67/// are stateless step-to-rate mappings and ride on the logical optimizer step
68/// already persisted in `.oam`.
69#[derive(Clone, Debug, PartialEq)]
70pub struct RunState {
71	/// Epoch whose shuffle order the loader cursor indexes.
72	pub epoch: u64,
73	/// Batch cursor within that epoch.
74	pub loader_cursor: i64,
75	/// Dynamic loss-scaler state, when the run uses one.
76	pub scaler: Option<crate::ml::optim::GradScalerState>,
77	/// Per-module RNG stream draw positions in deterministic traversal order.
78	pub rng_states: Vec<RngStreamPosition>,
79	/// Checkpoint selection criteria (best metric and best epoch), when active.
80	pub checkpoint: Option<CheckpointCriteriaState>,
81	/// Early-stopping criteria (best metric and wait count), when active.
82	pub early_stopping: Option<EarlyStoppingState>,
83}
84
85impl RunState {
86	/// Construct a bare run state at `(epoch, loader_cursor)` with no scaler,
87	/// RNG stream positions, or callback criteria.
88	#[must_use]
89	pub const fn new(epoch: u64, loader_cursor: i64) -> Self {
90		Self {
91			epoch,
92			loader_cursor,
93			scaler: None,
94			rng_states: Vec::new(),
95			checkpoint: None,
96			early_stopping: None,
97		}
98	}
99
100	fn uses_v2(&self) -> bool {
101		!self.rng_states.is_empty() || self.checkpoint.is_some() || self.early_stopping.is_some()
102	}
103}
104
105/// Capture the current stochastic draw position of every registered RNG stream
106/// in `model` in deterministic depth-first module order.
107///
108/// For streams that have been captured inside a replayable program, this reads
109/// the device-resident replay counter at the completed boundary.
110///
111/// # Errors
112///
113/// Returns an error for ambiguous module ownership, an active capture, or a
114/// device readback failure.
115pub fn capture_rng_states(model: &dyn crate::ml::Module) -> Result<Vec<RngStreamPosition>> {
116	let streams = model.all_named_rng_states()?;
117	let mut positions = Vec::with_capacity(streams.len());
118	for stream in streams {
119		positions.push(RngStreamPosition {
120			path: stream.path().to_owned(),
121			draw: stream.draw()?,
122		});
123	}
124	Ok(positions)
125}
126
127/// Restore per-module stochastic draw positions captured by
128/// [`capture_rng_states`].
129///
130/// Validation is exact and atomic: duplicate paths, missing module streams, or
131/// unknown paths fail before any live stream changes.
132///
133/// # Errors
134///
135/// Returns an error for ambiguous module ownership, duplicate paths, or any
136/// mismatch between `states` and `model`'s registered RNG stream paths.
137pub fn restore_rng_states(
138	model: &dyn crate::ml::Module,
139	states: &[RngStreamPosition],
140) -> Result<()> {
141	let streams = model.all_named_rng_states()?;
142	let mut seen = HashSet::with_capacity(states.len());
143	for entry in states {
144		if entry.path.is_empty() {
145			return Err(Error::invalid_argument(
146				"run state RNG stream path must not be empty",
147			));
148		}
149		if !seen.insert(entry.path.as_str()) {
150			return Err(Error::invalid_argument(format!(
151				"run state contains duplicate RNG stream path {}",
152				entry.path
153			)));
154		}
155	}
156	if streams.len() != states.len() {
157		return Err(Error::invalid_argument(format!(
158			"run state RNG stream count ({}) does not match model ({})",
159			states.len(),
160			streams.len()
161		)));
162	}
163	let mut resolved = Vec::with_capacity(streams.len());
164	for stream in streams {
165		let entry = states
166			.iter()
167			.find(|candidate| candidate.path == stream.path())
168			.ok_or_else(|| {
169				Error::invalid_argument(format!(
170					"run state is missing RNG stream position for {}",
171					stream.path()
172				))
173			})?;
174		resolved.push((stream, entry.draw));
175	}
176	for (stream, draw) in resolved {
177		stream.restore_draw(draw);
178	}
179	Ok(())
180}
181
182fn validate_checkpoint_criteria(criteria: CheckpointCriteriaState) -> Result<()> {
183	if criteria.best_metric.is_nan() {
184		return Err(Error::invalid_argument(
185			"run state checkpoint best_metric must not be NaN",
186		));
187	}
188	if let Some(best_epoch) = criteria.best_epoch {
189		if best_epoch == 0 {
190			return Err(Error::invalid_argument(
191				"run state checkpoint best_epoch must be one-based",
192			));
193		}
194		if !criteria.best_metric.is_finite() {
195			return Err(Error::invalid_argument(
196				"run state checkpoint best_metric must be finite when best_epoch is present",
197			));
198		}
199	}
200	Ok(())
201}
202
203fn validate_early_stopping(state: EarlyStoppingState) -> Result<()> {
204	if state.best.is_nan() {
205		return Err(Error::invalid_argument(
206			"run state early-stopping best metric must not be NaN",
207		));
208	}
209	Ok(())
210}
211
212fn validate_rng_positions(positions: &[RngStreamPosition]) -> Result<()> {
213	let mut seen = HashSet::with_capacity(positions.len());
214	for entry in positions {
215		if entry.path.is_empty() {
216			return Err(Error::invalid_argument(
217				"run state RNG stream path must not be empty",
218			));
219		}
220		if !seen.insert(entry.path.as_str()) {
221			return Err(Error::invalid_argument(format!(
222				"run state contains duplicate RNG stream path {}",
223				entry.path
224			)));
225		}
226	}
227	Ok(())
228}
229
230/// Encode a run state into its versioned wire form.
231///
232/// Bare states (epoch, cursor, optional scaler only) encode as v1 so existing
233/// readers remain compatible; states carrying RNG stream positions or callback
234/// criteria encode as v2.
235fn encode(state: &RunState) -> Result<Vec<u8>> {
236	if let Some(criteria) = state.checkpoint {
237		validate_checkpoint_criteria(criteria)?;
238	}
239	if let Some(early) = state.early_stopping {
240		validate_early_stopping(early)?;
241	}
242	validate_rng_positions(&state.rng_states)?;
243
244	let version = if state.uses_v2() {
245		VERSION_V2
246	} else {
247		VERSION_V1
248	};
249	let mut out = Vec::with_capacity(HEADER_LEN + V1_BODY_LEN);
250	out.extend_from_slice(&MAGIC.to_le_bytes());
251	out.extend_from_slice(&version.to_le_bytes());
252	out.extend_from_slice(&state.epoch.to_le_bytes());
253	out.extend_from_slice(&state.loader_cursor.to_le_bytes());
254	match state.scaler {
255		Some(scaler) => {
256			out.push(1);
257			out.extend_from_slice(&scaler.scale.to_le_bytes());
258			out.extend_from_slice(&scaler.growth_tracker.to_le_bytes());
259		}
260		None => {
261			out.push(0);
262			out.extend_from_slice(&0.0_f32.to_le_bytes());
263			out.extend_from_slice(&0_u64.to_le_bytes());
264		}
265	}
266	if version == VERSION_V1 {
267		return Ok(out);
268	}
269	match state.checkpoint {
270		Some(criteria) => {
271			out.push(1);
272			out.extend_from_slice(&criteria.best_metric.to_le_bytes());
273			match criteria.best_epoch {
274				Some(epoch) => {
275					out.push(1);
276					out.extend_from_slice(&epoch.to_le_bytes());
277				}
278				None => {
279					out.push(0);
280					out.extend_from_slice(&0_u64.to_le_bytes());
281				}
282			}
283		}
284		None => out.push(0),
285	}
286	match state.early_stopping {
287		Some(early) => {
288			out.push(1);
289			out.extend_from_slice(&early.best.to_le_bytes());
290			out.extend_from_slice(&early.bad_epochs.to_le_bytes());
291		}
292		None => out.push(0),
293	}
294	let rng_count = u32::try_from(state.rng_states.len())
295		.map_err(|_| Error::resource_exhausted("run state RNG stream count exceeds u32"))?;
296	out.extend_from_slice(&rng_count.to_le_bytes());
297	for entry in &state.rng_states {
298		let path_bytes = entry.path.as_bytes();
299		let path_len = u32::try_from(path_bytes.len())
300			.map_err(|_| Error::resource_exhausted("run state RNG stream path exceeds u32"))?;
301		out.extend_from_slice(&path_len.to_le_bytes());
302		out.extend_from_slice(path_bytes);
303		out.extend_from_slice(&entry.draw.to_le_bytes());
304	}
305	Ok(out)
306}
307
308struct Reader<'a> {
309	bytes: &'a [u8],
310	offset: usize,
311}
312
313impl<'a> Reader<'a> {
314	fn new(bytes: &'a [u8]) -> Self {
315		Self { bytes, offset: 0 }
316	}
317
318	fn take(&mut self, count: usize) -> Result<&'a [u8]> {
319		let end = self
320			.offset
321			.checked_add(count)
322			.ok_or_else(|| Error::invalid_argument("run state length overflow"))?;
323		if end > self.bytes.len() {
324			return Err(Error::invalid_argument("run state file is truncated"));
325		}
326		let slice = &self.bytes[self.offset..end];
327		self.offset = end;
328		Ok(slice)
329	}
330
331	fn u8(&mut self) -> Result<u8> {
332		Ok(self.take(1)?[0])
333	}
334
335	fn flag(&mut self, name: &str) -> Result<bool> {
336		match self.u8()? {
337			0 => Ok(false),
338			1 => Ok(true),
339			other => Err(Error::invalid_argument(format!(
340				"run state {name} flag has invalid value {other}"
341			))),
342		}
343	}
344
345	fn u32(&mut self) -> Result<u32> {
346		Ok(u32::from_le_bytes(
347			self.take(4)?.try_into().expect("u32 width"),
348		))
349	}
350
351	fn u64(&mut self) -> Result<u64> {
352		Ok(u64::from_le_bytes(
353			self.take(8)?.try_into().expect("u64 width"),
354		))
355	}
356
357	fn i64(&mut self) -> Result<i64> {
358		Ok(i64::from_le_bytes(
359			self.take(8)?.try_into().expect("i64 width"),
360		))
361	}
362
363	fn f32(&mut self) -> Result<f32> {
364		Ok(f32::from_le_bytes(
365			self.take(4)?.try_into().expect("f32 width"),
366		))
367	}
368
369	fn f64(&mut self) -> Result<f64> {
370		Ok(f64::from_le_bytes(
371			self.take(8)?.try_into().expect("f64 width"),
372		))
373	}
374
375	fn remaining(&self) -> usize {
376		self.bytes.len().saturating_sub(self.offset)
377	}
378}
379
380fn decode(bytes: &[u8]) -> Result<RunState> {
381	if bytes.len() < HEADER_LEN {
382		return Err(Error::invalid_argument("run state file is truncated"));
383	}
384	let mut reader = Reader::new(bytes);
385	let magic = reader.u32()?;
386	if magic != MAGIC {
387		return Err(Error::invalid_argument("not an OA run state file"));
388	}
389	let version = reader.u32()?;
390	if version != VERSION_V1 && version != VERSION_V2 {
391		return Err(Error::invalid_argument(format!(
392			"unsupported run state version {version}"
393		)));
394	}
395	if version == VERSION_V1 && bytes.len() != HEADER_LEN + V1_BODY_LEN {
396		return Err(Error::invalid_argument("run state v1 length mismatch"));
397	}
398	let epoch = reader.u64()?;
399	let loader_cursor = reader.i64()?;
400	let has_scaler = reader.flag("scaler")?;
401	let scale = reader.f32()?;
402	let growth_tracker = reader.u64()?;
403	let scaler = has_scaler.then_some(crate::ml::optim::GradScalerState {
404		scale,
405		growth_tracker,
406	});
407	if version == VERSION_V1 {
408		return Ok(RunState {
409			epoch,
410			loader_cursor,
411			scaler,
412			rng_states: Vec::new(),
413			checkpoint: None,
414			early_stopping: None,
415		});
416	}
417	let checkpoint = if reader.flag("checkpoint")? {
418		let best_metric = reader.f64()?;
419		let has_best_epoch = reader.flag("best_epoch")?;
420		let best_epoch_value = reader.u64()?;
421		let criteria = CheckpointCriteriaState {
422			best_metric,
423			best_epoch: has_best_epoch.then_some(best_epoch_value),
424		};
425		validate_checkpoint_criteria(criteria)?;
426		Some(criteria)
427	} else {
428		None
429	};
430	let early_stopping = if reader.flag("early_stopping")? {
431		let best = reader.f64()?;
432		let bad_epochs = reader.u64()?;
433		let state = EarlyStoppingState { best, bad_epochs };
434		validate_early_stopping(state)?;
435		Some(state)
436	} else {
437		None
438	};
439	let rng_count = reader.u32()? as usize;
440	// Guard allocation against crafted count larger than remaining payload.
441	if rng_count.saturating_mul(12) > reader.remaining() {
442		return Err(Error::invalid_argument("run state RNG table is truncated"));
443	}
444	let mut rng_states = Vec::with_capacity(rng_count);
445	for _ in 0..rng_count {
446		let path_len = reader.u32()? as usize;
447		let path_bytes = reader.take(path_len)?;
448		let path = std::str::from_utf8(path_bytes)
449			.map_err(|_| Error::invalid_argument("run state RNG stream path is not valid UTF-8"))?
450			.to_owned();
451		let draw = reader.u64()?;
452		rng_states.push(RngStreamPosition { path, draw });
453	}
454	if reader.remaining() != 0 {
455		return Err(Error::invalid_argument("run state v2 has trailing bytes"));
456	}
457	validate_rng_positions(&rng_states)?;
458	Ok(RunState {
459		epoch,
460		loader_cursor,
461		scaler,
462		rng_states,
463		checkpoint,
464		early_stopping,
465	})
466}
467
468/// Commit a run state atomically: write the complete payload to a sibling
469/// temporary file, flush, then rename over `path`. A crash anywhere before
470/// the rename leaves either the previous committed state or nothing — never
471/// a truncated run state.
472///
473/// # Errors
474///
475/// Returns an error when serialization, the temporary write, flush, or
476/// rename fails.
477pub fn save_run_state(path: &Path, state: &RunState) -> Result<()> {
478	let bytes = encode(state)?;
479	let temporary: PathBuf = path.with_extension("runstate.tmp");
480	{
481		let mut file = fs::File::create(&temporary).map_err(|error| {
482			Error::internal(format!(
483				"run state temporary create failed for {}: {error}",
484				temporary.display()
485			))
486		})?;
487		file.write_all(&bytes).map_err(|error| {
488			Error::internal(format!(
489				"run state temporary write failed for {}: {error}",
490				temporary.display()
491			))
492		})?;
493		file.sync_all().map_err(|error| {
494			Error::internal(format!(
495				"run state flush failed for {}: {error}",
496				temporary.display()
497			))
498		})?;
499	}
500	fs::rename(&temporary, path).map_err(|error| {
501		Error::internal(format!(
502			"run state commit rename failed for {}: {error}",
503			path.display()
504		))
505	})
506}
507
508/// Load a committed run state (v1 or v2).
509///
510/// # Errors
511///
512/// Returns an error when the file is missing, unreadable, or fails the
513/// magic/version/length/field contract — callers must not guess at a partial
514/// training position.
515pub fn load_run_state(path: &Path) -> Result<RunState> {
516	let bytes = fs::read(path).map_err(|error| {
517		Error::internal(format!(
518			"run state read failed for {}: {error}",
519			path.display()
520		))
521	})?;
522	decode(&bytes)
523}