Unit 6 of 12 · about 4 hours · explain, derive, measure
FP32, TF32, BF16 and FP16 state, autocast and loss-scaling failures
Precision is a memory and stability contract: the wrong accumulation dtype silently deletes small updates, while the wrong loss scale deletes the gradients. Both look like a healthy run with worse results.
You'll be able to
- Explain which training state lives in which precision and where accumulation must stay in FP32.
- Derive the per-dtype byte counts for parameters, gradients and optimizer state of a small model.
- Diagnose lost updates, underflowed gradients and overflowed products from a failing mixed-precision run.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Mixed Precision TrainingMixed Precision Training
Sections 1 to 3: FP32 master weights, loss scaling that lifts gradients above the FP16 underflow point (values below the minimum normal are subnormal and lose precision), and FP32 accumulation; Section 5 for the accuracy-matching evidence across architectures (arXiv:1710.03740v3)
- Dtype states and TF32Machine Learning Engineering Open Book - Training and PyTorch Debugging
Tensor Precision with the ML dtype progression; TF32 (
allow_tf32matmul and cudnn flags); When to use fp32 accumulators (LayerNorm, reductions, gradient accumulation and master weights) - CS336 Assignment 2: mixed-precision accumulationCS336 Assignment 2 (Spring 2026) - Sections 2 and 3
Section 2.1.5
mixed_precision_accumulation: the four-loop0.01 * 1000accumulation in fp32 versus fp16; Section 2.1.5benchmarking_mixed_precision:ToyModeldtype table undertorch.autocastand why LayerNorm is sensitive
Focus on
- Three techniques together make FP16 training match FP32: an FP32 master copy updated by the optimizer, a loss scale keeping small gradients representable in FP16, and FP32 accumulation of products. Each fixes a different failure.
- Autocast keeps parameters in FP32 while running matmuls in low precision: a CPU check shows a Linear output in
torch.bfloat16withweight.dtypestill FP32. Reductions and norms stay wide because they sum many small terms. - TF32 is a process-global matmul mode, default
allow_tf32False in PyTorch 2.14. It changes every matmul silently, so it belongs in the run manifest, not in model code. - The 2018 paper predates BF16 and TF32. Its loss-scaling derivation still holds, but every BF16 range claim must come from the Stas notes or current docs, never from this paper.
Common mistakes · 3
- Testing loss scaling only on clean steps. The skip-and-backoff path runs only after an overflow: put an
infinto one gradient and check that the step is skipped and the scale halves, from 65536 to 32768. This works on CPU in PyTorch 2.14.1. - Casting the master weights to FP16 to save memory. Small updates then round to zero and the model freezes while the loss looks algorithmically stuck.
- Citing the 2018 paper for BF16 behavior. BF16 has the range of FP32 with short mantissa, the opposite tradeoff to FP16, and the paper predates it.
Try it yourself
Closed-book, before checking anything
0.01 * 1000 in fp32-on-fp32, fp16-on-fp16, fp32-on-fp16 and cast-back) and explain which loop drifts and why. Then show one overflow fixed by scaling the loss and one small-update loss fixed by FP32 accumulation.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.FP16 gradients underflow while FP32 loss looks fine. Which of the three techniques is missing or misset?Answer
Loss scaling. In FP16, gradients below round to zero and those below already lose precision; scaling the loss up before backward and the gradients down before the step keeps them representable.
2.A BF16 run keeps parameters in FP32 under autocast. Why not store them in BF16 directly?Answer
The optimizer needs the FP32 master copy so small updates accumulate instead of rounding away. Autocast casts to BF16 only for compute.
3.Why does LayerNorm stay in FP32 under autocast while linears run narrow?Answer
It reduces over many elements, so narrow accumulation compounds rounding and its statistics need range. Linears are products plus a single accumulation that the backend keeps wide.
4.TF32 was enabled halfway through a study. Which comparisons break?Answer
All matmul numerics across the flag change. TF32 rounds differently from FP32, so loss, gradient and timing comparisons across the change confound precision with the studied effect.
Practice
- CS336 Assignment 2:
mixed_precision_accumulationandbenchmarking_mixed_precisionSection 2.1.5 both problems on model sizes your hardware fits: the accumulation error table with a 2 to 3 sentence accuracy comment, and the autocast dtype table with the LayerNorm sensitivity explanation
These are writeup problems with no public tests; checking is your own error table plus the dtype table. Run the accumulation loops on CPU, the autocast table needs one GPU.
You're done when
Your accumulation table predicts which loop drifts, and you can attribute a new mixed-precision failure to scale, accumulation width or master-copy dtype.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- CS336 Assignment 2 (Spring 2026) - Sections 2 and 3Stanford University · required
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. - 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.
- 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.
Also in this 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.
- 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.
- Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required
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. - 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.
- 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_lastpadding 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.