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 : 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 | about | |
| fp16 | 1, 5, 10 | 65504 | about | |
| bf16 | 1, 8, 7 | about | about |
Machine epsilon is the gap between 1 and the next representable number: relative rounding errors are about . bf16 keeps fp32's exponent (same range) but has far fewer mantissa bits (coarser); fp16 is more precise than bf16 but overflows above 65504.
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.
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 and without trouble but rounds 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 (the smallest subnormal) become 0. Fix: loss scaling: multiply the loss by a factor such as 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 (). 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.GradScalerimplements 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 . What is the stored result?
Answer
Still 1.0.
Solution
The spacing of bf16 numbers just above 1 is , so rounds back to 1. An fp32 master copy (spacing ) keeps the update.
Exercise 2: Loss scaling
An fp16 gradient of would underflow. What does it become with a loss scale of ?
Answer
About , safely representable.
Solution
. After the backward pass, dividing by in fp32 restores the true value.
Exercise 3: Summing in fp16 (code)
Add 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 , and adding rounds back to the same number.
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?
- The same precision as fp32
- The same range as fp32, but much lower precision
- A larger range than fp32
- No advantage over fp16
Loss scaling in fp16 training prevents…
- overflow of weights
- underflow of small gradients to zero
- the need for a learning rate
- bf16 rounding
Why keep an fp32 master copy of the weights in mixed-precision training?
- fp32 is faster
- Small updates to large weights would round away in 16-bit
- GPUs require it
- To double the memory