7 routes42 sections324 units

Unit 8.7 · about 5 h

227 / 324

Complete checkpoints, atomic writes and reproducibility boundaries

Resume bugs waste entire training runs: the loss looks fine while the data order, the schedule, or the augmentation stream quietly diverges. The checkpoint contract is what makes a restart a continuation instead of a new experiment.

  • implement

You can now

  • Save and restore every state a resume needs: model, optimizer, scheduler, scaler, epoch, RNG and data position.
  • Write checkpoints atomically so a crash never leaves a half-written file on the load path.
  • State the exact reproducibility boundary: what matches bitwise, what matches statistically, and what never matches.

Covers

  • Complete checkpoint and resume state
  • Atomic writes and reproducibility boundaries

Study, in this order

3 steps

  1. General checkpoints for resume
    PyTorch - reliability and performance recipes

    What is a state_dict; Saving and Loading a General Checkpoint: save and load patterns, optimizer state, 2 to 3 times model size, .tar convention, eval versus train mode; the best_model_state reference pitfall

    Depth · Skip Saving an Exported Program and the DataParallel section unless your model uses them.

  2. Reproducibility: seeds, determinism and data loading
    PyTorch - checkpointing, numerical accuracy and CUDA semantics

    Controlling sources of randomness including manual_seed across devices; Avoiding nondeterministic algorithms with the cross-release and CPU-versus-GPU limits; DataLoader worker seeding with worker_init_fn and generator; CUDA convolution benchmarking versus determinism

  3. Atomic renames for checkpoint writes
    Python os - `os.replace`

    os.replace: a successful rename is atomic, so write the checkpoint to a temp file in the same directory, flush and fsync, then replace the final name

Focus on

  • A resume checkpoint is a dict of state, not a model file: epoch, model, optimizer, scheduler, scaler, RNG states and the sampler position all belong in it.
  • state_dict returns references to live tensors. Training on after building the dict mutates the saved copy too; serialize to disk or deepcopy at save time.
  • Per-worker RNG needs explicit construction. A Generator built in Dataset init is fork-copied identically into every worker and repeats its stream.
  • Exact resume is realistic only on one machine, build and device kind, with deterministic algorithms. The reproducibility notes promise nothing across releases, platforms, or CPU versus GPU, so declare a tolerance there.

Reproduce closed-book

On CPU, train a small model with dropout for 3 steps, save model, optimizer and torch RNG state to disk, and train 2 more steps. Load the file into fresh model and optimizer objects, restore the RNG state, run the same 2 steps, and show the weights equal the continuous run (torch.equal held on CPU with PyTorch 2.14). Rerun without restoring the RNG and show the weights differ.

Traps

  • Reloading from the in-memory dict after further training. The dict aliases live optimizer buffers, so the resume silently starts from the later state.
  • Seeding only torch.manual_seed with several DataLoader workers. Global RNGs get per-worker seeds, but a copied Generator object repeats exactly; build it per worker from torch.initial_seed.
  • Writing the checkpoint straight to the final name. A mid-write crash leaves a corrupt file on the load path; temp file plus os.replace avoids it.

Practice

TrenTorch: Resume-from-checkpoint

Implement save_checkpoint, train_n_steps, resume_from_full_checkpoint and resume_from_weights_only around an Adam step

Restoring \(m\), \(v\) and \(t\) reproduces the uninterrupted weights; a weights-only resume restarts Adam's bias correction and diverges. The section mini-project then adds resume equivalence and interruption handling with declared tolerances.

Self-test

  1. Name the checkpoint contents for exact resume on one GPU of SGD with momentum, a StepLR scheduler, fp16 AMP with a GradScaler and a shuffled loader.

  2. A saved dict is kept in memory, training continues, then a fresh optimizer loads that dict. Why are its buffers wrong?

  3. Two DataLoader workers emit identical augmentation streams. State the bug and the fix.

  4. The job dies mid-write and the checkpoint is corrupt. What write pattern survives this?

Completion criterion

Stop when

Your disk-roundtrip resume matches the continuous run (exactly on CPU, or within a declared tolerance elsewhere), and a changed-seed or unrestored-RNG resume is caught by your own equivalence check.

Mark passed, then open 8.8 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • PyTorch - reliability and performance recipes
    PyTorchprimarycourse
    Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.
  • PyTorch - checkpointing, numerical accuracy and CUDA semantics
    PyTorchrequiredreference
    Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.
  • Python os - `os.replace`
    Python Software Foundationreferencereference
    Read os.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, then replace the final name.

Also in this section

  • PyTorch - compiler troubleshooting
    PyTorchrequiredreference
    Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.
  • Deep Learning Training Debugger
    Roadmap-Finalreferenceassessment
    Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.
  • TensorTonic - mixed-precision memory and transformer FLOPs
    TensorTonicsupportpractice
    Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.
  • Learn PyTorch - profiler walkthrough
    Daniel Bourkeoptionalimplementation
    Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.
  • TrenTorch - precision, checkpointing and resume
    TrenTorchsupportpractice
    Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.
  • Hands-On Machine Learning with Scikit-Learn and PyTorch
    Aurelien Geron (O'Reilly, 2025)supporttheory
    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels