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
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
- Run identity, launch configuration and the setup, step, save, load and teardown contract4h
- Dataset manifests, document-to-batch lineage and deterministic sampler position4h
- Microbatches, accumulation, global batch, token accounting and update semantics4h
- Who owns parameters, buffers, gradients, optimizer, scheduler, scaler, RNG and loader state4h
- Autograd graphs, backward scheduling, saved tensors and gradient hooks5h
- FP32, TF32, BF16 and FP16 state, autocast and loss-scaling failures4h
- Persistent, activation, temporary and allocator memory in one training step4h
- Activation checkpointing, recomputation cost and selective policies4h
- Step timelines and repeated-trial benchmark hygiene4h
- PyTorch profiler traces, memory snapshots and NVTX ranges for a training step3h
- `torch.compile` on a training step: graph boundaries, recompiles and breaks3h
- Exact resume state and tiny deterministic fixtures for systems debugging5h
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.
- 1Create
trainlabwithmanifests/,data/,model/,comm/,parallel/,plan/,ckpt/,faults/,trace/,ext/,tests/andreports/; add a tiny transformer with a single-process oracle inmodel/and a versioned corpus with a tokenizer indata/. - 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.
- 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.
- 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.
- 5Write a custom autograd
Functionwith explicit forward and backward, checked against finite differences; logregister_hookagainstregister_post_accumulate_grad_hookorder over accumulated steps and test each against the single-process oracle. - 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.
- 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.compilegraph break withtorch._dynamo.explain.
What you hand in
- The
trainlabskeleton withmodel/,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
- Self-grade with the rubric below
- TensorTonic: Gradient Accumulation Equivalence
Pass the public uneven-size cases in your harness before the trainer comparison.
- TensorTonic: Mixed-Precision Training Memory Accountant
Pass the public dtype cases; state the allocator and master-copy exclusions.
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_profilingandgradient_checkpointingon 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.pyend 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_lastpadding 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.