Mixed precision: which calculation needs more bits?
混合精度训练
Observe FP16 underflow, rescue a gradient before it vanishes, retain master updates and skip overflowed steps.
mixed-precisionStart with the problem
A small gradient can become zero before an optimizer sees it. A small update can also disappear when added to a much larger weight. These are different failures, and one switch does not repair both.
Mixed-precision training assigns different numerical formats to different operations or stored values. Micikevicius and colleagues combine lower-precision computation with FP32 master weights, loss scaling and selected higher-precision arithmetic. Their reported model experiments are hardware and workload results. The CPU program here demonstrates numerical mechanisms only; it does not run GPU kernels or measure a speedup.
Definitions and derivation
Binary16, commonly called FP16 here, has finite maximum 65504, smallest positive normal value 2⁻¹⁴ and smallest positive subnormal value 2⁻²⁴. Under round-to-nearest, not every number below that last value becomes zero: values sufficiently close to the smallest subnormal can round upward. Our deliberately smaller gradient avoids that ambiguity:
The forward residual x is representable. Its product with x is 2⁻²⁶ and rounds to zero in the demonstrated FP16 multiplication. Scaling the loss before differentiation rescales the backward chain:
The program first multiplies the residual by S, then by x, and unscales in FP32. Scaling an already-zero raw gradient cannot recover it. This ordering follows the paper’s loss-scaling discussion, not a rule to cast every operation to FP16.
A separate problem is storing accumulated updates. Repeatedly subtracting 2⁻¹³ from an FP16 weight at 1 rounds back to 1 in this example. A higher-precision master retains these increments:
The lower-precision copy is refreshed from the master. This does not make FP32 exact for arbitrary values; it simply supplies enough precision for these powers of two. The first tiny-gradient example and the master-weight example deliberately use different update sizes. Even FP32 can lose a sufficiently small increment near 1.
Run the calculation
Run this complete Python 3.12 / NumPy 1.26.4 program on the CPU. It performs explicitly rounded scalar operations; actual autocast policies can keep some operations in FP32 and GPU subnormal handling can differ.
import numpy as np
def small_gradient():
x = np.float16(2.0 ** -13)
residual = x # w=1, target=0
scale = np.float16(256)
raw = np.float16(residual * x)
scaled = np.float16(np.float16(scale * residual) * x)
rescued = np.float32(scaled) / np.float32(scale)
too_late = np.float32(np.float16(scale * raw)) / np.float32(scale)
return float(raw), float(rescued), float(too_late)
def master_updates(steps=64):
if type(steps) is not int or not 0 <= steps <= 128:
raise ValueError('Use 0 to 128 integer steps.')
half, master = np.float16(1), np.float32(1)
delta = np.float32(2.0 ** -13)
for _ in range(steps):
half = np.float16(half - np.float16(delta))
master = np.float32(master - delta)
return float(half), float(master), float(np.float16(master))
def retry_update():
master = np.float32(1)
gradient, rate, scale = np.float32(512), np.float32(1 / 1024), 256
attempts = []
for _ in range(4):
with np.errstate(over='ignore'):
scaled = np.float16(np.float16(gradient) * np.float16(scale))
accepted = bool(np.isfinite(scaled))
if accepted:
master -= rate * (np.float32(scaled) / np.float32(scale))
attempts.append((scale, accepted, float(master)))
if accepted:
return attempts
scale //= 2
raise RuntimeError('No finite gradient within the retry budget.')
if __name__ == '__main__':
print('raw, rescued, scaled too late:', small_gradient())
print('half, master, cast master:', master_updates())
print('scale, accepted, weight:', retry_update())
with np.errstate(over='ignore'):
print('forward overflow:', float(np.float16(500) * np.float16(500)))
Actual output:
raw, rescued, scaled too late: (0.0, 1.4901161193847656e-08, 0.0)
half, master, cast master: (1.0, 0.9921875, 0.9921875)
scale, accepted, weight: [(256, False, 1.0), (128, False, 1.0), (64, True, 0.5)]
forward overflow: inf
The retry example scales a gradient of 512. Scales 256 and 128 overflow FP16; both attempts leave the master at 1. Scale 64 is finite, is unscaled, and yields one accepted update to 0.5. This is a bounded illustrative backoff policy, not an implementation of all GradScaler rules. The final multiplication overflows in the forward pass. Loss scaling cannot repair a forward result that is already infinite.
Format casts, finite checks and scaling are linear in the number of values. A master copy adds storage; savings depend on which activations, parameters and optimizer states use which formats. Report measured end-to-end memory and time on a specified device instead of inferring a universal factor from bit widths.
When the method fails
Choose stable forward arithmetic first, then inspect backward ranges. Unscale before gradient clipping, because clipping scaled values changes the effective threshold. A skipped optimizer step must not silently advance optimizer moments as if an update happened.
The PyTorch 2.8 AMP examples put forward computation under autocast, scale before backward, unscale before clipping, and skip optimizer updates when relevant gradients are nonfinite. With gradient accumulation, keep one scale for the effective batch and unscale only after accumulation. Check numerical behavior against a higher-precision baseline; a finite output alone does not prove an accurate gradient or a useful trained model.
Exercises with answers
- Why does scaling after computing the raw FP16 gradient fail?
Answer 1: The raw value has already rounded to zero. Multiplying zero cannot reconstruct discarded information.
- What is 256 times 2⁻²⁶?
Answer 2: 2⁻¹⁸, which is representable in the demonstrated FP16 format.
- How many optimizer updates occur in the three retry attempts?
Answer 3: One. Two nonfinite attempts are skipped and do not change the master weight.
- Can loss scaling repair the FP16 product 500×500 after it overflows?
Answer 4: No. Change the forward arithmetic or range; scaling the later loss does not restore a finite product.
Sources and next steps
The original mixed-precision paper, Sections 3.1–3.2, separates master weights from loss scaling. The fixed AMP documentation supplies the order of unscaling, clipping and stepping. All numerical outputs above come from original CPU format tests. Continue with floating point for representation errors and Adam for the optimizer state that also needs a precision policy.
Make a prediction, then check
When must loss scaling happen to rescue a tiny backward gradient?
Learning objectives
- Separate gradient underflow, update rounding and forward overflow.
- Explain scaling, master weights and skipped-step ordering.
Prerequisites & connections
Explore related knowledge →References
- Mixed Precision Training — ICLR 2018, arXiv v3
Paulius Micikevicius et al. · 2018 - Automatic Mixed Precision examples — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Mixed Precision Training — ICLR 2018, arXiv v3 · Physical pages 2–4, Sections 3.1–3.2: FP32 master parameters and loss scaling before backward/unscaling before updates.
- Automatic Mixed Precision examples — PyTorch 2.8 · Typical Mixed Precision Training, Working with Unscaled Gradients and Gradient accumulation: finite-gradient step skipping and effective-batch scaling.
Related topics