Unit 1 of 11 · about 4 hours · implement
The recoverable state set and deterministic resume of samplers and RNG streams
A resume that restores weights but not data position or RNG trains a different experiment while the loss looks normal. Every later unit in this section assumes this contract.
You'll be able to
- List the complete resume state of a distributed job: model, optimizer, scheduler, scaler, every RNG stream, sampler position, and config and code identity.
- Resume a multi-process CPU job mid-epoch and prove the next batches, RNG draws and updates match an uninterrupted run.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Deterministic resume: RNG states and loader seedingDistributed Training Guide - Sharded Checkpoints, Determinism and Elastic Training
Code Changes diff:
torch.use_deterministic_algorithms(True), a seededGeneratorwithDistributedSampler,worker_init_fn=_seed_worker, and save plus restore ofrng.ptholding NumPy, Python, torch and per-device CUDA states - Crash-and-restart state disciplineDistributed Training Guide - Sharded Checkpoints, Determinism and Elastic Training
_STATE_PATHload at start,random.seed(rank + world_size * num_steps)from the saved step, rank-0 write between twodist.barrier()calls; README Elastic Training: all workers restart on one failure and ranks are unstable across restarts - Every stream as a Stateful entryTorchFeather - Distributed Checkpoint Manager
CheckpointManager.__init__states map withMODEL,OPTIMIZER,DATALOADER,LR_SCHEDULERplusadditional_states;ModelWrapper,OptimizersContainer,LRSchedulersContainerandBaseDataLoadereach implementStateful
Focus on
- Resume state is every stream that advances: parameters, optimizer moments and step counters, scheduler position, scaler state, each RNG stream, and the sampler epoch plus consumed offset. Each missing stream replays or skips data.
- Sampler resume needs the epoch and the offset inside it: same seed with
set_epoch, then fast-forward past consumed batches. Restarting the iterator replays the epoch from batch 0. - The DCP recipe's
AppStateholds model and optimizer only. Scheduler, scaler, RNG and loader state must be added as furtherStatefulentries, as TorchFeather's states map shows. - Per-worker RNG needs per-worker construction. A
Generatorbuilt in theDatasetconstructor is copied identically into every worker and repeats its stream; reseed fromtorch.initial_seed()insideworker_init_fn.
Common mistakes · 3
- Saving only model and optimizer. The loss curve looks normal while data order and schedule quietly diverge, so check the next-batch sequence, not just the loss.
- Treating the recipe's
get_state_dictpattern as full resume. It manages FSDP names for model and optimizer but knows nothing of scheduler, scaler, RNG or loader position. - Seeding
random.seed(rank + world_size * steps)once and assuming draws stay aligned. Any extra draw on one rank desynchronizes the streams, so reseed from saved step counts at load.
Try it yourself
Closed-book, before checking anything
DistributedSampler loader for 2 steps, and save model, optimizer, torch RNG state, sampler epoch and consumed count. Continue 2 steps as reference. Resume fresh objects from the save, fast-forward the loader, run 2 steps, and show torch.equal on weights. Then restart the loader from batch 0 and show the first batches repeat.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A resumed run matches the reference loss for 50 steps, then diverges slowly. The checkpoint held model, optimizer and scheduler. Name the two most likely missing pieces and the test that tells them apart.Answer
Sampler position and RNG state. Log the first batches after resume and compare with the reference batches at that step: repeated or shifted batches point to the sampler, identical batches with diverging updates point to an unrestored RNG stream.
2.Why does rank 0's file write in
toy.pysit between twodist.barrier()calls?AnswerThe first barrier stops rank 0 from writing state for a step some rank has not finished. The second stops every rank from starting the next step before the write lands. Without them a crash leaves state ahead of or behind the slowest rank.
3.Two
DataLoaderworkers emit identical augmentation streams. What was built in the wrong place, and where should it be built?AnswerA
torch.Generatorbuilt in theDatasetconstructor was copied identically into both workers. Build or reseed it insideworker_init_fnfromtorch.initial_seed().4.
torch.get_rng_state()is saved but CUDA draws still diverge after resume. What is missing?AnswerThe CUDA RNG states from
torch.cuda.get_rng_state_all(), restored per device withtorch.cuda.set_rng_state, plus the NumPy and Python states if the pipeline draws from them.
Practice
- Crash-and-restart loop with the guide
toy.pyRun
toy.pywith two CPU processes with GPUs hidden so it uses gloo: let it crash once, restart, and shownum_stepscontinues from the saved stateEach rank raises with probability 0.001 per step, so a 2-process run crashes within a few hundred steps (step 402 in about 2 s on CPU with PyTorch 2.14.1) and leaves
toy-state.json; a rerun continues from it, so delete the file before a fresh start. Compare post-restart draws with an uninterrupted run and explain the gap: the script reseeds from the step count instead of restoring the RNG state.
You're done when
A mid-epoch resume reproduces the reference run's next batches and weights exactly on CPU, and you can name every stream in the checkpoint plus what breaks when each is dropped.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 more in the section
- TorchFeather - Distributed Checkpoint ManagerTorchFeather · required
Trace components/checkpoint.py through state wrappers, DCP save and load, asynchronous mode, retention and cleanup. Write a failure table for every barrier, future, temporary artifact and deletion boundary.
- Distributed Training Guide - Sharded Checkpoints, Determinism and Elastic TrainingLambda Labs · required
Run
related-topics/elastic-training/toy.pywith two CPU processes (hide any GPU so it uses Gloo) to see a crash-and-restart loop, then read the determinism related topic and the Chapter 4 sharded save and load. Prove the same next batches and updates after one interrupted run.
Also in this section
- Machine Learning Systems Volume II - Chapter 7 Fault ToleranceML Systems Textbook · primary
Read Failure Analysis at Scale, Hardware Fault Taxonomy, Check-and-Verify, Fault Injection Tools and Frameworks, Checkpointing, Failure Detection and Recovery, Elastic Recovery and Distributed Debugging and Observability. Turn them into a failure matrix before implementing the PyTorch DCP lab.
- PyTorch Distributed Checkpoint RecipesPyTorch · required
Complete the distributed checkpoint recipe with a tiny sharded model on CPU, then
dcp.async_savefrom the 2.14 reference at https://docs.pytorch.org/docs/2.14/distributed.checkpoint.html. The recipe saves model and optimizer only: add scheduler, scaler, RNG and dataloader state yourself, then inject partial directories, missing shards and a changed world-size restore. - Machine Learning Engineering Open Book - Checkpoints, Storage and Fault ToleranceStas Bekman · required
Read
training/fault-tolerance/README.md(frequent checkpoints, kill and save switches, watchdogs, preemption) and the "Don't forget the checksums" and benchmark sections ofstorage/README.md. Turn them into an operational save, verify, publish, retain and recover runbook. - Picotron - Checkpoint StateHugging Face · support
Inspect picotron/checkpoint.py and every call site in train.py. List which state is saved, how ranks participate and which DT-1 reproducibility requirements need to be added in your project.
- Nanotron - Distributed SerializationHugging Face · support
Read the serialization section of
docs/docs.md(metadata, per-rank optimizer and RNG shards) and its statement that checkpoints are not topology agnostic, then the reasons insrc/nanotron/serialize/. Use it as the worked example of why resharding is hard. - PyTorch Elastic Run DocumentationPyTorch · support
Use failure modes and membership changes to understand agent, worker group, rendezvous and restart semantics. Implement only bounded local restart tests; elasticity is not a substitute for checkpoint correctness.
- torchftPyTorch · support
Read the README and
train_ddp.py: per-step quorum through the lighthouse, fault-tolerant DDP and HSDP, and live peer recovery. Compare per-step healing with restart-from-checkpoint. - TorchTitan - CheckpointingPyTorch · support
Read
docs/checkpoint.mdand the checkpointer component at a pinned commit: intervals, model-only and export saves, asynchronous modes and keys excluded from loading. - The Llama 3 Herd of Models - Reliability and Operational ChallengesLlama Team, Meta (2024) · support
Read the reliability section and its interruption table (root causes of unexpected interruptions over a 54-day snapshot) and use it to set failure rates in your checkpoint-interval model.
- Bumblebee - DCP and Checkpoint Smoke TestsBumblebee · depth
Only as a possible capstone target: read
primitive/ckpt/dcp.pyand the checkpoint smoke tests in a clean checkout. Its own roadmap lists reshardable optimizer state as a gap. - OLMo-core CheckpointerAi2 · support
Read
src/olmo_core/train/checkpoint.py(_temporary_wd,_get_tmp_dir,_teardown_tmp_dir,_save_metadata) for temp-directory atomic publish with barrier discipline, andsrc/test/train/checkpoint_test.py(run_checkpointer) for the save, find and reload assertions.