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

Model, optimizer, scheduler, scaler, RNG and dataloader stateDeterministic resume of sampler, shuffle and RNG streams
1

Read

In this order, only the parts listed

0 of 3 done

  1. Deterministic resume: RNG states and loader seedingDistributed Training Guide - Sharded Checkpoints, Determinism and Elastic Training

    Code Changes diff: torch.use_deterministic_algorithms(True), a seeded Generator with DistributedSampler, worker_init_fn=_seed_worker, and save plus restore of rng.pt holding NumPy, Python, torch and per-device CUDA states

  2. Crash-and-restart state disciplineDistributed Training Guide - Sharded Checkpoints, Determinism and Elastic Training

    _STATE_PATH load at start, random.seed(rank + world_size * num_steps) from the saved step, rank-0 write between two dist.barrier() calls; README Elastic Training: all workers restart on one failure and ranks are unstable across restarts

  3. Every stream as a Stateful entryTorchFeather - Distributed Checkpoint Manager

    CheckpointManager.__init__ states map with MODEL, OPTIMIZER, DATALOADER, LR_SCHEDULER plus additional_states; ModelWrapper, OptimizersContainer, LRSchedulersContainer and BaseDataLoader each implement Stateful

2

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 AppState holds model and optimizer only. Scheduler, scaler, RNG and loader state must be added as further Stateful entries, as TorchFeather's states map shows.
  • Per-worker RNG needs per-worker construction. A Generator built in the Dataset constructor is copied identically into every worker and repeats its stream; reseed from torch.initial_seed() inside worker_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_dict pattern 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.
3

Try it yourself

Closed-book, before checking anything

On CPU with 2 gloo processes, train a tiny model with dropout under a 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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 2.Why does rank 0's file write in toy.py sit between two dist.barrier() calls?Answer

    The 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. 3.Two DataLoader workers emit identical augmentation streams. What was built in the wrong place, and where should it be built?Answer

    A torch.Generator built in the Dataset constructor was copied identically into both workers. Build or reseed it inside worker_init_fn from torch.initial_seed().

  4. 4.torch.get_rng_state() is saved but CUDA draws still diverge after resume. What is missing?Answer

    The CUDA RNG states from torch.cuda.get_rng_state_all(), restored per device with torch.cuda.set_rng_state, plus the NumPy and Python states if the pipeline draws from them.

5

Practice

  • Crash-and-restart loop with the guide toy.py

    Run toy.py with two CPU processes with GPUs hidden so it uses gloo: let it crash once, restart, and show num_steps continues from the saved state

    Each 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.py with 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_save from 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 of storage/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 in src/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.md and 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.py and 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, and src/test/train/checkpoint_test.py (run_checkpointer) for the save, find and reload assertions.