Unit 7 of 9 · about 5 hours · implement

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.

You'll be able to

  • 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 stateAtomic writes and reproducibility boundaries
1

Read

In this order, only the parts listed

0 of 3 done

  1. General checkpoints for resumePyTorch - 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

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

  2. Reproducibility: seeds, determinism and data loadingPyTorch - 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 writesPython 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

2

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.
Common mistakes · 3
  • 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.
3

Try it yourself

Closed-book, before checking anything

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.
4

Quiz yourself

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

0 got · 0 missed

  1. 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.Answer

    Model, optimizer with its momentum buffers, scheduler, scaler, epoch and step, CPU and CUDA RNG states, and the sampler position or loader generator state.

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

    state_dict returns references, so continued training mutated the same buffers the dict aliases. Serialize to disk or deepcopy at save time.

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

    A Generator built in Dataset init was fork-copied identically into both workers. Reseed it per worker in worker_init_fn from torch.initial_seed(), or create it lazily inside the worker.

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

    Write to a temp file in the same directory, flush and fsync, then os.replace onto the final name. Readers only ever see complete files.

5

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 , and 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.

You're done 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.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 6 more in the section
  • PyTorch - reliability and performance recipesPyTorch · primary

    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 semanticsPyTorch · required

    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 Foundation · reference

    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 troubleshootingPyTorch · required

    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 DebuggerRoadmap-Final · reference

    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 FLOPsTensorTonic · support

    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 walkthroughDaniel Bourke · optional

    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 resumeTrenTorch · support

    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 PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.