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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! 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, where dynamic loss scaling stands, per-module
//! stochastic stream draw positions, and active callback criteria (checkpoint
//! best-metric / epoch and early-stopping patience). That state is
//! deliberately separate from the model artifact: best-model and deployable
//! weights files do not descend from a particular loop position, and loop
//! state follows the training session rather than model ownership.

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

use crate::{Error, Result};

const MAGIC: u32 = 0x4f41_5253; // "OARS" — OA run state
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;

/// One registered module RNG stream position keyed by its deterministic
/// registration-derived dotted path (for example `"dropout.draw"` or
/// `"block.attn.dropout_draw"`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RngStreamPosition {
	/// Registration-derived dotted path within the owning module tree.
	pub path: String,
	/// Number of draws (eager forwards or captured replays) already consumed.
	pub draw: u64,
}

/// Persisted best-checkpoint selection criteria for exact resume.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CheckpointCriteriaState {
	/// Best monitored metric value admitted so far (`f64::INFINITY` or
	/// `f64::NEG_INFINITY` when no epoch has been admitted yet).
	pub best_metric: f64,
	/// One-based epoch that produced `best_metric`, when one has been admitted.
	pub best_epoch: Option<u64>,
}

/// Persisted early-stopping patience criteria for exact resume.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EarlyStoppingState {
	/// Best monitored metric value observed so far (`f64::INFINITY` or
	/// `f64::NEG_INFINITY` when no epoch has been observed yet).
	pub best: f64,
	/// Consecutive non-improving epochs observed since the last improvement.
	pub bad_epochs: u64,
}

/// Exact-resume training-loop position committed at a completed update
/// boundary.
///
/// `epoch` and `loader_cursor` restore the data pass through
/// `DataLoader::seek`; `scaler` restores dynamic loss scaling through
/// `GradScaler::restore_state`; `rng_states` restores per-module stochastic
/// draw positions through [`restore_rng_states`]; `checkpoint` and
/// `early_stopping` restore callback selection and patience state. Schedulers
/// are stateless step-to-rate mappings and ride on the logical optimizer step
/// already persisted in `.oam`.
#[derive(Clone, 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>,
	/// Per-module RNG stream draw positions in deterministic traversal order.
	pub rng_states: Vec<RngStreamPosition>,
	/// Checkpoint selection criteria (best metric and best epoch), when active.
	pub checkpoint: Option<CheckpointCriteriaState>,
	/// Early-stopping criteria (best metric and wait count), when active.
	pub early_stopping: Option<EarlyStoppingState>,
}

impl RunState {
	/// Construct a bare run state at `(epoch, loader_cursor)` with no scaler,
	/// RNG stream positions, or callback criteria.
	#[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()
	}
}

/// Capture the current stochastic draw position of every registered RNG stream
/// in `model` in deterministic depth-first module order.
///
/// For streams that have been captured inside a replayable program, this reads
/// the device-resident replay counter at the completed boundary.
///
/// # Errors
///
/// Returns an error for ambiguous module ownership, an active capture, or a
/// device readback failure.
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)
}

/// Restore per-module stochastic draw positions captured by
/// [`capture_rng_states`].
///
/// Validation is exact and atomic: duplicate paths, missing module streams, or
/// unknown paths fail before any live stream changes.
///
/// # Errors
///
/// Returns an error for ambiguous module ownership, duplicate paths, or any
/// mismatch between `states` and `model`'s registered RNG stream paths.
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(())
}

/// Encode a run state into its versioned wire form.
///
/// Bare states (epoch, cursor, optional scaler only) encode as v1 so existing
/// readers remain compatible; states carrying RNG stream positions or callback
/// criteria encode as v2.
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;
	// Guard allocation against crafted count larger than remaining payload.
	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,
	})
}

/// 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 (v1 or v2).
///
/// # Errors
///
/// Returns an error when the file is missing, unreadable, or fails the
/// magic/version/length/field 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)
}