Unit 1 of 12 · about 4 hours · explain, implement

Run identity, launch configuration and the setup, step, save, load and teardown contract

Distributed runs multiply every unspecified choice: one missing flag or untracked code change becomes a different experiment on every rank. A written run contract makes resume and blame possible before any parallelism is added.

You'll be able to

  • Explain what belongs in an immutable run identity and why a seed alone cannot reproduce a run.
  • Implement setup, step, save, load and teardown in one script so a relaunch resumes from committed state instead of restarting.
  • Capture the launch configuration and environment needed to tell a changed setup apart from a broken resume.

Covers

Launch configuration, immutable run identity and environment captureFramework contracts for setup, step, save, load and teardown
1

Read

In this order, only the parts listed

0 of 3 done

  1. Single-GPU trainer end to endDistributed Training Guide - Chapter 1 and Related Topics

    README.md Code explanation from Argument parsing through Checkpoints; train_llm.py _get_parser, LocalTimer, the checkpoint-save block writing model.pt, optimizer.pt, lr_scheduler.pt and state.json, and the resume branch reloading them and skipping finished steps

  2. Pipeline architecture and the benchmark envelopeMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking

    Model Training, Pipeline Architecture; Training Benchmarks in https://mlsysbook.ai/vol1/benchmarking/benchmarking.html for the full envelope of commit, checksum, preprocessing, seed plan, versions, precision, batch schedule, topology, power and thermal, and checkpoint behavior

  3. Reproducible environment captureMachine Learning Engineering Open Book - Training and PyTorch Debugging

    enforce_reproducibility: seed handling, CUBLAS_WORKSPACE_CONFIG set before CUDA init, torch.use_deterministic_algorithms(True), cudnn.benchmark=False; Reproduce env: modules.txt, env.txt, pip freeze, git diff of local installs

2

Focus on

  • The run identity is code version, dataset version, config, seeds, and hardware and software versions together. Logging os.environ and args, as the single-GPU guide script does, starts the identity but pip freeze and the dataset version complete it.
  • state.json carries epoch, global_step, epoch_step and running_loss beside the three state dicts. Resume restores all of them and skips finished batches; loading weights alone restarts the schedule midstream.
  • Process-global flags are environment, not model config. In PyTorch 2.14 the default is torch.backends.cuda.matmul.allow_tf32 False with torch.get_float32_matmul_precision returning highest; record both in the manifest.
  • Teardown belongs to the contract: workers shut down, barriers complete, and only committed checkpoints are read back.
Common mistakes · 3
  • Treating the random seed as the full identity. Seeding alone still leaves algorithm choice and data position unspecified.
  • Reading a checkpoint written by different code or config and calling the mismatch a resume bug. Reject resume under a changed configuration instead.
  • Saving only model.state_dict. Optimizer, scheduler and data position are state too; without them the trajectory diverges after resume.
3

Try it yourself

Closed-book, before checking anything

From a blank file, write a loop that saves model, optimizer, scheduler and a position record every N steps, stops mid-epoch, and relaunches to the same loss trajectory. State which files must exist before the resumed run may continue.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.A resumed run reproduces the loss values but the learning rate schedule looks shifted by half an epoch. Which state was likely not restored?Answer

    The scheduler state and the position record (epoch_step or global_step). Weights plus optimizer without scheduler and position restart the schedule at the wrong point.

  2. 2.Why is logging os.environ and parsed args insufficient as a run identity?Answer

    It misses code version, dataset version, installed package versions and process-global flags. Two runs can share env and args yet differ in code, data or library behavior.

  3. 3.Where must CUBLAS_WORKSPACE_CONFIG be set, and why?Answer

    Before any CUDA work, as the Stas recipe does; it raises if CUDA is already initialized. cuBLAS reads the setting when it creates its workspaces, and with deterministic algorithms on PyTorch raises at a cuBLAS call when the variable is missing.

  4. 4.A crash leaves new weight files but no new state.json. Should the resumed run load the new weights?Answer

    No. Only a committed checkpoint with its position record is readable. Rebuild or discard the uncommitted shards first.

5

Practice

  • 01-single-gpu: interrupted and resumed run

    Outputs and Resuming plus Checkpoints: with one GPU on your machine, launch train_llm.py on the smallest model that fits, stop it mid-epoch, relaunch with the same experiment name and show it resumes from state.json instead of restarting. On a CPU-only machine run the same interrupt-and-resume cycle with the loop from the reproduce step, since this script hardcodes CUDA, fused=True and bfloat16.

    Keep the timer and memory logs from both halves as the resume evidence.

You're done when

You can list the complete identity for your own loop, and an interrupted run continues its loss trajectory instead of restarting it.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • Machine Learning Systems Volume I - ML Frameworks, Model Training and BenchmarkingML Systems Textbook · primary

    Read Model Training (Iron Law of Training Performance, Pipeline Architecture, Identifying Bottlenecks, Pipeline Optimizations), then ML Frameworks (Execution Problem, Differentiation Problem, Anatomy of a Training Step) at https://mlsysbook.ai/vol1/frameworks/frameworks.html and Benchmarking (Training Benchmarks, Benchmarking Best Practices) at https://mlsysbook.ai/vol1/benchmarking/benchmarking.html. Turn the reading into a state-ownership table and a deterministic train-resume trace before the CS336 exercises.

  • Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required

    Trace 01-single-gpu/train_llm.py end to end with its README (argument parsing, model initialization, checkpoint save of model, optimizer and scheduler, timers and memory statistics), then the related-topics folders on determinism, gradient accumulation, effective batch size and optimized data loading. Produce a state-ownership table and prove identical data order and optimizer trajectory after a controlled interruption.

  • Machine Learning Engineering Open Book - Training and PyTorch DebuggingStas Bekman · required

    Read training/README.md, training/dtype.md, training/reproducibility/README.md and the tiny-model, memory and profiling sections of debug/pytorch.md. Use its commands as a field checklist while diagnosing your own loop.

Also in this section

  • Ultra-Scale Playbook - First Steps: Training on One GPUHugging Face · required

    Read Memory usage in transformers, Activation recomputation and Gradient accumulation, then Appendix A1 on profiling. Derive weight, gradient, optimizer and activation bytes for your tiny model before measuring; the interactive calculator does not show its sequence length or recomputation setting, so compare it with the formulas only after setting both.

  • CS336 Assignment 2 (Spring 2026) - Sections 2 and 3Stanford University · required

    Complete benchmarking_script, nsys_profile, mixed_precision_accumulation, benchmarking_mixed_precision, memory_profiling and gradient_checkpointing on model sizes your hardware fits, with your own solutions. Keep timing tables, memory predictions and failure notes; the FlashAttention kernel (Section 4) and the leaderboard (Section 9) are outside this stage.

  • AI Systems Performance Engineering - Chapters 13 and 14Chris Fregly (O'Reilly) · support

    Read Chapter 13 on NVTX markers, the PyTorch profiler, memory and allocator tuning, activation checkpointing and the data input pipeline, and the Chapter 14 sections on graph breaks and recompilation. Use them to explain one profiled step of your own trainer; treat bundled expectations as the author's hardware results.

  • Transformer Math 101EleutherAI · support

    Use the compute, parameter, optimizer, gradient and activation memory equations as a second derivation of your memory ledger. Check each per-dtype byte count against your own trainer's state.

  • Mixed Precision TrainingMicikevicius et al. (ICLR 2018) · support

    Read the sections on FP32 master weights, loss scaling and FP32 accumulation. Connect each to a failure your trainer can show: lost small updates, underflowed gradients or overflowed products.

  • PyTorch Profiler RecipesPyTorch · support

    Use the profiler, memory snapshot and benchmark recipes only when the CS336 handout calls for them. Annotate one complete step and explain every visible gap or synchronization event.

  • TensorTonic - Training Arithmetic ProblemsTensorTonic · support

    Solve Training FLOP Estimator, Mixed-Precision Training Memory Accountant and Gradient Accumulation Equivalence (free problems in the Language Modeling from Scratch plan) before the CS336 measurements.

  • Distributed Training SubsystemRoadmap-Final · support

    Start Milestone A with the deterministic sampler, state manifest, event trace and single-process oracle. Keep extending this repository through DT-9.

  • PyTorch data loading API - DataLoader, Sampler and multi-process loadingPyTorch · reference

    Read Data Loading Order and Sampler, Single- and Multi-process Data Loading with its Randomness subsection, and the DistributedSampler entry for set_epoch, drop_last padding and worker seeding. Use it to define sampler position and worker sharding for the lineage and resume units.

  • PyTorch Autograd mechanics notePyTorch · reference

    Read How autograd encodes the history with Saved tensors, Hooks for saved tensors, and Backward Hooks execution (whether each hook fires and in which order). Use it for the autograd graph, saved-tensor and hook-ordering claims.