oarust 0.19.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Versioned exact-resume run state committed beside incremental checkpoints.
//!
//! Native `.oam` artifacts carry parameters, persistent buffers, optimizer
//! state, and progress — everything needed to reconstruct the model. Exact
//! resume additionally needs the training loop's own position: which epoch
//! and loader cursor come next, and where dynamic loss scaling stands. That
//! state is deliberately separate from the model artifact: best-model and
//! deployable-weights files do not descend from a particular loop position,
//! and the scaler follows the training loop rather than model ownership.

use std::{
	fs,
	io::Write,
	path::{Path, PathBuf},
};

use crate::{Error, Result};

const MAGIC: u32 = 0x4f41_5253; // "OARS" — OA run state
const VERSION: u32 = 1;
const HEADER_LEN: usize = 8;
const V1_BODY_LEN: usize = 8 + 8 + 1 + 4 + 8;

/// Exact-resume training-loop position committed at a completed update
/// boundary.
///
/// `epoch` and `loader_cursor` restore the data pass through
/// `DataLoader::seek`; the scaler fields restore dynamic loss scaling through
/// `GradScaler::restore_state`. Schedulers are stateless step-to-rate
/// mappings and ride on the logical optimizer step already persisted in
/// `.oam`. Stochastic stream positions have their own resume contract.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RunState {
	/// Epoch whose shuffle order the loader cursor indexes.
	pub epoch: u64,
	/// Batch cursor within that epoch.
	pub loader_cursor: i64,
	/// Dynamic loss-scaler state, when the run uses one.
	pub scaler: Option<crate::ml::optim::GradScalerState>,
}

/// Encode a run state into its versioned wire form.
fn encode(state: &RunState) -> Vec<u8> {
	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());
		}
	}
	out
}

fn decode(bytes: &[u8]) -> Result<RunState> {
	if bytes.len() < HEADER_LEN {
		return Err(Error::invalid_argument("run state file is truncated"));
	}
	let magic = u32::from_le_bytes(bytes[0..4].try_into().expect("magic width"));
	if magic != MAGIC {
		return Err(Error::invalid_argument("not an OA run state file"));
	}
	let version = u32::from_le_bytes(bytes[4..8].try_into().expect("version width"));
	if version != VERSION {
		return Err(Error::invalid_argument(format!(
			"unsupported run state version {version}"
		)));
	}
	if bytes.len() != HEADER_LEN + V1_BODY_LEN {
		return Err(Error::invalid_argument("run state v1 length mismatch"));
	}
	let body = &bytes[HEADER_LEN..];
	let epoch = u64::from_le_bytes(body[0..8].try_into().expect("epoch width"));
	let loader_cursor = i64::from_le_bytes(body[8..16].try_into().expect("cursor width"));
	let scaler = if body[16] == 1 {
		let scale = f32::from_le_bytes(body[17..21].try_into().expect("scale width"));
		let growth_tracker = u64::from_le_bytes(body[21..29].try_into().expect("tracker width"));
		Some(crate::ml::optim::GradScalerState {
			scale,
			growth_tracker,
		})
	} else {
		None
	};
	Ok(RunState {
		epoch,
		loader_cursor,
		scaler,
	})
}

/// Commit a run state atomically: write the complete payload to a sibling
/// temporary file, flush, then rename over `path`. A crash anywhere before
/// the rename leaves either the previous committed state or nothing — never
/// a truncated run state.
///
/// # Errors
///
/// Returns an error when serialization, the temporary write, flush, or
/// rename fails.
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()
		))
	})
}

/// Load a committed run state.
///
/// # Errors
///
/// Returns an error when the file is missing, unreadable, or fails the
/// magic/version/length contract — callers must not guess at a partial
/// training position.
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)
}