AI State of the Art
SOTA/Training: Modern Training Techniques/32 min
Section 85

Mixed Precision Training: FP16, BF16

Listen as a podcast →

The Simple Pitch

Training in FP32 (32 bits per floating-point number) is a thing of the past. Mixed precision uses 16-bit numbers (FP16 or BF16) for the majority of computations, and reserves FP32 only where it's critical.

The starting point is a counting exercise. A 32-bit number takes 4 bytes (32 bits divided by 8 bits per byte); a 16-bit number takes 2. Dropping from 32 to 16 bits therefore halves the space taken by activations and gradients, and halves the number of bytes that have to travel between memory and the compute units. That double saving (space and traffic) is the whole point.

This isn't an exotic optimization: it's the standard for all modern LLM (Large Language Model) training. Skipping it leaves the specialized compute units on the graphics card idle.

Mixed Precision Training

Floating-Point Number Formats

First: what the exponent and the mantissa actually are

You already know the mechanism under another name: scientific notation. Avogadro's number is written 6.022 × 10²³. Two parts are distinguishable in it:

  • 6.022, the digits, the information about the value itself. That is the mantissa.
  • 23, the power of ten, the information about the order of magnitude, in other words where the point sits. That is the exponent.

A floating-point number does exactly the same thing, but in base two: it is written mantissa × 2^exponent. The word "floating" comes from that: the point does not stay in a fixed place, it floats according to the exponent.

Take 0.15625. In base two that is 1.25 × 2⁻³. The mantissa is 1.25, the exponent is −3. So the machine does not store "0.15625" but those two numbers, side by side, each on a bit count fixed by the format.

The floating-point number therefore splits into three pieces:

  • the sign, on 1 bit: positive or negative;
  • the exponent: how far the point can travel. The more bits it has, the wider the gap between the smallest and largest representable number, what is called the dynamic range;
  • the mantissa: how many significant digits can be written. The more bits it has, the more finely two neighbouring numbers can be told apart, that is the precision.
Why 10 mantissa bits give 11 bits of precision

A detail that explains figures you meet everywhere. In base two, the leading significant digit of a normalised number is necessarily a 1, otherwise you would shift the point one notch further. Since that 1 is always the same, storing it is pointless: the standard leaves it implicit.

A 10-bit mantissa therefore carries 11 bits of useful information. That is where the relative step of 2−112^{-11} comes from, about 0.05%, which gives FP16 its three significant digits.

The total bit count fixes the space used; how those bits are split between exponent and mantissa fixes the trade between range and fineness. That is what everything below turns on.

FP32 (full precision), 4 bytes per number

The IEEE 754 standard: 1 sign bit, 8 exponent bits, 23 mantissa bits. Range: +-3.4x10^38. Precision: about 7 significant decimal digits. It's the "default" format in computing, but it's oversized for most deep learning computations.

FP16 (half precision), 2 bytes per number

1 sign bit, 5 exponent bits, 10 mantissa bits. Range: +-65504 only. Precision: about 3 decimal digits.

The problem: five exponent bits do not cover much ground. Take a gradient of 10^-5 multiplied by a learning rate of 10^-3: the product is 10^-8. The smallest non-zero number FP16 can write is about 6x10^-8. Our 10^-8 falls below that, so it rounds to zero, the update vanishes, and the layer stops learning. This is gradient underflow, loss of a value for being too small. This trap and its general remedy, the log-sum-exp trick, are covered in numerical stability.

BF16 (Brain Float 16, invented by Google), 2 bytes per number

1 sign bit, 8 exponent bits (as many as FP32), 7 mantissa bits. Range: +-3.4x10^38 (identical to FP32). Precision: about 2 decimal digits.

At equal size (16 bits, 2 bytes) BF16 takes FP32's 8 exponent bits and pays for them out of the mantissa (10 bits in FP16, 7 in BF16). Same footprint, opposite trade-off.

FP16 vs BF16: the crucial choice

FP16 offers more precision (10 mantissa bits vs 7 for BF16) but a reduced range that causes overflow and underflow. BF16 sacrifices fine precision to keep the full dynamic range of FP32. For LLMs, range is far more important than fine precision. That's why BF16 has become the dominant format for LLM training.

Why you cannot "just shift the decimal point"

It is the natural question, and it deserves a precise answer, because the intuition is half right.

First the numbers, to fix ideas.

FP16BF16
Bit layout1 sign, 5 exponent, 10 mantissa1 sign, 8 exponent, 7 mantissa
Smallest normal valueabout 6.1 × 10⁻⁵about 1.2 × 10⁻³⁸
Largest value65,504about 3.4 × 10³⁸
Significant digitsabout 3about 2

So FP16 tops out at 65,504 while BF16 reaches 3.4 followed by thirty-eight zeros: a gap of thirty-four orders of magnitude.

Shifting the decimal point is exactly what a float does. A number is written mantissa × 2^exponent, and the exponent is that shift. But the shift itself has to be stored, and its size is bounded by the bits reserved for it: five bits allow 32 possible shifts, eight bits allow 256. FP16 cannot shift further, not by design choice, but for lack of room to write a large shift.

Both formats hold exactly the same number of values

The point is counter-intuitive and it explains everything else. In sixteen bits there are 65,536 possible configurations, hence 65,536 representable values, for either format. What differs is not how many, but where they sit.

Picture a ruler carrying 65,536 marks. FP16 packs them into a narrow span: measurement is very fine, but nothing beyond that span can be measured at all. BF16 spreads the same marks across an immense distance: you can measure the millimetre and the kilometre, at the cost of coarser precision everywhere.

And why a global shift would not settle it. Because a network handles very different orders of magnitude at the same time: weights around 10⁻¹, gradients around 10⁻⁷, and squared gradients around 10⁻¹⁴. A single shift cannot suit all three, lifting the gradients into range would push the weights out the top.

The trick does exist, though, and it is precisely the loss scaling described further down: multiply the loss by a large factor to push gradients into FP16's range, then divide before the update. Effective but partial, and exactly the work BF16 makes unnecessary, which is why it eventually won.

How You Avoid Breaking Training

The fundamental principle: keep two copies of the weights instead of one, plus the gradients in the short format.

  1. Master copy in FP32 (4 bytes per weight): used for optimizer updates, where precision really matters
  2. Working copy in FP16/BF16 (2 bytes per weight): used for the forward and backward passes, where speed matters
  3. Gradients in FP16/BF16 (2 bytes per weight): computed during the backward pass. These are not weights, but they take up as much room as the working copy

The cycle at each iteration:

  1. Forward: cast the FP32 master copy to FP16/BF16, compute activations in FP16/BF16
  2. Backward: compute gradients in FP16/BF16
  3. Update: cast gradients to FP32, update the master copy (FP32 += gradient * lr)
  4. Cast: recreate the FP16/BF16 working copy from the updated master copy

Why is this FP32 master copy indispensable? Because the optimizer adds very small numbers (the gradient times the learning rate, often on the order of 10^-7) to large numbers (the weights, often on the order of 10^-1 to 10^1). A floating-point format only keeps a fixed number of significant digits: adding 10^-7 to 1 needs eight of them, and FP16 offers three. The sum therefore rounds back to 1 and the weight does not move. FP32 offers seven, which is enough to preserve the update. Without a master copy, training stalls.

Diagram of one mixed-precision training iteration: F32 Master-Weights pass through a float2half block producing F16 weights, used by the FWD, BWD-Actv and BWD-Weight blocks which exchange activations and gradients in F16; the F16 Weight Grad feeds back into a Weight Update block performed in F32 that updates the Master-Weights.
The figure from the original paper: everything in green (forward, backward, gradients) runs in 16 bits, and only the black arrow at the bottom - the weight update - stays in 32 bits. That is exactly the FP32 master copy described above, recast to FP16 at every iteration by the float2half block.Source : Mixed Precision Training paper (figure 1, Micikevicius et al.), via Lilian Weng

Loss Scaling: The Trick That Rescues FP16

In FP16, very small gradients (below about 6x10^-8, the smallest non-zero value the format can hold) round to zero. Deep layers naturally carry small gradients, because the backward pass multiplies together a long chain of factors that are usually below 1, see backpropagation. Those layers would simply stop learning.

Histogram of activation gradient magnitudes for an SSD network, as a percentage of the total against log2 of the magnitude. The bulk of the distribution sits between 2^-45 and 2^-15. An arrow labelled Become zero in FP16 covers the region left of 2^-24, an FP16 denorms arrow covers 2^-24 to 2^-14, and an FP16 representable range arrow covers everything from 2^-24 up to 2^15.
The problem made visible: on this network most gradients fall to the left of the red bar, in the region that becomes zero in FP16. The entire right-hand side of the FP16 range goes unused - hence the idea of shifting the distribution to the right.Source : NVIDIA Technical Blog, Mixed-Precision Training of Deep Neural Networks

The solution is elegant: multiply the loss by a large factor before the backward pass:

scaled_loss=1024×loss\text{scaled\_loss} = 1024 \times \text{loss}

Here the loss is the single number training tries to push down, and 1024 is a freely chosen factor. Read in one sentence: inflate the loss on purpose, and every gradient inflates by exactly the same factor, because differentiation is linear. Gradients become 1024 times larger and climb back into the range FP16 can write. You divide by the same factor just before the update, once back in FP32:

corrected_gradients=gradients1024\text{corrected\_gradients} = \frac{\text{gradients}}{1024}

Why 1024 rather than 1000? Because 1024 = 2^10 is a power of two. Multiplying or dividing a floating-point number by a power of two only shifts its exponent and leaves the mantissa untouched: the operation is exact and adds no rounding error of its own.

Dynamic loss scaling: in practice the factor is tuned automatically. If an overflow shows up (a gradient that has become Inf, infinite), the factor is halved and the iteration is thrown away. Otherwise the factor is raised gradually, to sit as high in the range as possible without ever spilling over.

BF16: no loss scaling needed!

Thanks to its dynamic range identical to FP32, BF16 doesn't suffer from gradient underflow. Loss scaling becomes unnecessary. This is a considerable practical advantage: less complexity, fewer potential bugs, fewer skipped iterations due to overflow.

The Concrete Gains

Speed, Thanks to Tensor Cores

Modern NVIDIA GPUs (Graphics Processing Units) carry specialized compute units called Tensor Cores, wired to do one thing only: multiply small matrices whose entries are 16-bit and whose result accumulates in 32-bit. See GPU architecture.

The table below gives the peak throughput published in NVIDIA's own datasheets, in TFLOP/s, teraFLOP per second, a thousand billion floating-point operations per second. The FP32 column is the ordinary units; the 16-bit column is the Tensor Cores, counting dense matrices (NVIDIA also publishes figures twice as high that only hold for sparse matrices).

GPUFP32 TFLOP/sFP16/BF16 TFLOP/s (Tensor Cores)Ratio of peak rates
V10015.71258x
A10019.531216x
H100 (SXM)6798915x
A peak ratio is not a measured speedup

Those 8x, 16x and 15x are ratios between two theoretical maximum rates. The speedup actually measured on a training run is markedly smaller, for three reasons: part of every iteration stays in 32-bit (optimizer update, normalization, loss accumulation); many operations are limited not by arithmetic but by how fast memory can be read; and the time spent shuffling data between machines does not shrink proportionally. The gain is worth having in every case, but we quote no numeric factor, for want of a published figure tied to a specific training run.

The Memory Footprint: What Goes Down and What Goes Up

Careful, the balance sheet is not uniformly downward. Count it out, for a model with NN parameters.

ItemWithout mixed precisionWith mixed precision
Activations and gradients4 bytes per value2 bytes per value
Weights4 bytes per parameter (a single FP32 copy)6 bytes per parameter (FP32 master copy at 4 bytes + 16-bit working copy at 2 bytes)

Activations and gradients are halved: that is where the gain lives, and it is a big one, because in LLM training the activations weigh far more than the weights.

The weights, on the other hand, grow by half: 6 bytes instead of 4. Mixed precision costs memory on the weights and saves a great deal everywhere else. For a 7-billion-parameter model that is 7 x 10^9 x 6 = 42 GB of weights instead of 28 GB. On top of that sit the optimizer states, which stay in FP32 and account for 8 bytes per parameter on their own with AdamW, i.e. 56 GB, that arithmetic is worked out in the lesson on optimizers.

Memory Bandwidth

Each FP16/BF16 number is half the size of its FP32 counterpart. For operations whose bottleneck is not arithmetic but the speed of reading and writing memory (attention being the textbook case, see FlashAttention) moving to 16 bits directly halves the number of bytes to shuttle around, and so the time spent shuttling them.

Operations That Must Stay in FP32

Some operations are numerically unstable in low precision and must imperatively stay in FP32:

  • Softmax (the function that turns arbitrary scores into probabilities): it chains a max subtraction, an exponential, and a division. The exponential violently amplifies any rounding error on its input.
  • LayerNorm / RMSNorm (the normalization layers, see normalization): computing a mean and a variance means adding thousands of terms, and each low-precision addition contributes its own rounding error.
  • Loss accumulation: summing many small terms in FP16 progressively loses precision, for the same reason.
  • Optimizer states: Adam's two running averages (mm and vv) update at each step from their own previous value. A rounding error introduced at step 1 propagates all the way to the end.

The library (PyTorch AMP, JAX) handles the choice for you: every operation sits either on a list allowed to run in 16-bit or on a list required to stay in FP32.

Signs of numerical instability

NaN or Inf in gradients. Loss that suddenly diverges after thousands of stable iterations. Convergence to a suboptimal result. Diagnosis: check that loss scaling is active (for FP16), that critical operations are indeed in FP32, and that gradients don't contain extreme values.

In Practice: AMP

PyTorch, JAX and TensorFlow offer AMP (Automatic Mixed Precision) which handles everything for you. A few lines of code are enough:

with torch.autocast(device_type="cuda"):
    output = model(input)  # FP16/BF16 automatically
    loss = criterion(output, target)

scaler.scale(loss).backward()
scaler.step(optimizer)

The autocast picks the precision for each operation from the two internal lists. The scaler handles dynamic loss scaling (unnecessary with BF16). It is invisible to the rest of the code.

Universal Adoption

Mixed precision training has not been optional for several years: every recent large model whose training has been documented uses it. A pure FP32 run would leave the Tensor Cores idle and double the space taken by activations, the dominant item in the memory footprint. We put no number on that penalty: no published measurement supports an honest factor, and the factors in circulation are peak-throughput ratios dressed up as wall-clock times.

The evolution continues

Pure FP32 is a fossil. FP16/BF16 mixed precision is the bare minimum of hygiene. FP8, at 1 byte per number, is the current frontier on NVIDIA's Hopper and Blackwell GPUs, the subject of the next lesson. The trend runs toward fewer bits per number, offset by ever more elaborate techniques for keeping training stable.

Check your understanding0 / 5

1. Why keep a master copy of the weights in FP32 when the forward and backward passes run in 16-bit?

2. FP16 and BF16 both use 16 bits. What actually sets them apart?

3. With mixed precision, what happens to the space taken by the model's weights?

4. An A100 spec sheet lists 312 TFLOP/s in 16-bit versus 19.5 in FP32, a 16x ratio. Does that mean training will run 16 times faster?

5. In loss scaling, why pick a factor like 1024 rather than 1000?