1use 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; const 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#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct RngStreamPosition {
33 pub path: String,
35 pub draw: u64,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct CheckpointCriteriaState {
42 pub best_metric: f64,
45 pub best_epoch: Option<u64>,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct EarlyStoppingState {
52 pub best: f64,
55 pub bad_epochs: u64,
57}
58
59#[derive(Clone, Debug, PartialEq)]
70pub struct RunState {
71 pub epoch: u64,
73 pub loader_cursor: i64,
75 pub scaler: Option<crate::ml::optim::GradScalerState>,
77 pub rng_states: Vec<RngStreamPosition>,
79 pub checkpoint: Option<CheckpointCriteriaState>,
81 pub early_stopping: Option<EarlyStoppingState>,
83}
84
85impl RunState {
86 #[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
105pub 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
127pub 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
230fn 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 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
468pub 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
508pub 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}