Training Pipeline and Framework Internals

Distributed execution magnifies any ambiguity in data order, state ownership, precision or timing. First make one training step observable, reproducible and restartable before adding ranks.

Section 1 of 10 · 12 units · about 48 hours

0/12

By the end you can Interrupt and resume a tiny run with identical data order and optimizer trajectory, account for every major memory category, and diagnose one hidden synchronization or retained-state failure from a step trace.

Units

Build it

Mini project · about 12 to 16 hours

Single-process golden trainer founding trainlab

Create trainlab and build its single-process core: a tiny transformer with a numerical oracle, a versioned corpus with deterministic sampling, and a frozen golden trainer. Every later section proves distributed equivalence against this core, so resume, lineage and ledgers must be exact here first.

  1. 1Create trainlab with manifests/, data/, model/, comm/, parallel/, plan/, ckpt/, faults/, trace/, ext/, tests/ and reports/; add a tiny transformer with a single-process oracle in model/ and a versioned corpus with a tokenizer in data/.
  2. 2Build a deterministic sampler over the versioned corpus with disjoint-coverage tests, stated padding and drop policies and document-to-batch lineage; interrupt a run mid-epoch and prove the resumed record-ID sequence matches the uninterrupted run.
  3. 3Implement accumulation over uneven microbatches with size-weighted averaging and one optimizer step per global batch, matching a full-batch oracle; pass the TensorTonic gradient-accumulation cases and show the naive mean-of-means fails as predicted.
  4. 4Tabulate every training state with owner, dtype and writer; ledger persistent bytes by dtype against measured tensors after the first optimizer update; pass the TensorTonic memory-accountant cases; show a loss-scaling overflow skips and recovers, and checkpointed recompute matches baseline gradients with a smaller peak.
  5. 5Write a custom autograd Function with explicit forward and backward, checked against finite differences; log register_hook against register_post_accumulate_grad_hook order over accumulated steps and test each against the single-process oracle.
  6. 6Freeze the golden trainer, interrupt it mid-run and resume in a fresh process from committed state only; prove consumed-ID and optimizer-trajectory equivalence with the uninterrupted run and refuse resume under a changed config with a named reason.
  7. 7Instrument one step into data, transfer, forward, backward, optimizer and checkpoint phases with synchronization and warmup, reporting spread over repeated trials; capture a labeled profiler trace with memory recording and, on your GPU, a memory snapshot attributing the peak to ledger rows, and locate every torch.compile graph break with torch._dynamo.explain.
What you hand in
  • The trainlab skeleton with model/, data/, manifests/, tests and the frozen golden trainer.
  • Sampler, accumulation, autograd-hook and resume tests with oracle comparisons and the lineage evidence.
  • State-ownership table, dtype-aware memory ledger, phase-timing report and the labeled step trace.
How to check it
How it's graded

Sampler lineage

Pass: Interrupted and uninterrupted runs yield identical record-ID sequences under both padding policies with disjoint coverage proved.

Great: A worker-seeding defect is seeded, caught by the tests, and the lineage traces any batch to document IDs.

Resume equivalence

Pass: Fresh-process resume from committed state matches the uninterrupted trajectory, and changed configs are refused with reasons.

Great: Each state row dropped in turn fails its targeted check, and CPU resume matches exactly with the settings named.

State ledger

Pass: Hand ledger reconciles with measured tensors after the first update, and the accountant cases pass with exclusions stated.

Great: One mispredicted row is explained to allocator or temporary buffers, and recompute keeps gradients while cutting peak.

Autograd correctness

Pass: Custom Function matches finite differences and hook order is logged against the oracle.

Great: A broken backward is shown to fail the check, and accumulation interaction is tested.

Timing honesty

Pass: Phase timers use synchronization and warmup with spread reported, and the trace has no unexplained gap.

Great: Removing warmup or sync is shown to move the numbers, and breaks are each explained.

Resources

  • Machine Learning Systems Volume I - ML Frameworks, Model Training and BenchmarkingML Systems Textbook

    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.

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

    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

    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.

  • Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs

    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

    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.

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

    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

    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)

    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

    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

    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

    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

    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

    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.