use std::{
collections::HashSet,
fs,
io::Write,
path::{Path, PathBuf},
};
use crate::{Error, Result};
const MAGIC: u32 = 0x4f41_5253; const VERSION_V1: u32 = 1;
const VERSION_V2: u32 = 2;
const HEADER_LEN: usize = 8;
const V1_BODY_LEN: usize = 8 + 8 + 1 + 4 + 8;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RngStreamPosition {
pub path: String,
pub draw: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CheckpointCriteriaState {
pub best_metric: f64,
pub best_epoch: Option<u64>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EarlyStoppingState {
pub best: f64,
pub bad_epochs: u64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RunState {
pub epoch: u64,
pub loader_cursor: i64,
pub scaler: Option<crate::ml::optim::GradScalerState>,
pub rng_states: Vec<RngStreamPosition>,
pub checkpoint: Option<CheckpointCriteriaState>,
pub early_stopping: Option<EarlyStoppingState>,
}
impl RunState {
#[must_use]
pub const fn new(epoch: u64, loader_cursor: i64) -> Self {
Self {
epoch,
loader_cursor,
scaler: None,
rng_states: Vec::new(),
checkpoint: None,
early_stopping: None,
}
}
fn uses_v2(&self) -> bool {
!self.rng_states.is_empty() || self.checkpoint.is_some() || self.early_stopping.is_some()
}
}
pub fn capture_rng_states(model: &dyn crate::ml::Module) -> Result<Vec<RngStreamPosition>> {
let streams = model.all_named_rng_states()?;
let mut positions = Vec::with_capacity(streams.len());
for stream in streams {
positions.push(RngStreamPosition {
path: stream.path().to_owned(),
draw: stream.draw()?,
});
}
Ok(positions)
}
pub fn restore_rng_states(
model: &dyn crate::ml::Module,
states: &[RngStreamPosition],
) -> Result<()> {
let streams = model.all_named_rng_states()?;
let mut seen = HashSet::with_capacity(states.len());
for entry in states {
if entry.path.is_empty() {
return Err(Error::invalid_argument(
"run state RNG stream path must not be empty",
));
}
if !seen.insert(entry.path.as_str()) {
return Err(Error::invalid_argument(format!(
"run state contains duplicate RNG stream path {}",
entry.path
)));
}
}
if streams.len() != states.len() {
return Err(Error::invalid_argument(format!(
"run state RNG stream count ({}) does not match model ({})",
states.len(),
streams.len()
)));
}
let mut resolved = Vec::with_capacity(streams.len());
for stream in streams {
let entry = states
.iter()
.find(|candidate| candidate.path == stream.path())
.ok_or_else(|| {
Error::invalid_argument(format!(
"run state is missing RNG stream position for {}",
stream.path()
))
})?;
resolved.push((stream, entry.draw));
}
for (stream, draw) in resolved {
stream.restore_draw(draw);
}
Ok(())
}
fn validate_checkpoint_criteria(criteria: CheckpointCriteriaState) -> Result<()> {
if criteria.best_metric.is_nan() {
return Err(Error::invalid_argument(
"run state checkpoint best_metric must not be NaN",
));
}
if let Some(best_epoch) = criteria.best_epoch {
if best_epoch == 0 {
return Err(Error::invalid_argument(
"run state checkpoint best_epoch must be one-based",
));
}
if !criteria.best_metric.is_finite() {
return Err(Error::invalid_argument(
"run state checkpoint best_metric must be finite when best_epoch is present",
));
}
}
Ok(())
}
fn validate_early_stopping(state: EarlyStoppingState) -> Result<()> {
if state.best.is_nan() {
return Err(Error::invalid_argument(
"run state early-stopping best metric must not be NaN",
));
}
Ok(())
}
fn validate_rng_positions(positions: &[RngStreamPosition]) -> Result<()> {
let mut seen = HashSet::with_capacity(positions.len());
for entry in positions {
if entry.path.is_empty() {
return Err(Error::invalid_argument(
"run state RNG stream path must not be empty",
));
}
if !seen.insert(entry.path.as_str()) {
return Err(Error::invalid_argument(format!(
"run state contains duplicate RNG stream path {}",
entry.path
)));
}
}
Ok(())
}
fn encode(state: &RunState) -> Result<Vec<u8>> {
if let Some(criteria) = state.checkpoint {
validate_checkpoint_criteria(criteria)?;
}
if let Some(early) = state.early_stopping {
validate_early_stopping(early)?;
}
validate_rng_positions(&state.rng_states)?;
let version = if state.uses_v2() {
VERSION_V2
} else {
VERSION_V1
};
let mut out = Vec::with_capacity(HEADER_LEN + V1_BODY_LEN);
out.extend_from_slice(&MAGIC.to_le_bytes());
out.extend_from_slice(&version.to_le_bytes());
out.extend_from_slice(&state.epoch.to_le_bytes());
out.extend_from_slice(&state.loader_cursor.to_le_bytes());
match state.scaler {
Some(scaler) => {
out.push(1);
out.extend_from_slice(&scaler.scale.to_le_bytes());
out.extend_from_slice(&scaler.growth_tracker.to_le_bytes());
}
None => {
out.push(0);
out.extend_from_slice(&0.0_f32.to_le_bytes());
out.extend_from_slice(&0_u64.to_le_bytes());
}
}
if version == VERSION_V1 {
return Ok(out);
}
match state.checkpoint {
Some(criteria) => {
out.push(1);
out.extend_from_slice(&criteria.best_metric.to_le_bytes());
match criteria.best_epoch {
Some(epoch) => {
out.push(1);
out.extend_from_slice(&epoch.to_le_bytes());
}
None => {
out.push(0);
out.extend_from_slice(&0_u64.to_le_bytes());
}
}
}
None => out.push(0),
}
match state.early_stopping {
Some(early) => {
out.push(1);
out.extend_from_slice(&early.best.to_le_bytes());
out.extend_from_slice(&early.bad_epochs.to_le_bytes());
}
None => out.push(0),
}
let rng_count = u32::try_from(state.rng_states.len())
.map_err(|_| Error::resource_exhausted("run state RNG stream count exceeds u32"))?;
out.extend_from_slice(&rng_count.to_le_bytes());
for entry in &state.rng_states {
let path_bytes = entry.path.as_bytes();
let path_len = u32::try_from(path_bytes.len())
.map_err(|_| Error::resource_exhausted("run state RNG stream path exceeds u32"))?;
out.extend_from_slice(&path_len.to_le_bytes());
out.extend_from_slice(path_bytes);
out.extend_from_slice(&entry.draw.to_le_bytes());
}
Ok(out)
}
struct Reader<'a> {
bytes: &'a [u8],
offset: usize,
}
impl<'a> Reader<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes, offset: 0 }
}
fn take(&mut self, count: usize) -> Result<&'a [u8]> {
let end = self
.offset
.checked_add(count)
.ok_or_else(|| Error::invalid_argument("run state length overflow"))?;
if end > self.bytes.len() {
return Err(Error::invalid_argument("run state file is truncated"));
}
let slice = &self.bytes[self.offset..end];
self.offset = end;
Ok(slice)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
fn flag(&mut self, name: &str) -> Result<bool> {
match self.u8()? {
0 => Ok(false),
1 => Ok(true),
other => Err(Error::invalid_argument(format!(
"run state {name} flag has invalid value {other}"
))),
}
}
fn u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(
self.take(4)?.try_into().expect("u32 width"),
))
}
fn u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(
self.take(8)?.try_into().expect("u64 width"),
))
}
fn i64(&mut self) -> Result<i64> {
Ok(i64::from_le_bytes(
self.take(8)?.try_into().expect("i64 width"),
))
}
fn f32(&mut self) -> Result<f32> {
Ok(f32::from_le_bytes(
self.take(4)?.try_into().expect("f32 width"),
))
}
fn f64(&mut self) -> Result<f64> {
Ok(f64::from_le_bytes(
self.take(8)?.try_into().expect("f64 width"),
))
}
fn remaining(&self) -> usize {
self.bytes.len().saturating_sub(self.offset)
}
}
fn decode(bytes: &[u8]) -> Result<RunState> {
if bytes.len() < HEADER_LEN {
return Err(Error::invalid_argument("run state file is truncated"));
}
let mut reader = Reader::new(bytes);
let magic = reader.u32()?;
if magic != MAGIC {
return Err(Error::invalid_argument("not an OA run state file"));
}
let version = reader.u32()?;
if version != VERSION_V1 && version != VERSION_V2 {
return Err(Error::invalid_argument(format!(
"unsupported run state version {version}"
)));
}
if version == VERSION_V1 && bytes.len() != HEADER_LEN + V1_BODY_LEN {
return Err(Error::invalid_argument("run state v1 length mismatch"));
}
let epoch = reader.u64()?;
let loader_cursor = reader.i64()?;
let has_scaler = reader.flag("scaler")?;
let scale = reader.f32()?;
let growth_tracker = reader.u64()?;
let scaler = has_scaler.then_some(crate::ml::optim::GradScalerState {
scale,
growth_tracker,
});
if version == VERSION_V1 {
return Ok(RunState {
epoch,
loader_cursor,
scaler,
rng_states: Vec::new(),
checkpoint: None,
early_stopping: None,
});
}
let checkpoint = if reader.flag("checkpoint")? {
let best_metric = reader.f64()?;
let has_best_epoch = reader.flag("best_epoch")?;
let best_epoch_value = reader.u64()?;
let criteria = CheckpointCriteriaState {
best_metric,
best_epoch: has_best_epoch.then_some(best_epoch_value),
};
validate_checkpoint_criteria(criteria)?;
Some(criteria)
} else {
None
};
let early_stopping = if reader.flag("early_stopping")? {
let best = reader.f64()?;
let bad_epochs = reader.u64()?;
let state = EarlyStoppingState { best, bad_epochs };
validate_early_stopping(state)?;
Some(state)
} else {
None
};
let rng_count = reader.u32()? as usize;
if rng_count.saturating_mul(12) > reader.remaining() {
return Err(Error::invalid_argument("run state RNG table is truncated"));
}
let mut rng_states = Vec::with_capacity(rng_count);
for _ in 0..rng_count {
let path_len = reader.u32()? as usize;
let path_bytes = reader.take(path_len)?;
let path = std::str::from_utf8(path_bytes)
.map_err(|_| Error::invalid_argument("run state RNG stream path is not valid UTF-8"))?
.to_owned();
let draw = reader.u64()?;
rng_states.push(RngStreamPosition { path, draw });
}
if reader.remaining() != 0 {
return Err(Error::invalid_argument("run state v2 has trailing bytes"));
}
validate_rng_positions(&rng_states)?;
Ok(RunState {
epoch,
loader_cursor,
scaler,
rng_states,
checkpoint,
early_stopping,
})
}
pub fn save_run_state(path: &Path, state: &RunState) -> Result<()> {
let bytes = encode(state)?;
let temporary: PathBuf = path.with_extension("runstate.tmp");
{
let mut file = fs::File::create(&temporary).map_err(|error| {
Error::internal(format!(
"run state temporary create failed for {}: {error}",
temporary.display()
))
})?;
file.write_all(&bytes).map_err(|error| {
Error::internal(format!(
"run state temporary write failed for {}: {error}",
temporary.display()
))
})?;
file.sync_all().map_err(|error| {
Error::internal(format!(
"run state flush failed for {}: {error}",
temporary.display()
))
})?;
}
fs::rename(&temporary, path).map_err(|error| {
Error::internal(format!(
"run state commit rename failed for {}: {error}",
path.display()
))
})
}
pub fn load_run_state(path: &Path) -> Result<RunState> {
let bytes = fs::read(path).map_err(|error| {
Error::internal(format!(
"run state read failed for {}: {error}",
path.display()
))
})?;
decode(&bytes)
}