x = torch.tensor(300.0)
x.to(torch.float16)**2, x.to(torch.bfloat16)**2Dive into Deep Learning · §5.5
Numerical Precision and Mixed-Precision Training
fp32 vs. bf16 vs. fp16 · update rounding · fp32 master weights · dynamic loss scaling · numerical hazards
The Low-Precision Trade-Off
(tensor(inf, dtype=torch.float16), tensor(90112., dtype=torch.bfloat16))
fp16: Squaring 300.0 overflows to inf (\max = 65{,}504).bf16: bf16 keeps 300^2 finite (90{,}112), yet 1.0 + 10^{-3} rounds back to 1.0, freezing direct 16-bit weight updates.Exponent vs. Mantissa Bits
x = (-1)^s \cdot 2^e \cdot (1 + f)
fp32 and bf16 the same \sim 10^{\pm 38} range, whereas 5 exponent bits cap fp16 at 65{,}504.Opposite 16-Bit Partitions
bf16 truncates fp32: Preserving all 8 exponent bits gives bf16 the exact dynamic range of fp32, making overflow and underflow nearly as rare as in 32-bit training.fp16 prioritizes mantissa over range: Its 10 mantissa bits resolve 8\times finer steps than bf16, but its 5-bit exponent overflows above 65{,}504 and drops into subnormals below 6.1 \times 10^{-5}.Exact Format Boundaries
We can inspect max (largest finite value), tiny (smallest positive normal number), and eps (2^{-t} gap at 1.0) directly in code:
torch.float32 max 3.403e+38 tiny 1.175e-38 eps 1.192e-07
torch.bfloat16 max 3.390e+38 tiny 1.175e-38 eps 7.812e-03
torch.float16 max 6.550e+04 tiny 6.104e-05 eps 9.766e-04
inf or 0, whereas a coarser mantissa merely adds mild quantization noise.The Parameter Update Swamping Trap
torch.float32 : 1.0010000, 1.0001000
torch.bfloat16: 1.0000000, 1.0000000
torch.float16 : 1.0009766, 1.0000000
bf16 spacing is 2^{-7} \approx 0.0078, so any update |\Delta w| < 0.0039 snaps back to 1.0 unless accumulated in fp32.Mixed-Operand Arithmetic
fp16 + fp32 -> fp32, fp16 + bf16 -> fp32), so a single stray fp32 buffer contaminates a 16-bit pass:(torch.float32, torch.float16, torch.float16)
Whole-Model Dtype Casting
814,120 B -> 407,060 B).Whole-Model Dtype Casting
def mlp():
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
nn.Linear(256, 10))
for layer in net[1], net[3]:
nn.init.normal_(layer.weight, std=0.01)
nn.init.zeros_(layer.bias)
return net
def param_bytes(net):
return sum(p.numel() * p.element_size() for p in net.parameters())
net = mlp()
param_bytes(net)The AMP Training Loop
Mixed-precision training (Micikevicius et al., 2018) decouples compute precision from storage precision:
fp32 master weights to bf16 (or fp16) for forward and backward matrix multiplications and activation storage.fp32: Compute loss functions, softmaxes, and layer normalizations in fp32.fp32: Apply gradients (and Adam’s fp32 moments \mathbf{m}, \mathbf{v}) directly to the fp32 master weights.Framework Autocast & Policies
A precision policy or context manager keeps weights in fp32 while outputting 16-bit activations:
(torch.bfloat16, torch.float32)
Fashion-MNIST Training Comparison
Training identical Fashion-MNIST MLPs for 1{,}000 SGD steps at \eta = 0.01 across three precision modes shows why fp32 master weights are non-negotiable:
validation accuracy: fp32 0.684, bf16 weights 0.639, mixed 0.685
bf16 updates vanish: With pure bf16 weights, roughly 90\% of first-layer updates fall below half the local bf16 spacing, leaving the loss at \sim 1.15 after 1{,}000 steps while mixed precision tracks fp32 (\sim 0.85) virtually on top of each other.Training vs. Inference Memory
128 GB: Mixed precision must retain fp32 master weights (32 GB), fp32 gradients (32 GB) and fp32 Adam moments \mathbf{m}, \mathbf{v} (64 GB); the 16-bit values of the forward pass are cast from them.Why fp16 Needs Loss Scaling
Why fp16 Needs Loss Scaling
scale 1: 32.5% subnormal, 0.21% zero
scale 65536: 0.0% subnormal, 0.00% zero
scale 1), roughly a third of nonzero first-layer gradients fall below 2^{-14} and \sim 0.1\text{--}0.2\% round to zero.fp16 range.GradScaler & LossScaleOptimizer
net = mlp()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
scaler = torch.amp.GradScaler('cpu')
for X, y in batches[:20]:
with torch.autocast('cpu', dtype=torch.float16):
loss = F.cross_entropy(net(X), y)
optimizer.zero_grad()
scaler.scale(loss).backward() # Gradients of S * loss
scaler.step(optimizer) # Divide by S, skip the step on inf/NaN
scaler.update() # Adjust S
print(f'loss {loss.item():.3f}, loss scale {scaler.get_scale():.0f}')inf/NaN gradient appears, and doubles S after a clean streak:loss 2.030, loss scale 65536
Hardware Precision Selection Guide
bfloat16 mixed precision (Ampere/Hopper/TPU default): fp32 master weights + bf16 compute with no loss scaling needed.float16 mixed precision + GradScaler (Volta/Turing GPUs): Prevents 5-bit exponent gradient underflow.TF32) math mode: Operates on fp32 tensors while rounding internal matmul inputs to 10 mantissa bits.Guarding 16-Bit Range
(tensor(inf, dtype=torch.float16), tensor(nan, dtype=torch.float16))
(tensor(inf, dtype=torch.float16), tensor(12.4062, dtype=torch.float16))
inf and NaN.Accumulating Reductions in fp32
(np.float16(2.0), np.float32(4.0))
fp16 numbers sit 2^{-9} apart, so 2 + 2^{-10} rounds back to 2.0 forever; always accumulate sums and normalizations in fp32.Concept Check
Work out these three numerical precision questions by hand:
bfloat16 (7 mantissa bits), what is the grid spacing between adjacent representable numbers in the interval [512, 1024), and what does bf16(1000.0) + bf16(1.0) evaluate to?fp16 (tiny = 6.1 \times 10^{-5}, min subnormal = 6.0 \times 10^{-8}), is g normal, subnormal, or zero? What happens when scaled by S = 2^{16}?inf gradient on step t, why must it skip updating Adam’s moments \mathbf{m} and \mathbf{v} rather than zeroing out the inf entry?Answers:
bf16 values sit 4 apart; an increment of 1 is less than half a grid step (2.0) and vanishes.fp16 precision.inf permanently poisons Adam with NaNs, while replacing inf with 0 corrupts the running moment history for the largest-gradient parameters.Key Takeaways
fp32 (1+8+23) holds master weights, Adam moments, and reductions; bf16 (1+8+7) matches fp32 range without loss scaling; fp16 (1+5+10) requires dynamic loss scaling S \cdot L.fp32 master weights to 16 bits for matmuls and activations, matching fp32 convergence while halving activation memory.logsumexp and fp32 accumulators to prevent overflow and running-sum stagnation.