How does Mixed Precision Training work?

Authors
How does Mixed Precision Training work?

Mixed Precision Training is a way of training an AI model where most of the math is done with small 16-bit numbers for speed and less memory, while a few important things are kept in full 32-bit numbers for accuracy. This way, we usually get faster training without losing quality.

In this blog, we will learn about how Mixed Precision Training works. We will also see how a computer stores decimal numbers, what FP32, FP16, and BF16 mean, why using only 16-bit numbers breaks training, how three tricks fix those problems, how to write it in PyTorch, and when to use FP16 and when to use BF16.

We will cover the following:

  • How does a computer store decimal numbers?
  • What is precision?
  • FP32, FP16, and BF16
  • Why do we want to use smaller numbers?
  • The problems with training only in FP16
  • What is Mixed Precision Training?
  • Trick 1: Keep a master copy of the weights in FP32
  • Trick 2: Loss scaling
  • Trick 3: Do the sensitive math in FP32
  • The full Mixed Precision Training step
  • Mixed Precision Training in PyTorch
  • FP16 vs BF16 for Mixed Precision Training

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

How does a computer store decimal numbers?

Before jumping into Mixed Precision Training, we must know how a computer stores a decimal number like 3.14159.

A computer stores everything as bits. The more bits we use for a number, the more detail we can store about that number.

A decimal number is stored in a format called floating point. The computer stores a number in a scientific-notation style, like below:

   3.14159  =  3.14159 x 10^0
   0.00042  =  4.2     x 10^-4
   65000    =  6.5     x 10^4

So, every number is split into two main parts:

  • The digits (like 3.14159 or 4.2). The computer calls this part the mantissa. More bits here means more digits after the decimal point.
  • The power (like 10^-4 or 10^4). The computer calls this part the exponent. More bits here means we can store very big and very tiny numbers.

There is also one sign bit that tells whether the number is positive or negative.

Note: Just for the sake of understanding, we are using powers of 10 here. The computer actually uses powers of 2, but the idea is exactly the same.

Let's say we have a fixed number of boxes to write a number. If we give more boxes to the digits, the number becomes more exact. If we give more boxes to the power, the number can become bigger or tinier. We cannot have both unless we add more boxes.

What is precision?

Precision means how exact a number is.

Let's say we write the value of pi:

  • High precision: 3.1415927
  • Low precision: 3.14

Both are pi, but the first one is more exact. Low precision saves space but loses some detail.

We have a detailed blog on Model Quantization that explains how we store a model with fewer bits.

Now, let's see the number formats that AI training uses.

FP32, FP16, and BF16

FP means floating point, and the number after it is the total number of bits.

FP32 uses 32 bits, which is 4 bytes. It is called full precision or single precision. For a long time, AI models were trained fully in FP32.

FP16 uses 16 bits, which is 2 bytes. It is called half precision.

BF16 also uses 16 bits. BF16 stands for Brain Floating Point 16. It was created by the Google Brain team. It splits its 16 bits in a different way from FP16.

Let's see how each one splits its bits as below:

            sign   exponent (range)   mantissa (detail)
   FP32:     1          8                  23
   FP16:     1          5                  10
   BF16:     1          8                   7

Here, we can notice:

  • FP16 keeps a decent amount of detail (10 bits) but has a small range (only 5 bits of exponent). The biggest number FP16 can store is 65,504. And it cannot store very tiny numbers either.
  • BF16 keeps the same range as FP32 (8 bits of exponent), so it can store very big and very tiny numbers. But it keeps less detail (only 7 bits).

Let's see this in Python with a small example as below:

import numpy as np

print(np.float32(3.14159265))   # 3.1415927
print(np.float16(3.14159265))   # 3.14
print(np.float16(70000))        # inf
print(np.float16(0.00000001))   # 0.0

Here, we can see that:

  • FP32 keeps pi as 3.1415927.
  • FP16 keeps only about 3.14 (the exact stored value is 3.140625).
  • 70,000 is bigger than 65,504, so FP16 turns it into inf, which means infinity. This is called overflow.
  • 0.00000001 is too tiny for FP16, so it becomes 0.0. This is called underflow.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

Why do we want to use smaller numbers?

If FP32 is more exact, why not always use it? The answer is speed and memory.

Training a big model means doing billions of multiplications on a GPU.

16-bit numbers give us the following advantages:

  • Half the memory: each number takes 2 bytes instead of 4. So, we can fit a bigger model or a bigger batch on the same GPU. A batch is the group of examples that the model learns from in one step.
  • Faster data movement: the GPU spends a lot of time just moving numbers from its memory to its math units. Smaller numbers move faster.
  • Faster math: modern NVIDIA GPUs have special units called Tensor Cores that do 16-bit matrix math much faster than 32-bit math.

So, 16-bit numbers make training faster and cheaper. Now, the question is: why not just train everything in FP16?

The problems with training only in FP16

Let's first understand what happens in one training step.

The model is made of weights. A weight is just a number that the model adjusts while learning. One training step looks like below:

Input
  ↓
Model (weights)
  ↓
Prediction
  ↓
Loss
  ↓
Gradients
  ↓
Update weights
  • Loss: a number that tells how wrong the prediction is.
  • Gradient: for each weight, a number that tells in which direction and by how much the weight should change to reduce the loss.
  • Update: new weight = old weight - learning rate x gradient. The learning rate is a small number that controls how big each step is.

Now, if we do all of this in FP16, the following issues arise.

Problem 1: Small updates disappear.

Let's say a weight is 1.0, and the update is 0.0001. In FP16, the gap between 1.0 and the next number that FP16 can store is about 0.001. So, 0.0001 is too small to change 1.0 at all.

import numpy as np

print(np.float32(1.0) + np.float32(0.0001))   # 1.0001
print(np.float16(1.0) + np.float16(0.0001))   # 1.0

Here, we can see that in FP32, the weight becomes 1.0001. In FP16, it stays 1.0. The update is lost. If this happens again and again, the model stops learning.

Let's say we have a big jar with 1 kg of rice, and our weighing machine shows only whole grams. One grain of rice weighs much less than a gram. If we add one grain and write down the new reading, the machine still shows 1000 g. If we keep doing this, grain by grain, the reading never changes, even though the jar is getting heavier. This is exactly what happens to small updates in FP16.

Problem 2: Tiny gradients become zero.

Many gradients in a deep model are very tiny numbers. As we saw, FP16 cannot store numbers that are too tiny. They underflow and become 0. A gradient of 0 means "do not change this weight". So, the model loses useful learning signals.

Problem 3: Big values become infinity.

Some calculations, like adding up many big numbers, can go above 65,504. Then, FP16 overflows to infinity, and the training breaks with errors.

So, pure FP16 is fast but broken. Pure FP32 is correct but slow. Here comes Mixed Precision Training into the picture.

What is Mixed Precision Training?

Mixed Precision Training means training a model with a mix of 16-bit and 32-bit numbers. We use 16-bit where it is safe and fast, and 32-bit where we need accuracy.

The idea was made popular by the 2017 paper "Mixed Precision Training" by researchers from NVIDIA and Baidu. They showed that with three tricks, we can train in 16-bit and still reach the same accuracy as full 32-bit training.

Let's learn about each trick one by one.

Trick 1: Keep a master copy of the weights in FP32

This trick solves Problem 1, the disappearing updates.

We keep two copies of the weights:

  • A master copy in FP32. This is the real, exact version of the weights.
  • A working copy in FP16. This is used for the fast math in the forward pass and the backward pass. The forward pass means the input goes through the model to produce a prediction. The backward pass means we go back through the model to calculate the gradients.

The update always happens on the FP32 master copy. So, a tiny update like 0.0001 is not lost. After the update, we make a fresh FP16 working copy from the master copy for the next step.

Let's go back to our rice jar. We keep a very exact weighing machine (FP32) for the real record, and use the rough machine (FP16) only for quick daily work. The tiny grains get counted on the exact machine.

Note: Keeping an extra FP32 copy uses some extra memory for the weights. But the big memory users during training are the activations, the in-between results that the model saves during the forward pass. These are stored in 16-bit, so the total memory still goes down in most cases.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

Trick 2: Loss scaling

This trick solves Problem 2, the tiny gradients that become zero.

Before the backward pass, we multiply the loss by a big number, like 1024. This big number is called the scale factor.

Because of the way gradients are calculated, when the loss is multiplied by 1024, every gradient also gets multiplied by 1024. So, the tiny gradients become bigger and move into the range that FP16 can store.

Then, before updating the weights, we divide the gradients by 1024 again, in FP32. This brings them back to their true size.

Let's see with an example as below:

Without loss scaling:

True gradient: 0.00000001
  ↓
In FP16, it becomes 0 (lost)

With loss scaling:

Multiply the loss by 1024
  ↓
Scaled gradient: 0.00001024
  ↓
In FP16, it stays about 0.00001025 (safe)
  ↓
Divide by 1024 in FP32
  ↓
About 0.00000001 (correct size again)

Here, we can see that scaling saves the gradient from becoming zero.

Let's say we are taking a photo of a very small insect. The camera cannot see it clearly. So, we zoom in first, take the photo, and then write down the real size by dividing by the zoom level. Loss scaling is the zoom.

If the scale factor is too big, some gradients become too big and overflow to infinity. So, how do we pick the right scale factor? The answer is dynamic loss scaling.

In dynamic loss scaling:

  • We start with a big scale factor.
  • After every step, we check whether any gradient became infinity or "not a number" (called NaN).
  • If yes, we skip this update and cut the scale factor in half.
  • If many steps pass with no problem, we double the scale factor again.

This way, the scale factor adjusts itself automatically. PyTorch does all of this for us, as we will see in the code.

If we want to go deep into Backpropagation, Loss Functions, and Gradient Descent, check out our AI and Machine Learning Program at Outcome School.

Trick 3: Do the sensitive math in FP32

This trick solves Problem 3, the big values that overflow.

Not every calculation is safe in 16-bit. Some calculations add up a lot of numbers, and the total can become too big for FP16. Some need more detail to stay correct.

So, we do these sensitive calculations in FP32:

  • Adding up results in big matrix multiplications: the multiplications happen in 16-bit, but the running total is kept in FP32. Tensor Cores support this directly.
  • Sums and averages over many numbers, like the ones in softmax and normalization layers.
  • The loss calculation.

Everything else, like the big matrix multiplications, runs in 16-bit.

Now, we have understood all three tricks. Let's put them together.

The full Mixed Precision Training step

Let's see one full training step as below:

Master weights (FP32)
  ↓
Make an FP16 copy
  ↓
Forward pass in FP16 (sensitive parts in FP32)
  ↓
Loss (FP32) x scale factor
  ↓
Backward pass in FP16, which gives scaled gradients
  ↓
Convert gradients to FP32, divide by scale factor
  ↓
Any infinity or NaN?
  ↓
Yes: skip the update, reduce the scale factor
No: update the master weights (FP32)

This is how Mixed Precision Training works.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

Mixed Precision Training in PyTorch

The best part is that we do not need to write all of this by hand. PyTorch gives us AMP, which means Automatic Mixed Precision.

Let's see the code for training with AMP as below:

import torch

model = MyModel().cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
scaler = torch.amp.GradScaler("cuda")

for inputs, targets in data_loader:
    optimizer.zero_grad()

    with torch.autocast(device_type="cuda", dtype=torch.float16):
        outputs = model(inputs)
        loss = loss_fn(outputs, targets)

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

Here, we have:

  • Created the model normally. Its weights stay in FP32. These are our master weights.
  • Created a GradScaler. This is the part that does dynamic loss scaling for us.
  • Used torch.autocast. Inside this block, PyTorch automatically runs safe operations like matrix multiplications in FP16, and keeps sensitive operations like softmax and the loss in FP32. This is Trick 3, done for us.
  • Called scaler.scale(loss).backward(). This multiplies the loss by the scale factor and then runs the backward pass. This is Trick 2.
  • Called scaler.step(optimizer). This divides the gradients back to their true size, checks for infinity or NaN, and updates the weights only if everything is fine. The update happens on the FP32 master weights, which is Trick 1.
  • Called scaler.update(). This increases or decreases the scale factor for the next step.

With only a few extra lines, our training usually becomes faster and uses less memory.

If we use BF16, the code becomes even simpler, like below:

with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
    outputs = model(inputs)
    loss = loss_fn(outputs, targets)

loss.backward()
optimizer.step()

Here, we can notice that there is no GradScaler. Let's understand why.

FP16 vs BF16 for Mixed Precision Training

Remember, BF16 has the same range as FP32 because it has 8 bits of exponent. So, tiny gradients do not underflow, and big values do not overflow so easily. Hence, we usually do not need loss scaling with BF16.

But, BF16 has less detail. That is why we still keep the master weights in FP32, so that small updates are not lost.

Let me tabulate the differences between FP16 and BF16 for your better understanding so that you can decide which one to use based on your use case.

PointFP16BF16
Total bits1616
Exponent bits (range)58, same as FP32
Mantissa bits (detail)107
Biggest number65,504About the same as FP32
Underflow and overflow riskHighLow
Needs loss scalingYesUsually no
Needs FP32 master weightsYesYes
GPU supportMost modern NVIDIA GPUsNewer GPUs like NVIDIA A100, H100, and Google TPUs

Here, we can see that BF16 trades detail for range, and for training, range is usually more important.

So, if our hardware supports BF16, we use BF16, because it is simpler and more stable. If our GPU is older and does not support BF16, we use FP16 with loss scaling.

Now we must have understood how Mixed Precision Training works.

Frequently Asked Questions

Does Mixed Precision Training reduce model accuracy?

Usually, no. The 2017 "Mixed Precision Training" paper by researchers from NVIDIA and Baidu showed that with three tricks, we can train in 16-bit and still reach the same accuracy as full 32-bit training. The tricks are an FP32 master copy of the weights, loss scaling, and doing the sensitive math in FP32.

Does Mixed Precision Training always save memory?

In most cases, yes. Keeping an extra FP32 master copy uses some extra memory for the weights. But the big memory users during training are the activations, the in-between results saved during the forward pass. These are stored in 16-bit, so the total memory still goes down in most cases.

What happens when a gradient becomes infinity or NaN during Mixed Precision Training?

The update for that step is skipped, and the scale factor is cut in half. This is part of dynamic loss scaling. In PyTorch, the GradScaler does this for us automatically, so the scale factor adjusts itself from step to step.

Do we still need FP32 master weights when training in BF16?

Yes. BF16 has the same range as FP32, so we usually do not need loss scaling with it. But BF16 keeps less detail, with only 7 bits of mantissa. That is why we still keep the master weights in FP32, so that small updates are not lost.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.