interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/5

Unit 8 · AI infrastructure · Lesson 4 of 10

Mixed precision, accumulation and activation checkpointing

Lower-precision arithmetic speeds up training and shrinks activations but changes numerical behavior, while gradient accumulation and activation checkpointing trade time for memory. These are the standard knobs for fitting and speeding up training, and interviewers expect you to know their failure modes as well as their benefits.
About 3 h 20 minFocus mode

Step 1: Learn the ideas

  • Floating-point formats: fp32, TF32, fp16, bf16 and fp8 (concept level)
  • Range versus precision: overflow, underflow and rounding
  • Static and dynamic loss scaling; unscaling before clipping
  • Autocast operator lists and fp32 master weights
  • Numerically sensitive operations: softmax, normalization, reductions, losses
  • Gradient accumulation: loss normalization, no_sync, effective batch size
  • Interaction with batch normalization and learning-rate schedules
  • Activation checkpointing: full versus selective, recomputation cost and random state
  • Debugging NaNs and loss spikes

Why it matters

Lower precision is the default way to make training faster and activations smaller; gradient accumulation and activation checkpointing are the default ways to fit larger effective batches and longer contexts into memory. Each knob changes numerics or cost in specific ways. Interviewers probe whether you know why loss scaling exists, what autocast keeps in fp32, and when accumulation is not equivalent to a larger batch.

Core ideas

Formats trade exponent bits (range) against mantissa bits (precision).

  • fp32: 8 exponent bits, 23 mantissa bits.
  • fp16: 5 exponent, 10 mantissa. The largest finite value is 65504 and values below about 6e-8 flush to zero, so small gradients underflow and large activations overflow.
  • bf16: 8 exponent, 7 mantissa. The same range as fp32 with much coarser precision.
  • TF32: a tensor-core mode that keeps the fp32 exponent with a 10-bit mantissa for matmul inputs and accumulates in fp32.
  • fp8 (E4M3, E5M2): narrower still; in practice used with per-tensor or finer scaling factors managed by the framework.

The mixed-precision recipe. Keep an fp32 master copy of the weights; run forward and backward mostly in 16-bit; accumulate matmul results in fp32; keep precision-sensitive operations (softmax, normalization, reductions, losses) in fp32. PyTorch autocast makes this per-operator choice from explicit lists. With fp16, multiply the loss by a scale S before backward so small gradients stay representable, unscale before the optimizer step and before gradient clipping, skip the step and lower S when an inf or NaN appears, and raise S periodically (dynamic loss scaling). bf16's fp32-like range usually makes scaling unnecessary.

Gradient accumulation. Run k micro-batches, sum their gradients, step once. To reproduce a large-batch gradient, normalize correctly: divide each micro-batch's mean loss by k when micro-batches are equal-sized, or normalize by the total token count across all micro-batches when sequence lengths vary. With DDP, skip the all-reduce on all but the last micro-batch (no_sync), or you pay k times the communication. The effective batch is micro-batch × k × data-parallel ranks, and schedules count optimizer steps, not micro-batches. Changing the effective batch usually needs learning-rate retuning; linear scaling is a heuristic, not a law. Batch normalization computes statistics per micro-batch, so accumulation does not reproduce large-batch behavior for models that use it.

Activation checkpointing. Store activations only at segment boundaries and recompute the inside of each segment during backward. Recomputing everything costs about one extra forward pass, roughly a third more compute when backward costs about twice the forward. Chen et al. show that checkpointing every √n layers reduces activation memory for n layers to O(√n). Selective checkpointing recomputes only operations that are cheap to redo but expensive to store, such as attention softmax outputs. Random state must be replayed so dropout masks match; PyTorch's checkpoint utility does this by default.

Common misconceptions

  • "bf16 is strictly better than fp16." bf16 trades precision for range. It avoids loss scaling, but its 7-bit mantissa makes accumulation and small updates noisier, so reductions and master weights still need fp32.
  • "Mixed precision means everything runs in 16-bit." Autocast keeps sensitive operations in fp32, matmuls accumulate in fp32, and the optimizer updates fp32 master weights.
  • "Loss scaling changes the optimization." Done correctly, gradients are unscaled before the update, so updates match except for skipped overflow steps. Clipping still-scaled gradients is a bug.
  • "Gradient accumulation is identical to a larger batch." Only with correct normalization and no batch-dependent layers; batch norm, dropout randomness and data order differ, and throughput is not that of more devices.
  • "Checkpointing reduces all memory." It shrinks activations only; weights, gradients and optimizer state are untouched.

How to approach it

Break things on purpose: train with fp16 and no scaler until gradients underflow or overflow, then add the scaler and watch the scale adapt. Verify that accumulated gradients match large-batch gradients within a tolerance. Measure peak memory and step time with checkpointing on and off. In interviews, connect each choice to range, precision, memory and compute, and say what you would monitor (loss-scale history, inf and NaN counts, gradient norms).

Suggested order

  1. 1Read the Mixed Precision Training paper for its three ingredients: fp32 master weights, loss scaling and higher-precision accumulation.
  2. 2Read the PyTorch AMP documentation, including gradient scaling and the autocast op reference, and list which operations stay in fp32.
  3. 3Read NVIDIA’s Train With Mixed Precision guide for loss-scaling practice and format choices.
  4. 4Read the gradient-checkpointing paper by Chen et al. and the torch.utils.checkpoint documentation, noting how random state is replayed.
  5. 5Do the precision-and-accumulation project: provoke fp16 overflow, verify accumulation equivalence, and time checkpointing on and off.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • Mixed Precision TrainingStart here

    arXiv

    Why master weights, loss scaling and higher-precision accumulation are each necessary for half-precision training.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PyTorch: Automatic Mixed Precision package (torch.amp)Start here

    PyTorch documentation

    Section: Autocast Op Reference

    How autocast and gradient scaling work in practice and which operations are kept in fp32.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • NVIDIA Deep Learning Performance guides (GPU background, matrix multiplication, mixed precision)

    NVIDIA Documentation

    Section: Train With Mixed Precision

    Practical loss-scaling guidance and format considerations from the hardware vendor.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Training Deep Nets with Sublinear Memory Cost

    arXiv

    The compute-for-memory trade-off behind activation checkpointing and the square-root checkpoint spacing.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PyTorch: torch.utils.checkpoint

    PyTorch documentation

    The checkpointing API, its handling of random state and its reentrant and non-reentrant variants.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Write a small training loop with autocast and a gradient scaler, then: (1) disable the scaler with fp16 and observe what happens to small gradients; (2) log the scale factor over steps; (3) compare accumulated gradients from k micro-batches against one large batch with an explicit tolerance, including a variable-length case; (4) measure peak memory and step time with and without checkpointing. Write down predictions before each run.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Why does fp16 training need loss scaling while bf16 usually does not?
  2. Question 2What happens to a step when the scaler finds an inf, and why is that safe?
  3. Question 3Which operations does autocast keep in fp32, and why?
  4. Question 4How should the loss be normalized when accumulating over micro-batches of variable-length sequences?
  5. Question 5Why does batch normalization break the equivalence between accumulation and a larger batch?
  6. Question 6What does full activation checkpointing cost in compute, and what does selective checkpointing change?

You’re done when you can

  • State exponent and mantissa bits of fp32, fp16 and bf16 and explain one failure each format can cause.
  • Write a training loop with autocast and gradient scaling that unscales before clipping, and explain each call.
  • Show numerically that your gradient accumulation matches a large-batch gradient, or explain why it cannot for your model.
  • Predict, then measure, the memory saved and time added by checkpointing a model you choose.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: Quantization, kernels and quality tradeoffs

Your notes and study time

Log study time