TExcelTAD
Home › Math for Deep Learning & LLMs › Floating Point: fp32, fp16 and bf16

Floating Point: fp32, fp16 and bf16

Networks are trained on hardware that computes with limited precision. Halving the number of bits halves memory and roughly doubles throughput, which is why modern training uses 16-bit formats. But fewer bits mean a smaller range and coarser rounding, and knowing exactly what each format can represent explains loss scaling, why bf16 replaced fp16, and why some operations stay in fp32.

Anatomy of a float

A floating-point number is (−1)s⋅1.m⋅2e−bias(-1)^s \cdot 1.m \cdot 2^{e - \text{bias}}: a sign bit, an exponent that sets the range, and a mantissa that sets the precision.

Format Bits (sign, exponent, mantissa) Largest value Smallest normal Machine epsilon
fp32 1, 8, 23 about 3.4×10383.4 \times 10^{38} about 1.2×10−381.2 \times 10^{-38} 2−23≈1.2×10−72^{-23} \approx 1.2 \times 10^{-7}
fp16 1, 5, 10 65504 about 6.1×10−56.1 \times 10^{-5} 2−10≈9.8×10−42^{-10} \approx 9.8 \times 10^{-4}
bf16 1, 8, 7 about 3.4×10383.4 \times 10^{38} about 1.2×10−381.2 \times 10^{-38} 2−7≈7.8×10−32^{-7} \approx 7.8 \times 10^{-3}

Machine epsilon is the gap between 1 and the next representable number: relative rounding errors are about ϵ/2\epsilon/2. bf16 keeps fp32's exponent (same range) but has far fewer mantissa bits (coarser); fp16 is more precise than bf16 but overflows above 65504.

python · try it yourself
import numpy as np

for t in (np.float32, np.float16):
    fi = np.finfo(t)
    print(f"{t.__name__}: max {float(fi.max):.4g}, smallest normal {float(fi.tiny):.4g}, eps {float(fi.eps):.4g}")
print("fp16 overflow: 300 * 300 =", np.float16(300) * np.float16(300))
print("fp16 underflow: 1e-8 ->", np.float16(1e-8))
print("fp16 rounding: 2048 + 1 =", np.float16(2048) + np.float16(1))
float32: max 3.403e+38, smallest normal 1.175e-38, eps 1.192e-07
float16: max 6.55e+04, smallest normal 6.104e-05, eps 0.0009766
fp16 overflow: 300 * 300 = inf
fp16 underflow: 1e-8 -> 0.0
fp16 rounding: 2048 + 1 = 2048.0

NumPy has no bf16 type, but we can simulate it: bf16 is the top 16 bits of an fp32, so rounding an fp32 to its top 16 bits (round to nearest even, as hardware does) shows its precision.

python · try it yourself
import numpy as np

def to_bf16(x):
    a = np.asarray(x, dtype=np.float32).copy()
    bits = a.view(np.uint32)
    bits += 0x7FFF + ((bits >> 16) & 1)          # round to nearest even
    bits &= 0xFFFF0000
    return bits.view(np.float32)

for v in (1.0, 1.001, 3.14159265, 1e30, 1e-30):
    print(f"{v:<12g} -> bf16 {float(to_bf16(v)):.8g}")
print("1 + 1/256 in bf16:", float(to_bf16(1 + 1 / 256)), " 1 + 1/128:", float(to_bf16(1 + 1 / 128)))
1            -> bf16 1
1.001        -> bf16 1
3.14159      -> bf16 3.140625
1e+30        -> bf16 1.0002556e+30
1e-30        -> bf16 9.9840208e-31
1 + 1/256 in bf16: 1.0  1 + 1/128: 1.0078125

bf16 represents 103010^{30} and 10−3010^{-30} without trouble but rounds π\pi to about 3.14: three significant digits.

What goes wrong and the fixes

  • Overflow in fp16. Large activations or squared values exceed 65504 and become inf. Fix: bf16, or keep sensitive operations (softmax, norms, losses) in fp32.
  • Underflow of small gradients in fp16. Gradients below about 6×10−86 \times 10^{-8} (the smallest subnormal) become 0. Fix: loss scaling: multiply the loss by a factor such as 2162^{16} before backprop, divide the gradients by it before the update.
  • Lost updates. Adding a tiny update to a large weight can round to no change at all (w+ηg=ww + \eta g = w). Fix: keep an fp32 master copy of the weights and apply updates there.
  • Accumulation error. Long sums in low precision drift. Fix: accumulate matrix products in fp32 (tensor cores do this).

In software

  • torch.autocast(dtype=torch.bfloat16) runs matrix products in bf16 and keeps reductions in fp32; torch.cuda.amp.GradScaler implements dynamic loss scaling for fp16.
  • Quantized inference goes further, to int8, fp8 or 4-bit formats, with per-channel scale factors.
  • Weight memory for inference is parameters times bytes per parameter: 2 bytes in bf16 (Counting Parameters and FLOPs).

Go further: Mixed Precision: float16 and bfloat16 shows what breaks in pure 16-bit training and the automatic mixed-precision recipe that fixes it.

Exercises

Exercise 1: Lost update

A weight equals 1.0 in bf16 and the update is +0.002+0.002. What is the stored result?

Answer

Still 1.0.

Solution

The spacing of bf16 numbers just above 1 is 2−7=0.00781252^{-7} = 0.0078125, so 1.0021.002 rounds back to 1. An fp32 master copy (spacing 1.2×10−71.2 \times 10^{-7}) keeps the update.

Exercise 2: Loss scaling

An fp16 gradient of 10−810^{-8} would underflow. What does it become with a loss scale of 2162^{16}?

Answer

About 6.6×10−46.6 \times 10^{-4}, safely representable.

Solution

10−8⋅65536≈6.55×10−410^{-8} \cdot 65536 \approx 6.55 \times 10^{-4}. After the backward pass, dividing by 2162^{16} in fp32 restores the true value.

Exercise 3: Summing in fp16 (code)

Add 0.10.1 to an fp16 accumulator 10,000 times. What do you get, and why?

Answer

The sum gets stuck at 256, far below 1000.

Solution

Between 256 and 512 the fp16 spacing is 0.250.25, and adding 0.10.1 rounds back to the same number.

python · try it yourself
import numpy as np
s = np.float16(0)
for _ in range(10000):
    s = np.float16(s + np.float16(0.1))
print(s)
256.0

Test yourself

bf16 has the same exponent width as fp32. What does that give it?

  1. The same precision as fp32
  2. The same range as fp32, but much lower precision
  3. A larger range than fp32
  4. No advantage over fp16

Loss scaling in fp16 training prevents…

  1. overflow of weights
  2. underflow of small gradients to zero
  3. the need for a learning rate
  4. bf16 rounding

Why keep an fp32 master copy of the weights in mixed-precision training?

  1. fp32 is faster
  2. Small updates to large weights would round away in 16-bit
  3. GPUs require it
  4. To double the memory