|
| 1 | +//! Training checkpoints that resume a run exactly: model tensors (sharded across files), optimizer state, the global RNG |
| 2 | +//! state, and the position in training (epoch, step, batch within the epoch) plus free-form scalars. |
| 3 | +//! |
| 4 | +//! A checkpoint is a directory: |
| 5 | +//! `model-00001-of-0000N.safetensors` … `model.index.json` · `optimizer.safetensors` · `state.txt`. |
| 6 | +//! It is first written to `<dir>.tmp` and renamed into place, so a crash never leaves a half-written checkpoint visible. |
| 7 | +//! Tensors are addressed by name, so a checkpoint written with one shard size loads with no regard to the sharding |
| 8 | +//! (resharding is free), and [`CheckpointManager`] keeps the last N and finds the latest for `--resume`. |
| 9 | +
|
| 10 | +use crate::error::{Error, Result}; |
| 11 | +use crate::nn::Module; |
| 12 | +use crate::optim::{Optimizer, OptimizerState}; |
| 13 | +use crate::serialize::{load_safetensors, serialize_safetensors_with_metadata}; |
| 14 | +use crate::tensor::Tensor; |
| 15 | +use std::collections::{BTreeMap, HashMap}; |
| 16 | +use std::path::{Path, PathBuf}; |
| 17 | + |
| 18 | +fn io<T>(r: std::io::Result<T>, what: &str) -> Result<T> { |
| 19 | + r.map_err(|e| Error::Msg(format!("checkpoint: {what}: {e}"))) |
| 20 | +} |
| 21 | + |
| 22 | +/// Everything needed to continue a run. |
| 23 | +#[derive(Clone, Default)] |
| 24 | +pub struct TrainState { |
| 25 | + pub model: HashMap<String, Tensor>, |
| 26 | + pub optimizer: Option<OptimizerState>, |
| 27 | + pub rng: Vec<u8>, |
| 28 | + pub epoch: u64, |
| 29 | + pub step: u64, |
| 30 | + /// Batches of `epoch` already consumed (feed to `PrefetchLoader::epoch_from`). |
| 31 | + pub batch_in_epoch: u64, |
| 32 | + pub extra: BTreeMap<String, f64>, |
| 33 | +} |
| 34 | + |
| 35 | +impl TrainState { |
| 36 | + /// Snapshots the model, the optimizer (if any) and the global RNG. Tensors are copied, so training can go on while the |
| 37 | + /// state is written. |
| 38 | + pub fn capture(model: &dyn Module, optimizer: Option<&dyn Optimizer>, epoch: u64, step: u64, batch_in_epoch: u64) -> Result<Self> { |
| 39 | + let copy = |t: &Tensor| t.detach().contiguous()?.mul_scalar(1.0); |
| 40 | + let mut m = HashMap::new(); |
| 41 | + for (k, t) in model.state_dict() { |
| 42 | + m.insert(k, if t.dtype().is_floating_point() { copy(&t)? } else { t.detach().contiguous()? }); |
| 43 | + } |
| 44 | + let optimizer = match optimizer { |
| 45 | + Some(o) => { |
| 46 | + let mut s = o.state_dict(); |
| 47 | + for t in s.tensors.values_mut() { |
| 48 | + *t = copy(t)?; |
| 49 | + } |
| 50 | + Some(s) |
| 51 | + } |
| 52 | + None => None, |
| 53 | + }; |
| 54 | + Ok(Self { model: m, optimizer, rng: crate::rng::get_rng_state(), epoch, step, batch_in_epoch, extra: BTreeMap::new() }) |
| 55 | + } |
| 56 | + |
| 57 | + /// Puts the state back: model weights, optimizer, and the global RNG. |
| 58 | + pub fn restore(&self, model: &dyn Module, optimizer: Option<&mut dyn Optimizer>) -> Result<()> { |
| 59 | + model.load_state_dict(&self.model)?; |
| 60 | + if let (Some(o), Some(s)) = (optimizer, &self.optimizer) { |
| 61 | + o.load_state_dict(s)?; |
| 62 | + } |
| 63 | + if !self.rng.is_empty() { |
| 64 | + crate::rng::set_rng_state(&self.rng)?; |
| 65 | + } |
| 66 | + Ok(()) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +fn tensor_bytes(t: &Tensor) -> usize { |
| 71 | + t.numel() * t.dtype().size_in_bytes() |
| 72 | +} |
| 73 | + |
| 74 | +/// A serialized checkpoint, ready to be written (possibly from another thread). |
| 75 | +pub struct EncodedCheckpoint { |
| 76 | + files: Vec<(String, Vec<u8>)>, |
| 77 | +} |
| 78 | + |
| 79 | +/// Serializes `state` into files, splitting the model into shards of at most `max_shard_bytes` (a single tensor larger |
| 80 | +/// than that gets a shard of its own). |
| 81 | +pub fn encode(state: &TrainState, max_shard_bytes: usize) -> Result<EncodedCheckpoint> { |
| 82 | + let mut names: Vec<&String> = state.model.keys().collect(); |
| 83 | + names.sort(); |
| 84 | + let mut shards: Vec<HashMap<String, Tensor>> = vec![HashMap::new()]; |
| 85 | + let mut used = 0usize; |
| 86 | + for n in names { |
| 87 | + let t = &state.model[n]; |
| 88 | + let sz = tensor_bytes(t); |
| 89 | + if used > 0 && used + sz > max_shard_bytes { |
| 90 | + shards.push(HashMap::new()); |
| 91 | + used = 0; |
| 92 | + } |
| 93 | + shards.last_mut().unwrap().insert(n.clone(), t.clone()); |
| 94 | + used += sz; |
| 95 | + } |
| 96 | + let total = shards.len(); |
| 97 | + let mut files = Vec::new(); |
| 98 | + let mut index = Vec::new(); |
| 99 | + for (i, shard) in shards.iter().enumerate() { |
| 100 | + let fname = format!("model-{:05}-of-{:05}.safetensors", i + 1, total); |
| 101 | + let mut keys: Vec<&String> = shard.keys().collect(); |
| 102 | + keys.sort(); |
| 103 | + for k in keys { |
| 104 | + index.push(format!(" \"{}\": \"{}\"", k.replace('\\', "\\\\").replace('"', "\\\""), fname)); |
| 105 | + } |
| 106 | + files.push((fname, serialize_safetensors_with_metadata(shard, None)?)); |
| 107 | + } |
| 108 | + files.push(("model.index.json".into(), format!("{{\n \"weight_map\": {{\n{}\n }}\n}}\n", index.join(",\n")).into_bytes())); |
| 109 | + if let Some(o) = &state.optimizer { |
| 110 | + let mut all = o.tensors.clone(); |
| 111 | + for (k, &v) in &o.scalars { |
| 112 | + all.insert(format!("__scalar__.{k}"), Tensor::from_slice(&[v], &[1])?); |
| 113 | + } |
| 114 | + files.push(("optimizer.safetensors".into(), serialize_safetensors_with_metadata(&all, None)?)); |
| 115 | + } |
| 116 | + let mut txt = format!("epoch={}\nstep={}\nbatch_in_epoch={}\nrng={}\n", state.epoch, state.step, state.batch_in_epoch, hex(&state.rng)); |
| 117 | + for (k, v) in &state.extra { |
| 118 | + txt.push_str(&format!("extra.{k}={}\n", v.to_bits())); |
| 119 | + } |
| 120 | + files.push(("state.txt".into(), txt.into_bytes())); |
| 121 | + Ok(EncodedCheckpoint { files }) |
| 122 | +} |
| 123 | + |
| 124 | +fn hex(b: &[u8]) -> String { |
| 125 | + b.iter().map(|x| format!("{x:02x}")).collect() |
| 126 | +} |
| 127 | +fn unhex(s: &str) -> Result<Vec<u8>> { |
| 128 | + (0..s.len() / 2).map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).map_err(|_| Error::Msg("checkpoint: bad rng hex".into()))).collect() |
| 129 | +} |
| 130 | + |
| 131 | +impl EncodedCheckpoint { |
| 132 | + /// Writes to `<dir>.tmp` then renames to `dir` (replacing an older checkpoint at that path). |
| 133 | + pub fn write(&self, dir: &Path) -> Result<()> { |
| 134 | + let tmp = PathBuf::from(format!("{}.tmp", dir.display())); |
| 135 | + if tmp.exists() { |
| 136 | + io(std::fs::remove_dir_all(&tmp), "clearing stale temp dir")?; |
| 137 | + } |
| 138 | + io(std::fs::create_dir_all(&tmp), "creating temp dir")?; |
| 139 | + for (name, bytes) in &self.files { |
| 140 | + io(std::fs::write(tmp.join(name), bytes), name)?; |
| 141 | + } |
| 142 | + if dir.exists() { |
| 143 | + io(std::fs::remove_dir_all(dir), "replacing old checkpoint")?; |
| 144 | + } |
| 145 | + io(std::fs::rename(&tmp, dir), "publishing checkpoint") |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/// Saves `state` to `dir` (blocking). |
| 150 | +pub fn save_checkpoint(dir: impl AsRef<Path>, state: &TrainState, max_shard_bytes: usize) -> Result<()> { |
| 151 | + encode(state, max_shard_bytes)?.write(dir.as_ref()) |
| 152 | +} |
| 153 | + |
| 154 | +/// Serializes now and writes on a background thread; join the handle to learn whether the write succeeded. |
| 155 | +pub fn save_checkpoint_async(dir: impl AsRef<Path>, state: &TrainState, max_shard_bytes: usize) -> Result<std::thread::JoinHandle<Result<()>>> { |
| 156 | + let enc = encode(state, max_shard_bytes)?; |
| 157 | + let dir = dir.as_ref().to_path_buf(); |
| 158 | + Ok(std::thread::spawn(move || enc.write(&dir))) |
| 159 | +} |
| 160 | + |
| 161 | +/// Loads a checkpoint directory. |
| 162 | +pub fn load_checkpoint(dir: impl AsRef<Path>) -> Result<TrainState> { |
| 163 | + let dir = dir.as_ref(); |
| 164 | + let mut st = TrainState::default(); |
| 165 | + let mut shard_files: Vec<PathBuf> = io(std::fs::read_dir(dir), "reading directory")? |
| 166 | + .filter_map(|e| e.ok().map(|e| e.path())) |
| 167 | + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("model-") && n.ends_with(".safetensors"))) |
| 168 | + .collect(); |
| 169 | + shard_files.sort(); |
| 170 | + if shard_files.is_empty() { |
| 171 | + return Err(Error::Msg(format!("checkpoint: no model shards in {}", dir.display()))); |
| 172 | + } |
| 173 | + for f in shard_files { |
| 174 | + st.model.extend(load_safetensors(&f)?); |
| 175 | + } |
| 176 | + let opt = dir.join("optimizer.safetensors"); |
| 177 | + if opt.exists() { |
| 178 | + st.optimizer = Some(OptimizerState::load(&opt)?); |
| 179 | + } |
| 180 | + let text = io(std::fs::read_to_string(dir.join("state.txt")), "state.txt")?; |
| 181 | + for line in text.lines() { |
| 182 | + let Some((k, v)) = line.split_once('=') else { continue }; |
| 183 | + let num = |v: &str| v.parse::<u64>().map_err(|_| Error::Msg(format!("checkpoint: bad value for {k}"))); |
| 184 | + match k { |
| 185 | + "epoch" => st.epoch = num(v)?, |
| 186 | + "step" => st.step = num(v)?, |
| 187 | + "batch_in_epoch" => st.batch_in_epoch = num(v)?, |
| 188 | + "rng" => st.rng = unhex(v)?, |
| 189 | + _ => { |
| 190 | + if let Some(name) = k.strip_prefix("extra.") { |
| 191 | + st.extra.insert(name.to_string(), f64::from_bits(num(v)?)); |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + Ok(st) |
| 197 | +} |
| 198 | + |
| 199 | +/// Keeps `step-<n>` checkpoints under a root directory: saves, finds the latest, deletes all but the newest `keep`. |
| 200 | +pub struct CheckpointManager { |
| 201 | + root: PathBuf, |
| 202 | + keep: usize, |
| 203 | + pending: Option<std::thread::JoinHandle<Result<()>>>, |
| 204 | + pub max_shard_bytes: usize, |
| 205 | +} |
| 206 | + |
| 207 | +impl CheckpointManager { |
| 208 | + pub fn new(root: impl AsRef<Path>, keep: usize) -> Result<Self> { |
| 209 | + io(std::fs::create_dir_all(root.as_ref()), "creating root")?; |
| 210 | + Ok(Self { root: root.as_ref().to_path_buf(), keep: keep.max(1), pending: None, max_shard_bytes: 1 << 30 }) |
| 211 | + } |
| 212 | + |
| 213 | + fn path(&self, step: u64) -> PathBuf { |
| 214 | + self.root.join(format!("step-{step:010}")) |
| 215 | + } |
| 216 | + |
| 217 | + /// Waits for an outstanding async save. |
| 218 | + pub fn wait(&mut self) -> Result<()> { |
| 219 | + match self.pending.take() { |
| 220 | + Some(h) => h.join().map_err(|_| Error::Msg("checkpoint: writer thread panicked".into()))?, |
| 221 | + None => Ok(()), |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + /// Saves `state` as step `state.step`; with `background` the write happens on another thread (the previous one is |
| 226 | + /// awaited first, so at most one is in flight). |
| 227 | + pub fn save(&mut self, state: &TrainState, background: bool) -> Result<()> { |
| 228 | + self.wait()?; |
| 229 | + let dir = self.path(state.step); |
| 230 | + if background { |
| 231 | + self.pending = Some(save_checkpoint_async(&dir, state, self.max_shard_bytes)?); |
| 232 | + } else { |
| 233 | + save_checkpoint(&dir, state, self.max_shard_bytes)?; |
| 234 | + self.prune()?; |
| 235 | + } |
| 236 | + Ok(()) |
| 237 | + } |
| 238 | + |
| 239 | + /// Steps with a complete checkpoint on disk, ascending. |
| 240 | + pub fn steps(&self) -> Vec<u64> { |
| 241 | + let mut v: Vec<u64> = std::fs::read_dir(&self.root) |
| 242 | + .into_iter() |
| 243 | + .flatten() |
| 244 | + .filter_map(|e| e.ok()) |
| 245 | + .filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_prefix("step-")).and_then(|n| n.parse().ok())) |
| 246 | + .collect(); |
| 247 | + v.sort_unstable(); |
| 248 | + v |
| 249 | + } |
| 250 | + |
| 251 | + pub fn latest(&mut self) -> Result<Option<TrainState>> { |
| 252 | + self.wait()?; |
| 253 | + self.prune()?; |
| 254 | + match self.steps().last() { |
| 255 | + Some(&s) => Ok(Some(load_checkpoint(self.path(s))?)), |
| 256 | + None => Ok(None), |
| 257 | + } |
| 258 | + } |
| 259 | + |
| 260 | + fn prune(&self) -> Result<()> { |
| 261 | + let steps = self.steps(); |
| 262 | + for s in steps.iter().take(steps.len().saturating_sub(self.keep)) { |
| 263 | + io(std::fs::remove_dir_all(self.path(*s)), "pruning")?; |
| 264 | + } |
| 265 | + Ok(()) |
| 266 | + } |
| 267 | +} |
| 268 | + |
| 269 | +impl Drop for CheckpointManager { |
| 270 | + fn drop(&mut self) { |
| 271 | + let _ = self.wait(); |
| 272 | + } |
| 273 | +} |
| 274 | + |
| 275 | +#[cfg(test)] |
| 276 | +mod tests { |
| 277 | + use super::*; |
| 278 | + use crate::nn::Linear; |
| 279 | + use crate::optim::Adam; |
| 280 | + |
| 281 | + fn tmp(name: &str) -> PathBuf { |
| 282 | + let d = std::env::temp_dir().join(format!("oxideon_ckpt_{name}")); |
| 283 | + let _ = std::fs::remove_dir_all(&d); |
| 284 | + d |
| 285 | + } |
| 286 | + |
| 287 | + fn train_steps(m: &Linear, opt: &mut Adam, n: usize) -> Vec<f32> { |
| 288 | + let x = Tensor::from_slice(&[0.5f32, -1.0, 2.0, 0.25], &[2, 2]).unwrap(); |
| 289 | + (0..n) |
| 290 | + .map(|_| { |
| 291 | + opt.zero_grad(); |
| 292 | + let noise = Tensor::randn(&[2, 2]).unwrap().mul_scalar(0.01).unwrap(); // consumes the global RNG |
| 293 | + let loss = m.forward(&x.add(&noise).unwrap()).unwrap().square().unwrap().mean().unwrap(); |
| 294 | + loss.backward().unwrap(); |
| 295 | + opt.step().unwrap(); |
| 296 | + loss.item::<f32>().unwrap() |
| 297 | + }) |
| 298 | + .collect() |
| 299 | + } |
| 300 | + |
| 301 | + #[test] |
| 302 | + fn resumed_run_is_bit_identical_to_an_uninterrupted_one() { |
| 303 | + let make = || { |
| 304 | + crate::rng::manual_seed(11); |
| 305 | + let m = Linear::new(2, 2).unwrap(); |
| 306 | + let opt = Adam::new(m.parameters(), 0.05); |
| 307 | + (m, opt) |
| 308 | + }; |
| 309 | + // reference: 8 uninterrupted steps |
| 310 | + let (m, mut opt) = make(); |
| 311 | + let reference = train_steps(&m, &mut opt, 8); |
| 312 | + let ref_w = m.state_dict()["weight"].to_vec::<f32>().unwrap(); |
| 313 | + |
| 314 | + // 4 steps, checkpoint (tiny shards force several files), then a brand-new process-like restart |
| 315 | + let dir = tmp("resume"); |
| 316 | + let (m, mut opt) = make(); |
| 317 | + let first = train_steps(&m, &mut opt, 4); |
| 318 | + let st = TrainState::capture(&m, Some(&opt), 0, 4, 4).unwrap(); |
| 319 | + save_checkpoint(&dir, &st, 8).unwrap(); |
| 320 | + assert!(!PathBuf::from(format!("{}.tmp", dir.display())).exists()); |
| 321 | + assert!(std::fs::read_dir(&dir).unwrap().count() >= 4); // 2+ shards, index, optimizer, state |
| 322 | + |
| 323 | + crate::rng::manual_seed(999); // the restarted run starts with unrelated RNG and weights |
| 324 | + let m2 = Linear::new(2, 2).unwrap(); |
| 325 | + let mut opt2 = Adam::new(m2.parameters(), 0.05); |
| 326 | + let loaded = load_checkpoint(&dir).unwrap(); |
| 327 | + assert_eq!((loaded.epoch, loaded.step, loaded.batch_in_epoch), (0, 4, 4)); |
| 328 | + loaded.restore(&m2, Some(&mut opt2)).unwrap(); |
| 329 | + let second = train_steps(&m2, &mut opt2, 4); |
| 330 | + assert_eq!([first, second].concat(), reference); |
| 331 | + assert_eq!(m2.state_dict()["weight"].to_vec::<f32>().unwrap(), ref_w); |
| 332 | + let _ = std::fs::remove_dir_all(&dir); |
| 333 | + } |
| 334 | + |
| 335 | + #[test] |
| 336 | + fn manager_keeps_the_newest_finds_the_latest_and_saves_in_background() { |
| 337 | + let root = tmp("manager"); |
| 338 | + let m = Linear::new(2, 2).unwrap(); |
| 339 | + let mut mgr = CheckpointManager::new(&root, 2).unwrap(); |
| 340 | + for step in [10u64, 20, 30] { |
| 341 | + let mut st = TrainState::capture(&m, None, 1, step, 0).unwrap(); |
| 342 | + st.extra.insert("best_loss".into(), 0.125 * step as f64); |
| 343 | + mgr.save(&st, step == 30).unwrap(); // the last one goes through the async path |
| 344 | + } |
| 345 | + let latest = mgr.latest().unwrap().unwrap(); |
| 346 | + assert_eq!(mgr.steps(), vec![20, 30]); |
| 347 | + assert_eq!(latest.step, 30); |
| 348 | + assert_eq!(latest.extra["best_loss"], 3.75); |
| 349 | + assert!(latest.optimizer.is_none()); |
| 350 | + let empty = CheckpointManager::new(tmp("empty"), 1).unwrap().latest().unwrap(); |
| 351 | + assert!(empty.is_none()); |
| 352 | + let _ = std::fs::remove_dir_all(&root); |
| 353 | + } |
| 354 | +} |
0 commit comments