research35 min studyLesson 95 in Engineering

Numerical stability and mixed precision

Reason about range, rounding, accumulation, conditioning, and loss scaling before trusting a faster numerical training path.

On this page

What you’ll understand

  • Distinguish representable range from precision and conditioning.
  • Explain what loss scaling can and cannot fix.
  • Design numerical comparisons using meaningful tolerances and quality checks.

Two kernels implement the same real-number expression but produce slightly different floating-point answers. That difference can be expected rounding, a serious stability problem, or an implementation bug. Mixed precision makes this distinction essential: storage, multiplication, accumulation, and optimizer state may use different formats. A numerical investigation follows values through the whole computation instead of treating the model's advertised dtype as a complete description.

Range and precision answer different questions

Floating-point formats allocate bits to sign, exponent, and significand. Exponent range controls how large or small normal values can be; significand precision controls relative spacing within a range. Binary16 and bfloat16 make different tradeoffs, so replacing one with the other changes more than memory use. Subnormal handling and intermediate accumulation formats also matter. Check the documented execution path for the actual operation and hardware rather than assuming all arithmetic uses the input storage format.

For an ordinary correctly rounded operation whose exact result is normal and does not overflow, a relative rounding model is often useful. It is not a universal bound for underflow, overflow, cancellation-relative error, or an entire algorithm. Addition is not associative after rounding: a parallel reduction tree can change the result. A well-conditioned problem can still be implemented unstably, while an ill-conditioned problem may amplify tiny input errors even under a stable implementation.

fl⁡(a∘b)=(a∘b)(1+δ),∣δ∣≤u\operatorname{fl}(a\circ b)=(a\circ b)(1+\delta),\qquad |\delta|\leq u
This standard local model uses unit roundoff u and an ordinary arithmetic operation with correctly rounded normal result, excluding overflow and problematic underflow. It does not directly bound a complete training step.↔ Scroll wide equations horizontally.

Scale gradients without changing the intended update

Loss scaling multiplies the scalar loss before differentiation, making gradients larger before low-precision representation can discard tiny values. Gradients must be unscaled before operations whose meaning depends on their magnitude, such as ordinary gradient clipping, and before the intended optimizer update. If scaled gradients overflow, a dynamic scheme can reduce the scale and skip an unsafe update. Scaling is a range-management technique, not extra significand bits or a cure for a poor algorithm.

Higher-precision accumulation reduces some summation error, and higher-precision master weights can retain small updates that would round away in lower-precision storage. These techniques were central to early mixed-precision training recipes, but modern frameworks can use other format-specific strategies. Loss scaling is often less necessary for bfloat16's wider exponent range than for binary16; that does not imply every bfloat16 operation has adequate precision. Test the selected recipe rather than making a universal format claim.

gs=∇θ(sL)=s∇θL,g=gs/sg_s=\nabla_\theta(sL)=s\nabla_\theta L,\qquad g=g_s/s
For a positive constant scale s independent of θ, exact differentiation gives this identity. Floating-point scaling and unscaling still introduce rounding and may overflow; clipping the scaled gradient changes ordinary clipping semantics.↔ Scroll wide equations horizontally.

Diagnose numerics with a ladder of evidence

Begin with a small deterministic case and a higher-precision reference where feasible. Compare absolute and relative error together, because relative error is unstable near zero. Inspect activation, gradient, and optimizer-state distributions by layer, along with nonfinite counts and skipped updates. A close output for one batch does not prove equivalent training: small systematic errors can accumulate, while harmless nondeterministic rounding may lead to different but similarly good optimization trajectories.

For unstable expressions, change the mathematics of evaluation. Subtracting a maximum before exponentiating in a softmax avoids unnecessary overflow without changing the exact normalized probabilities. Reductions may benefit from better ordering or compensated summation where cost permits. Measure end-to-end quality across seeds after local numerical checks. Report tolerance choices and hardware settings so another investigator can separate expected differences from a regression.

Understand a tiny scaled gradient

Suppose a toy rounding path discards an unscaled gradient of 10⁻⁸, but can represent 10⁻⁵ adequately. Choose loss scale 1,024 and assume no overflow elsewhere.

  1. The exact scaled gradient is 1,024 × 10⁻⁸ = 1.024 × 10⁻⁵, moving it into the assumed usable range.

  2. After storage and computation, unscale by dividing by 1,024; the intended magnitude is again approximately 10⁻⁸, with rounding error remaining.

  3. At learning rate 0.01, the intended parameter update magnitude is 10⁻¹⁰. Whether it changes the stored weight depends on that weight's precision and magnitude.

  4. A higher-precision update accumulator can preserve such small changes, but the scale cannot repair gradients already lost earlier or overflow in unrelated intermediate values.

The result

Scaling may preserve a small gradient's range, while separate accumulation and stability choices determine the quality of the eventual update.

Explore the model

Interactive lab

Interactive lab · optimization

Compare algorithmic instability with rounding

Explore exact-model gradient descent xₙ=(1−η)ⁿx₀ on f(x)=x²/2. With η>2 the iteration diverges and reports values outside the plotting range. The lab uses the stated scalar model; it does not emulate binary16, bfloat16, rounding, or loss scaling.

Compare algorithmic instability with roundingGradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Current readings: Position x0: 2; Objective x²/2: 2; Iteration behavior: Stable step. All parameters are adjustable with the labeled controls below.−4−202402.174.356.528.7Parameter xf(x) = x²/2n = 0
ObjectiveDiscrete iterate
Position x0
2
Objective x²/2
2
Iteration behavior
Stable step
n = 0 · t = 0 s

Gradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA diverging numerical method can fail even before finite-precision effects are considered.

Check your understanding

What does multiplying a loss by a constant scale primarily aim to improve in a low-precision gradient path?

Try it yourself

For logits 1,000 and 999, derive equivalent softmax probabilities without directly exponentiating either large logit. Give approximate values and explain why the transformation helps.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Subtract the maximum logit from both entries before exponentiation.

Compare with the solution

Use logits 0 and −1. Their exponentials are 1 and approximately 0.367879, so probabilities are about 0.731059 and 0.268941. The common exponential factor cancels mathematically, while shifted exponentiation avoids overflow from exp(1,000). This does not eliminate all rounding or every possible softmax-related stability issue.

pi=ezi−m∑jezj−m,m=max⁡jzjp_i=\frac{e^{z_i-m}}{\sum_j e^{z_j-m}},\qquad m=\max_j z_j
For finite real logits, subtracting a common maximum leaves exact softmax unchanged and bounds each exponential argument above by zero.↔ Scroll wide equations horizontally.

Take it with you

  • Inspect storage, computation, accumulation, and optimizer formats separately.
  • Loss scaling addresses range and requires correct unscaling and overflow handling.
  • Combine local error analysis with multi-run quality validation.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.