Key takeaways
- A floating-point number has three parts: a sign, an exponent and a mantissa. The exponent sets the range; the mantissa sets the precision.
- FP16 is a bit more precise but tops out at 65,504, so it overflows and underflows easily. BF16 takes the same 2 bytes but has the same range as FP32, which makes it the go-to format for training.
- Mixed precision training keeps the master weights in FP32 and does most of the math in BF16; gradients are computed in BF16 and accumulated into FP32. With FP16 you also need loss scaling.
- For inference, load the model with
torch_dtype=torch.bfloat16. torch.autocast picks a precision per operation and leaves the weights in FP32.
- Quantization uses scale factors to squeeze weights into a few slots (INT8, NF4). bitsandbytes only actually quantizes when the model moves to the GPU with
.to('cuda').
How much memory does a model need?
A large language model with 7 billion parameters is, at the end of the day, just 7 billion numbers, and how many bits you spend on each number decides how big the model is. The usual choice is 32 bits, or 4 bytes per number:
7×109 numbers×4 bytes≈28 GB
Even a high-end gaming graphics card has only 24 GB of memory, so it can't hold the weights. With 16 bits per number you'd need just 14 GB; with 8 bits, 7 GB; with 4 bits, only about 3.5 GB, small enough for a laptop.
The common precision options (bytes per number in parentheses):
- FP32: full precision (4 bytes). Most accurate, most memory.
- FP16: half precision (2 bytes). Half the memory.
- BF16: same size as FP16 (2 bytes), but a larger dynamic range, so it's numerically more stable.
- INT8: a quarter of FP32 (1 byte). Requires quantization.
- INT4: smaller still.
Intuition: Precision is like photo resolution. FP32 is the full-resolution original: big, and the most faithful. BF16 and FP16 are compressed copies at half the size. INT8 and INT4 are even harder compression: smaller still, but they need special quantization tricks. A lot of the work in training and inference doesn't need full resolution.
That raises two puzzles:
- Cut the bits in each number by half, or even by seven eighths, and the model still works. Why?
- Train in 16-bit FP16, and the loss is coming down nicely, then suddenly turns into NaN ("Not a Number"). Why?
To answer them, we start with how a computer stores a number like 3.14.
Binary: nothing but 0s and 1s
Everything inside a computer is ultimately stored as a string of zeros and ones, and each one is called a bit.
In decimal, 307 is 3 hundreds, 0 tens and 7 ones: each step to the left multiplies the place value by 10. Binary works the same way, except each step multiplies by 2. From right to left the place values are 1, 2, 4, 8:
11012=8+4+0+1=13
Fractions work the same way. To the right of the point, decimal places are worth a tenth, a hundredth, and so on; in binary they're worth a half, a quarter, an eighth:
0.1012=21+81=0.625,110.12=4+2+21=6.5
Remember 6.5. We'll need it again soon.
Scientific notation: letting the point float
We usually write very big or very small numbers in scientific notation:
620000000=6.2×108,0.00015=1.5×10−4
It splits a number in two: the digits in front tell you how precise it is, and the power of 10 tells you how big it is.
Binary can be written this way too. Slide the point in 110.12 two places to the left and it becomes 1.1012×22. The point can float back and forth as the exponent changes, which is why this is called floating point.
Let's agree to always put the point right after the first 1, so the leading digit is always 1. And if it's always 1, why store it at all? Leave it out and you save a bit for free. This unstored 1 is the hidden bit. So a floating-point number needs just three things:
- a sign: positive or negative;
- an exponent: which power of 2;
- a mantissa: the string of digits after the point.
Decoding an FP16 number, step by step
A real format: the 16-bit half-precision float, FP16. It splits its 16 bits into 1 sign bit, 5 exponent bits and 10 mantissa bits. Here's a string of bits:
1 | 10001 | 1010000000
The three groups are the sign (1 bit), the exponent (5 bits) and the mantissa (10 bits).
- Sign bit: 0 means positive, 1 means negative. Here it's 1, so the number is negative.
- Exponent: read the 5 bits as binary, with place values 16, 8, 4, 2, 1: 100012=16+1=17. But the exponent also has to handle negative powers like 2−3. FP16's trick is to add 15 when storing and subtract 15 when reading. That 15 is called the bias. So the real exponent is 17−15=2.
- Mantissa: put the hidden 1 and the point back in front: 1.10100000002=1+21+81=1.625.
Put the pieces together:
−1.625×22=−1.625×4=−6.5
That's our 6.5 from before, just with a minus sign.
The general formula, the maximum, and special values
The general formula
Those three steps, written as one formula:
x=(−1)s×1.m×2E−bias
s is the sign bit, E is the exponent as stored, m is the string of mantissa bits (with the hidden 1 put back in front), and the bias is the offset, 15 for FP16.
FP16's ceiling: 65,504
The all-ones exponent pattern is reserved for something else, so the largest exponent we can store is 111102=30; subtract 15 and we get 15. Make the mantissa all ones too, a 1, a point and ten more ones, which is a hair less than 2: 1.11111111112=2−2−10. Multiply and expand:
(2−2−10)×215=216−25=65536−32=65504
That's the largest number FP16 can hold.
The bottom end and special values
- Smallest normal number: exponent field 1, mantissa all zeros: 1.0×21−15=2−14≈0.000061.
- Subnormal numbers: for even smaller values, FP16 uses the all-zeros exponent pattern and drops the hidden 1, so the mantissa can creep down toward zero. The smallest is 0.00000000012×2−14=2−24≈6×10−8. Anything smaller simply becomes 0.
- Infinity and NaN: the all-ones exponent pattern is saved for these. Once a result goes past 65,504, it turns into infinity.
Range vs precision: how to split the bits
What do the numbers a float can represent look like on a number line? Try a toy format with just 5 bits (ignoring the sign).
Format A: 3 exponent bits, 2 mantissa bits. Between 1 and 2, a 2-bit mantissa can make only 4 numbers: 1, 1.25, 1.5, 1.75. Between 2 and 4 there are still 4, but the gap doubles to 0.5; between 4 and 8 the gap is 1. The further right you go, the sparser the grid, while between 0 and 1 the numbers are packed tight. Look closely: in every segment, the gap is exactly a quarter of the number where that segment starts. Floating-point error is relative: it scales with the size of the number.
Format B: 2 exponent bits, 3 mantissa bits. The grid is twice as fine, with 8 numbers between 1 and 2. But the biggest number it can reach is 7.5, while format A keeps going all the way to 28.
That's the core trade-off of floating point:
Intuition: With a fixed number of bits, more exponent bits → more range, and more mantissa bits → a finer grid, more precision.
A handy measure of precision: how far is 1 from the very next number to its right? With m mantissa bits, that gap is 2−m (2−2=0.25 for format A, 2−3=0.125 for format B).
Side by side: FP32, TF32, FP16, BF16, FP8
- FP32 (single precision): 8 exponent bits, 23 mantissa bits, 32 bits or 4 bytes in all. The traditional default.
- FP16 (half precision): 5 exponent bits, 10 mantissa bits. Half the space, but with only 5 exponent bits it tops out at 65,504.
- BF16 ("brain float", from the Google Brain team): keeps FP32's 8 exponent bits and cuts the mantissa to 7 bits. So it's the same size as FP16 but has the same range as FP32. The price is coarser precision.
- TF32: starting with the A100, the format NVIDIA's tensor cores use internally for FP32 matrix multiplication: 8 exponent bits with 10 mantissa bits, so only 19 bits are actually used.
- FP8: 8 bits, supported starting with the H100, in two flavors. E4M3 (4 exponent + 3 mantissa bits) is a bit more precise, so it's typically used for the forward pass; E5M2 (5 exponent + 2 mantissa bits) has more range, so it's typically used for gradients. In practice both are paired with scaling factors.
Watch out: BF16 and FP16 take exactly the same memory. The difference is how they split those 16 bits. BF16 gives up some precision to get a much larger range, which is why it's usually the safer, recommended choice in deep learning.
The key numbers, side by side
| Format |
Exp/Mant |
Max |
Gap near 1 |
| FP32 |
8/23 |
3.4×1038 |
1.2×10−7 |
| TF32 |
8/10 |
3.4×1038 |
9.8×10−4 |
| FP16 |
5/10 |
65504 |
9.8×10−4 |
| BF16 |
8/7 |
3.4×1038 |
7.8×10−3 |
| E4M3 |
4/3 |
448 |
0.125 |
| E5M2 |
5/2 |
57344 |
0.25 |
- The max value tells you the range. FP32, TF32 and BF16 all reach around 1038; FP16 only about 65 thousand; FP8 even less.
- The gap near 1 tells you the precision. FP32 can tell apart differences of about one part in ten million; FP16 and TF32, about one part in a thousand; BF16, only about 8 parts in a thousand. In decimal terms, FP32 gives about 7 significant digits, FP16 about 3, BF16 only two or three, and FP8 about 1.
So FP16 and BF16 are the same size but make opposite trade-offs: FP16 leans toward precision, BF16 toward range. Which is better for training? First, let's see what goes wrong when you run out of range.
Overflow and underflow
Lay the axis out by orders of magnitude. The positive numbers FP32 can represent run from about 10−45 up to 1038, and BF16 is almost as wide. FP16 covers just a narrow strip, from about 6×10−8 to 65,504, and FP8 is narrower still.
- Overflow means going over the top. For example, 300×300=90000, which is more than 65,504, so all FP16 can give you is infinity (inf). Once infinity gets into more math, say ∞−∞, you get NaN. Anything combined with NaN is still NaN, so it quickly spreads through the whole network and the loss turns into NaN too. That's our second puzzle solved.
- Underflow means dropping below the bottom. During training, lots of gradients are tiny, say 10−8. In FP16 that becomes exactly 0, and that bit of learning signal is gone.
BF16, with FP32's range, handles both examples with ease. The results are just a little rough: 90,000 comes out as 90,112, and 10−8 survives.
Why training loves BF16
BF16 has one more perk: converting between it and FP32 is dead simple. Take π, which is about 3.14159274 in FP32. Chop off the last 16 of its 32 bits and the first 16 that remain are a perfectly valid BF16 number: the sign and the 8 exponent bits are untouched, and only the mantissa got shorter. It reads as 3.140625, off from π by about 3 parts in 10,000. (A real conversion rounds to the nearest value instead of just chopping, but here the result happens to be the same.)
Three reasons training loves BF16:
- Same range as FP32: it almost never overflows or underflows, so training needs no extra tricks.
- Networks tolerate rounding noise: its precision is coarse, but one matrix multiplication adds up thousands of products whose small errors partly cancel out, and the hardware usually does that adding in FP32.
- Native hardware support: Google's TPUs and NVIDIA's GPUs from the A100 onward support BF16 natively.
That's why BF16 is pretty much the default for training large models today.
Mixed precision training
The problem with pure BF16
Training in pure BF16 has one problem. Say some weight equals 1, and this step wants to add 0.0001 to it:
- BF16 can represent 0.0001 itself just fine, since its grid is very fine near zero;
- but near 1, BF16's gap is 2−7≈0.0078, about 8 thousandths.
1.0001 is only a hair away from 1 but still far from the next grid point (1.0078), so it gets rounded right back down to 1. That update was wasted. Even after 100 updates like this in a row, the BF16 weight is still exactly 1.0000; in FP32 it dutifully climbs to 1.0100.
The fix: save where you can, be exact where you must
Mixed precision training runs the heavy math (matrix multiplications and so on) in cheap BF16 and keeps the state that really needs precision in FP32. It works as a loop:
- The master weights are always kept in FP32.
- Each step, make a BF16 copy of them. That copy runs the forward pass, and the activations it produces are in BF16 too.
- Once we have the loss, run the backward pass. The gradients are computed in BF16 as well, then converted to FP32 and accumulated there.
- The optimizer uses those FP32 gradients to update the FP32 master weights. Then the next step begins.
Most of the computation happens in fast, lean BF16, while all those tiny updates get faithfully recorded in FP32.
Intuition: Matrix multiplications are tolerant of rounding noise, so BF16 is fine for the forward and backward passes. The master weights have to stay in FP32 because individual gradients are tiny compared with the weights, and low precision can't hold such small nudges. All we need is for the accumulated gradients to land in FP32.
Watch out: Each parameter's .grad has the same dtype as the parameter itself, so individual gradients are cast to FP32 before they're accumulated. Also, what mixed precision mainly saves is compute time and activation memory. The master weights are still in FP32, with a BF16 copy on top, so the weights themselves actually take up a little more.
Loss scaling: the rescue for FP16
If your hardware doesn't support BF16 and you have to do mixed precision in FP16, you have to deal with underflow. Lay out gradient sizes in powers of 2: the smallest positive number FP16 can represent is about 2−24, and any gradient smaller than that becomes 0.
The fix is clever. Loss scaling: before the backward pass, multiply the loss by a big number S, say 216=65536. By the chain rule, scaling the loss by S scales every gradient by exactly S:
∂w∂(S⋅L)=S⋅∂w∂L
On the plot, the whole gradient distribution slides 16 steps to the right, and the gradients that would have turned into 0 now land inside FP16's range. Once the gradients are computed and converted to FP32, divide them by S to undo the scaling, g=gscaled/S. The gradients that actually update the weights are back at their original size.
How big should S be? PyTorch's GradScaler tunes it automatically:
- if any gradient turns into infinity or NaN, it skips that step and cuts S in half;
- if 2000 steps in a row go fine, it doubles S.
scaler = torch.amp.GradScaler("cuda")
with torch.autocast("cuda", dtype=torch.float16):
loss = model(x)
scaler.scale(loss).backward() # loss times S
scaler.step(optimizer) # divide by S, then update
scaler.update() # adjust S
Watch out: BF16 has the same range as FP32, so its gradients almost never underflow. With BF16 you usually don't need loss scaling at all.
Loading a model in low precision
The most common case is inference: loading a model that's already been trained. With Hugging Face's .from_pretrained(), add one argument:
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16, # weights and activations in BF16
)
Now the weights load in BF16 and the activations are computed in BF16 too. This is the recommended approach: a 7-billion-parameter model drops from 28 GB to 14 GB.
If the model is already in memory, convert it directly: model.half() gives FP16, and model.to(torch.bfloat16) gives BF16.
model = MyModel()
model.load_state_dict(torch.load('model.pt'))
model = model.half() # convert to FP16
model = model.to(torch.bfloat16) # or convert to BF16
Now both the weights and the math are in low precision. In practice, running inference entirely in BF16 is usually no problem at all.
The same memory-saving spirit works for training data. With memory mapping (memmap), the data file stays on disk and only the part you actually use gets read in, instead of loading the whole dataset into memory at once.
data = np.memmap('train.bin', dtype=np.uint16, mode='r')
x = data[i : i + block_size] # reads only the slice you use
torch.autocast: picking a precision per operation
Another option is automatic mixed precision with torch.autocast():
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
output = model(x)
Inside the with block, the weights stay in FP32, but every time an operation runs, PyTorch picks a precision for it. The dtype argument names the low-precision type it may switch to.
| Operation |
Precision |
| matmul, linear |
low (e.g. BF16) |
| softmax |
FP32 |
| LayerNorm |
FP32 |
| sum, log, exp |
FP32 |
- Matrix multiplies and linear layers are forgiving of rounding noise, so they switch to low precision: fast and lean.
- Softmax, LayerNorm, sums and logarithms either pool together lots of numbers (reductions) or are sensitive to small errors, so they stay in FP32.
Watch out: autocast only decides what precision each operation runs in. It doesn't manage the master weights. Compared with converting the whole model to BF16, it uses more memory but is often more stable numerically. So it's a good choice when your model is in FP32 and hard to convert, or when pure BF16 runs into numerical trouble. If you use FP16, pair it with the GradScaler from before.
Quantization: fitting numbers into integer slots
To save even more, we switch to integers. INT8 has 8 bits and covers the whole numbers from −128 to 127, 256 in all. Squeezing weights into these slots is called quantization.
Example: four weights, 0.423, −1.27, 0.051, 0.888.
- Find the largest absolute value: 1.27. We want it to land on 127, so the scale factor is max∣w∣127=1.27127=100.
- Multiply each weight by 100 and round: 42, −127, 5, 89. Each integer takes 1 byte.
- When we need them, divide back: 0.42, −1.27, 0.05, 0.89. The errors are just a few thousandths.
As formulas, quantizing and restoring are:
q=round(max∣w∣127⋅w),w^=q⋅127max∣w∣
This is called absmax quantization.
Outliers, and LLM.int8()
This method has a weak spot: outliers. Suppose a 25.4 sneaks into the group. Now the largest absolute value is 25.4, and the scale factor drops to 127/25.4=5. All the small weights get crushed toward zero: 0.051 turns into 0, and 0.423 becomes 0.4. A single outlier ruins the precision of the whole group.
So in practice, each small group of weights gets its own scale factor, say one per row, or one per block of 64. Then an outlier only drags down its own group.
The LLM.int8() method in bitsandbytes goes a step further: it picks out the few unusually large outlier features and computes them separately in FP16. Only the rest is done in INT8.
Watch out: When you load a model with load_in_8bit=True (which uses LLM.int8()), only the weights are stored as INT8; the activations stay in FP16. It saves the memory for storing weights. It does not turn every calculation into integer math.
This also hints that activations are harder to quantize than weights. Weights are fixed and their distribution is fairly tidy; activations change with every input and often carry huge outliers.
4-bit quantization and NF4
What if we only have 4 bits? That's just 16 different values. The simplest approach is to spread 16 grid points evenly between −1 and 1. But neural network weights mostly follow a bell-shaped normal distribution: the vast majority crowd around zero and thin out toward the edges. An even grid is wasteful at the two ends, where hardly any weights land, and short of points in the crowded middle.
NF4 (4-bit NormalFloat) takes a different approach: it places the 16 values at the quantiles of a normal distribution, so each slot gets roughly the same share of the weights. The grid ends up dense in the middle and sparse at the ends.
Example: a block of 8 weights,
0.31, −0.82, 0.05, 1.64, −0.27, 0.66, −1.12, 0.12
- Divide them all by the block's largest absolute value, 1.64, which squeezes them into −1 to 1.
- Snap each number to the nearest NF4 grid point and store only that point's index, 0 to 15: exactly 4 bits.
- When we need the weights, look up each grid value and multiply by 1.64 again to get close approximations of the originals.
Real NF4 uses blocks of 64 weights, each with its own scale factor. Stored in FP32, those scales add 32/64=0.5 bits per parameter. Quantize the scales themselves, a trick called double quantization, and the overhead drops to about 0.13 bits per parameter.
Watch out: At compute time, the 4-bit weights are temporarily restored to BF16 before the matrix multiply runs. So 4 bits saves memory, but the math itself still happens in BF16.
Hands-on: loading and quantizing a model
Swapping out the linear layers
With bitsandbytes, the idea is to swap every nn.Linear in the model for the quantized version the library provides: bnb.nn.Linear8bitLt for 8 bits, bnb.nn.Linear4bit for 4 bits. This function builds the 8-bit version:
def replace_linear_with_8bit(model):
"""Replace all nn.Linear with bnb.nn.Linear8bitLt"""
for name, child in model.named_children():
if isinstance(child, nn.Linear):
# Create quantized replacement
new_layer = bnb.nn.Linear8bitLt(
child.in_features,
child.out_features,
bias=child.bias is not None,
has_fp16_weights=False,
)
# Copy weights (they'll be quantized when moved to CUDA)
new_layer.weight = bnb.nn.Int8Params(
child.weight.data,
requires_grad=False,
)
if child.bias is not None:
new_layer.bias = nn.Parameter(child.bias.data)
setattr(model, name, new_layer)
else:
# Recurse into child modules
replace_linear_with_8bit(child)
return model
It walks recursively through every child module. Whenever it finds a linear layer, it creates an 8-bit layer of the same size, copies in the original weights and bias, and swaps the new layer in for the old one. Anything that isn't a linear layer, it recurses into.
Four steps
model = MyTransformer()
model.load_state_dict(torch.load('model.pt'))
model = replace_linear_with_8bit(model)
model = model.to('cuda') # quantization happens here
MyTransformer(): build the model's skeleton. The weights are still random.
load_state_dict(...): load the trained weights from disk into the skeleton.
replace_linear_with_8bit(model): swap the linear layers for 8-bit versions. Nothing has actually been quantized yet. We've only changed the layer types.
model.to('cuda'): move the model to the GPU. This is where quantization happens. The weights get compressed to INT8 at the very moment they move to CUDA.
Intuition: Think of it as modding a race car. First assemble the car (build the skeleton and load the weights). Then swap the regular parts for lightweight ones (the quantized layers). Then drive it onto the track (move it to CUDA), and the weight savings only kick in at the moment it hits the track.
Watch out: The order matters: load the weights first, then swap the layers, and move to the GPU last. Get the order wrong, or forget to move to the GPU, and quantization won't happen the way you expect.
The Hugging Face way
With Hugging Face it's even simpler. Write a BitsAndBytesConfig (4 bits, NF4, BF16 for compute, double quantization on) and pass it in when you load the model. For 8 bits, use load_in_8bit=True instead.
cfg = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
model_name, quantization_config=cfg)
Back to where we started
Our 7-billion-parameter model:
| Format |
Weight memory |
| FP32 |
28 GB |
| BF16 |
14 GB |
| INT8 |
7 GB |
| NF4 |
~3.5 GB (+ scales) |
From too big for a high-end graphics card to small enough to run on a laptop. And our first puzzle: why does the model still work after we cut so many bits? Because networks are forgiving of small rounding errors, and scale factors and NF4 squeeze those errors down as far as they can.
Recap
- A float is sign + exponent + mantissa, x=(−1)s×1.m×2E−bias. The exponent sets the range, the mantissa sets the precision, and the error is relative.
- FP16 (5/10) tops out at 65,504, so it overflows to inf/NaN and underflows to 0. BF16 (8/7) has FP32's range with coarser precision, and is the default for training.
- Mixed precision: FP32 master weights, BF16 forward and backward passes, gradients accumulated in FP32. FP16 also needs loss scaling (
GradScaler).
- For inference, load in BF16.
autocast picks a precision per operation and doesn't manage the master weights.
- Quantization uses scale factors to fit weights into INT8 or NF4 slots, with per-group scales to contain outliers. bitsandbytes only quantizes on
.to('cuda').
Even at 4 bits, the biggest models still won't fit on one GPU, let alone train on one. Next time we split the model across many GPUs: parallelism.