Numerical Formats

Dive 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

16-Bit Formats Halve Memory but Bring Two Hazards

The Low-Precision Trade-Off

x = torch.tensor(300.0)
x.to(torch.float16)**2, x.to(torch.bfloat16)**2
(tensor(inf, dtype=torch.float16), tensor(90112., dtype=torch.bfloat16))
  • Range overflow in fp16: Squaring 300.0 overflows to inf (\max = 65{,}504).
  • Precision rounding in bf16: bf16 keeps 300^2 finite (90{,}112), yet 1.0 + 10^{-3} rounds back to 1.0, freezing direct 16-bit weight updates.

Anatomy of a Floating-Point Number: Range vs. Precision

Exponent vs. Mantissa Bits

x = (-1)^s \cdot 2^e \cdot (1 + f)

  • Exponent bits govern dynamic range: 8 exponent bits give fp32 and bf16 the same \sim 10^{\pm 38} range, whereas 5 exponent bits cap fp16 at 65{,}504.
  • Mantissa bits (t) govern relative precision: Within any octave [2^e, 2^{e+1}), adjacent numbers sit 2^{e-t} apart (\text{eps} = 2^{-t}).

Bit Layouts of fp32, bf16, and fp16 Compared

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}.

Querying Machine Limits with finfo

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:

for dtype in (torch.float32, torch.bfloat16, torch.float16):
    fi = torch.finfo(dtype)
    print(f'{str(dtype):15} max {fi.max:10.3e}  tiny {fi.tiny:9.3e}'
          f'  eps {fi.eps:8.3e}')
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
  • Why range beats precision in deep learning: Activations and gradients span many orders of magnitude across layers; running out of range turns values into inf or 0, whereas a coarser mantissa merely adds mild quantization noise.

Why 16-Bit Weights Stall Training: Small-Update Rounding

The Parameter Update Swamping Trap

w = torch.tensor(1.0)
for dtype in (torch.float32, torch.bfloat16, torch.float16):
    print(f'{str(dtype):14}: {float(w.to(dtype) + 1e-3):.7f}, '
          f'{float(w.to(dtype) + 1e-4):.7f}')
torch.float32 : 1.0010000, 1.0001000
torch.bfloat16: 1.0000000, 1.0000000
torch.float16 : 1.0009766, 1.0000000
  • Master weights rule: Near w = 1.0, bf16 spacing is 2^{-7} \approx 0.0078, so any update |\Delta w| < 0.0039 snaps back to 1.0 unless accumulated in fp32.

Dtype Promotion Rules for Mixed Operands

Mixed-Operand Arithmetic

  • Combining different float widths promotes to the wider format (fp16 + fp32 -> fp32, fp16 + bf16 -> fp32), so a single stray fp32 buffer contaminates a 16-bit pass:
x16 = torch.ones(3, dtype=torch.float16)
x32 = torch.ones(3, dtype=torch.float32)
(x16 + x32).dtype, (x16 + 1.0).dtype, (x16 + torch.arange(3)).dtype
(torch.float32, torch.float16, torch.float16)

Casting a Model to 16 Bits Halves Inference Memory

Whole-Model Dtype Casting

  • Walking the state tree to cast parameters to 16 bits cuts weight memory in half (814,120 B -> 407,060 B).

Casting Every Parameter to 16 Bits

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)
net = net.bfloat16()
X = torch.randn(8, 1, 28, 28)
try:
    net(X)
except RuntimeError as e:
    print(e)
print(net(X.bfloat16()).dtype, param_bytes(net))
mat1 and mat2 must have the same dtype, but got Float and BFloat16
torch.bfloat16 407060

Mixed Precision: fp32 Master Weights + 16-Bit Compute

The AMP Training Loop

Mixed-precision training (Micikevicius et al., 2018) decouples compute precision from storage precision:

  1. Cast for compute: Cast fp32 master weights to bf16 (or fp16) for forward and backward matrix multiplications and activation storage.
  2. Reduce in fp32: Compute loss functions, softmaxes, and layer normalizations in fp32.
  3. Update in fp32: Apply gradients (and Adam’s fp32 moments \mathbf{m}, \mathbf{v}) directly to the fp32 master weights.

Enabling Mixed Precision in Four Lines of Code

Framework Autocast & Policies

A precision policy or context manager keeps weights in fp32 while outputting 16-bit activations:

net = mlp()
with torch.autocast('cpu', dtype=torch.bfloat16):
    Y = net(X)
Y.dtype, net[1].weight.dtype
(torch.bfloat16, torch.float32)

Pure bf16 Weights Stall; Mixed Precision Matches fp32

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
  • 90% of 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.

Why Mixed Precision Keeps the 128 GB Static Floor

Training vs. Inference Memory

  • Static training floor stays 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.
  • Where mixed precision wins: It halves dynamic forward activation memory and doubles Tensor Core matrix-multiply throughput.

Measuring Gradient Underflow in fp16

Why fp16 Needs Loss Scaling

net = mlp()
X, y = batches[0]
F.cross_entropy(net(X), y).backward()
g = net[1].weight.grad.flatten()
g = g[g != 0]
for scale in (1, 2**16):
    print(f'scale {scale:5}: '
          f'{((g * scale).abs() < 2**-14).float().mean():.1%} subnormal, '
          f'{((g * scale).half() == 0).float().mean():.2%} zero')

Gradient Underflow in fp16 and Dynamic Loss Scaling

Why fp16 Needs Loss Scaling

scale     1: 32.5% subnormal, 0.21% zero
scale 65536: 0.0% subnormal, 0.00% zero
  • One-third of gradients drop into subnormals: Unscaled (scale 1), roughly a third of nonzero first-layer gradients fall below 2^{-14} and \sim 0.1\text{--}0.2\% round to zero.
  • Loss scaling (S = 2^{16}): Multiplying the loss by S before backpropagation lifts all of them safely into normal fp16 range.

Automatic Dynamic Loss Scaling in Practice

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}')
  • Dynamic loss scaling starts with a large scale factor S, skips the optimizer step and halves S whenever an inf/NaN gradient appears, and doubles S after a clean streak:
loss 2.030, loss scale 65536

When to Use bf16 vs. fp16 vs. TF32

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.
  • TensorFloat-32 (TF32) math mode: Operates on fp32 tensors while rounding internal matmul inputs to 10 mantissa bits.

Numerical Hazards: Overflow to NaN and Log-Sum-Exp

Guarding 16-Bit Range

s = torch.tensor(60000., dtype=torch.float16) * 2  # Overflows
s, s - s
(tensor(inf, dtype=torch.float16), tensor(nan, dtype=torch.float16))
x = torch.tensor([12.0, 11.0, 10.0], dtype=torch.float16)
x.exp().sum().log(), torch.logsumexp(x, dim=0)
(tensor(inf, dtype=torch.float16), tensor(12.4062, dtype=torch.float16))
  • Shifted Log-Sum-Exp: Subtracting m = \max_i x_i before exponentiating prevents e^{12} \approx 163{,}000 > 65{,}504 from overflowing to inf and NaN.

Numerical Hazard: Running Sums Stall in 16 Bits

Accumulating Reductions in fp32

total16, total32 = np.float16(0), np.float32(0)
term = np.float16(2**-10)
for _ in range(4096):
    total16 += term  # fp16 accumulator
    total32 += term  # fp32 accumulator, same fp16 terms
total16, total32
(np.float16(2.0), np.float32(4.0))
  • Between 2 and 4, adjacent 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: Floating-Point Formats & Mixed Precision

Concept Check

Work out these three numerical precision questions by hand:

  1. In 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?
  2. A gradient entry has magnitude g = 2 \times 10^{-6}. In unscaled 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}?
  3. When dynamic loss scaling encounters an 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:

  1. Spacing is 2^{9 - 7} = 4.0, so 1000.0 + 1.0 = 1000.0: Since 512 = 2^9, adjacent bf16 values sit 4 apart; an increment of 1 is less than half a grid step (2.0) and vanishes.
  2. Subnormal unscaled (\sim 5 bits of precision left); normal when scaled: S \cdot g = 65{,}536 \times 2 \times 10^{-6} \approx 0.131, restoring full 10-bit fp16 precision.
  3. Updating \mathbf{m}, \mathbf{v} with inf permanently poisons Adam with NaNs, while replacing inf with 0 corrupts the running moment history for the largest-gradient parameters.

Summary: Numerical Formats and Mixed Precision

Key Takeaways

  • Format trade-offs: 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.
  • Mixed precision (AMP): Casts fp32 master weights to 16 bits for matmuls and activations, matching fp32 convergence while halving activation memory.
  • Stable reductions: Use shifted logsumexp and fp32 accumulators to prevent overflow and running-sum stagnation.