Unit 8 of 9
Quantization: fewer bits, measured error
What you’ll learn
- Compare FP32, BF16, FP16, FP8, INT8, and INT4 by bytes per value, range, and precision.
- Quantize and restore values by hand with a scale and a zero point, and predict the largest rounding error.
- Choose per-tensor, per-channel, or per-group scales, and count what their metadata costs in bytes.
- Estimate a quantized model’s weight memory and its decode speed limit from the bytes it moves.
- Plan an evaluation that checks quality, memory, and speed before a quantized model ships.
Why fewer bits make decode faster
Llama 3.1 8B stores 8.03 billion weights in BF16, 2 bytes each: about 16 GB. In the batching lesson you saw that every decode step reads all of them, so on an H100 a single request can never go faster than one token per 4.8 ms. Batching shares that read among requests. Quantization makes the read smaller by storing each weight in fewer bits.
Llama 3.1 8B weights at fewer bits, if every parameter shrank
- BF16, 2 bytes per weight
8.03 billion × 2 = 16.06 GB - FP8 or INT8, 1 byte per weight
8.03 billion × 1 = 8.03 GB - INT4, half a byte per weight
8.03 billion × 0.5 ≈ 4.02 GB
ResultUp to 4 times fewer bytes to store and to read at every decode step
Fewer bits can hold fewer distinct numbers, so every quantized weight is an approximation. The work is to choose where that error goes and to measure it. By the end of this lesson you will be able to quantize numbers by hand, predict the error and the storage cost including metadata, explain why published checkpoints are larger than the estimate above, and decide what a quantized model must pass before you serve it.
Number formats: bytes, range, and precision
A floating-point number has three parts: a sign bit, exponent bits that set how large or small it can be, and mantissa bits that set how finely it can distinguish nearby values. BF16 keeps FP32’s 8 exponent bits, so it covers the same range, but has only 7 mantissa bits. FP16 trades range for precision: 5 exponent bits and 10 mantissa bits. FP8 comes in two layouts: E4M3 (4 exponent bits, 3 mantissa bits) for weights and activations, and E5M2 (5 and 2) for gradients in training.
Integers work differently. INT8 has 256 evenly spaced codes, −128 to 127, and INT4 has 16, −8 to 7. They carry no exponent, so on their own they cannot represent 0.037 or 1,500. A separate scale, stored alongside the codes, maps them onto the real range a tensor needs.
| Format | Bytes per value | Bits: sign, exponent, mantissa | Largest value | Gap after 1.0 | Typical use |
|---|---|---|---|---|---|
| FP32 | 4 | 1, 8, 23 | about 3.4 × 10³⁸ | about 0.00000012 | Reference math, training |
| BF16 | 2 | 1, 8, 7 | about 3.4 × 10³⁸ | 0.0078 | Default weights and activations |
| FP16 | 2 | 1, 5, 10 | 65,504 | 0.00098 | Older GPUs; overflows past 65,504 |
| FP8 E4M3 | 1 | 1, 4, 3 | 448 | 0.125 | Weights, activations, KV cache on Hopper and Ada GPUs |
| INT8 | 1 | 8-bit integer | 127 × scale | one scale step, everywhere | Weights and activations with a scale |
| INT4 | 0.5 | 4-bit integer | 7 × scale | one scale step, everywhere | Weights only, with a scale per group |
Two consequences follow. Floating-point formats have relative precision: the gap between neighbors grows with the value, so small and large numbers keep roughly the same number of significant digits. Integer formats have absolute precision: every neighbor is one scale step apart, so small values in a tensor with a large range get very few codes. That is why the choice of scale matters so much.
Scale and zero point: map real numbers onto integers
Start with the simplest mapping, symmetric quantization. Choose the scale so the largest magnitude lands on code 127, divide every value by the scale, and round to the nearest integer. To restore a value, multiply its code by the scale.
Symmetric INT8 for four weights: 0.4213, −1.2700, 0.0327, 0.8861
- Scale: largest magnitude / 127
1.27 / 127 = 0.01 - Divide by the scale
42.13, −127.00, 3.27, 88.61 - Round to codes (1 byte each)
42, −127, 3, 89 - Restore: code × scale
0.42, −1.27, 0.03, 0.89 - Error
0.0013, 0, 0.0027, 0.0039
ResultEvery error is at most half a step: 0.01 / 2 = 0.005
Symmetric mapping wastes codes when the values are lopsided, such as a range from −0.51 to 2.04: codes below −41 would never be used. Asymmetric (affine) quantization stretches all 256 codes over the actual range and adds an integer zero point, the code that stands for real 0. The script in the try-it section below uses this form:
scale = (max − min) / 255
zero_point = round(−128 − min / scale)
code = clip(round(x / scale) + zero_point, −128, 127)
restored = (code − zero_point) × scaleAffine INT8 for the range −0.51 to 2.04
- Scale
(2.04 − (−0.51)) / 255 = 2.55 / 255 = 0.01 - Zero point
round(−128 − (−0.51 / 0.01)) = round(−128 + 51) = −77 - Encode 1.234
round(123.4) − 77 = 123 − 77 = 46 - Restore code 46
(46 − (−77)) × 0.01 = 123 × 0.01 = 1.23 - Encode 0.0 and restore it
0 − 77 = −77, then (−77 + 77) × 0.01 = 0.0 exactly
ResultError for 1.234 is 0.004, within half a step
Rounding error is bounded; clipping error is not. A value outside the range, say 3.00, would need code 300 − 77 = 223, which is clipped to 127 and restored as 2.04: an error of 0.96, about 190 times the worst rounding error. Choosing the range is a trade between those two errors, and that choice is called calibration.
Per-tensor, per-channel, and per-group scales
The scale is set by the largest value it has to cover, so one outlier coarsens every value that shares its scale. Here is a small weight matrix with one large weight, 6.35, quantized with a single scale for the whole tensor: 6.35 / 127 = 0.05.
The fix is to give fewer weights each scale. In this lesson a weight matrix is stored as (inputs, outputs), as in y = x @ W, so each column produces one output channel. (PyTorch’s nn.Linear stores the transpose, with one row per output channel.)
- Per tensor: one scale for the whole matrix. Cheapest, but every weight pays for the largest one.
- Per channel: one scale per output channel. In the example, only column 1, which holds the outlier, stays coarse: 3 small weights change instead of 14.
- Per group: one scale per run of consecutive inputs within a channel, typically 128 of them for 4-bit weights. With groups of 2 rows in the example, only −0.07, which shares a group with 6.35, changes.
Each extra scale costs bytes. For a 4,096 × 4,096 projection in Llama 3.1 8B with FP16 scales, per-channel scaling needs 4,096 scales (8 KiB), and groups of 128 need 131,072 scales (256 KiB), an extra 16 / 128 = 0.125 bits per weight. That is why a 4-bit format usually stores about 4.1 to 4.25 bits per weight once scales and zero points are counted.
Always add the metadata before you quote a size. Take a 128 × 64 weight matrix quantized to INT8 with one FP32 scale and one INT32 zero point per output column:
Storage for a 128 × 64 matrix, INT8 with per-column metadata
- INT8 codes
128 × 64 = 8,192 weights × 1 byte = 8,192 bytes - FP32 scales, one per column
64 × 4 bytes = 256 bytes - INT32 zero points, one per column
64 × 4 bytes = 256 bytes - Total
8,192 + 256 + 256 = 8,704 bytes - The same matrix in FP32
8,192 × 4 bytes = 32,768 bytes
Result32,768 / 8,704 ≈ 3.76 times smaller, not 4
Calibration and outliers
Calibration chooses the range each scale must cover. For weights it is easy, because the checkpoint is fixed: read every weight and compute the scales once. Activations, the values flowing between layers, change with every input. There are two ways to handle them:
- Static scales are measured ahead of time by running a few hundred representative prompts through the model and recording each tensor’s range. They cost nothing at run time, but inputs unlike the calibration set can clip.
- Dynamic scales are computed from the actual values at run time, often one scale per token. They adapt to every input, at the cost of an extra pass over the values.
Taking the full minimum and maximum never clips, but a single extreme value then coarsens everything else. Methods that clip a small fraction of extreme values, chosen by percentile or by minimizing the average error, often give a lower total error. Test both on your own data rather than assuming either.
Large language models make this harder, because their activations contain systematic outliers: a few hidden dimensions carry values far larger than the rest. The LLM.int8() paper handles them by running those dimensions in 16-bit while more than 99.9% of values are multiplied in 8-bit. SmoothQuant observes that weights are easy to quantize while activations are not, and moves part of the activation range into the weights with an equivalent rescaling. AWQ finds that protecting about 1% of salient weight channels, chosen by looking at activations, greatly reduces the error of 4-bit weights. GPTQ rounds weights one at a time and adjusts the remaining ones to compensate, using second-order information, reaching 3 or 4 bits with little accuracy loss.
All of these methods start from a trained model, which is called post-training quantization. Quantization-aware training instead simulates low precision during training so the model can adapt, which costs a training run. Whichever you use, calibrate on data that looks like your traffic (the same languages, code, and prompt lengths) and evaluate on different data.
Weight-only versus weight-and-activation, and what gets faster
Quantized storage and quantized math are separate choices. The table shows the three common schemes; names like W4A16 mean 4-bit weights and 16-bit activations.
| Scheme | Stored in low precision | Matrix math runs in | Speeds up |
|---|---|---|---|
| Weight-only (W4A16, W8A16) | Weights | BF16 or FP16, after converting weights inside the kernel | Memory-bound decode at small batches |
| Weight and activation (W8A8, INT8 or FP8) | Weights and activations | INT8 or FP8 tensor cores | Decode and compute-bound prefill |
| KV cache (FP8 cache) | Cached keys and values | Unchanged | Capacity and long-context decode |
For decode at small batches the rule is simple: the step time follows the bytes read. Published checkpoints are larger than the 8.03 billion × bytes estimate, though, because they keep the embedding table and the output layer in 16 bits and store scales. Each of those tensors holds 128,256 × 4,096 ≈ 525 million values, and together they take 2.1 GB in BF16.
Batch-1 decode ceiling from checkpoint size, H100 at 3.35 TB/s
- BF16, 16.06 GB
16.06 / 3,350 GB/s ≈ 4.8 ms per token, about 209 tokens per second - FP8, 9.08 GB
9.08 / 3,350 GB/s ≈ 2.7 ms per token, about 369 tokens per second - INT4 (AWQ), 5.73 GB
5.73 / 3,350 GB/s ≈ 1.7 ms per token, about 585 tokens per second
ResultUp to 2.8 times faster decode at batch 1 for 4-bit weights
Compute-bound work is different. Prefill and large batches are limited by math, and weight-only kernels still do their math in BF16, plus the work of converting weights, so their advantage fades as the batch grows. The Marlin paper reports close to the full 4 times speedup for 4-bit weights up to batch sizes of 16 to 32, shrinking gradually up to 64 to 128. Weight-and-activation schemes speed up the math itself: an H100 runs FP8 and INT8 at about 1,979 dense teraFLOPS, twice its BF16 rate. vLLM’s documentation reports up to 1.6 times higher throughput for FP8 models.
The saved memory is a second gain. Dropping from 16.06 GB to 9.08 GB frees about 7 GB for the KV cache, room for about 53,000 more tokens of Llama 3.1 8B context.
Evaluate quality before you ship
A quantized model can look fine on a quick chat and still fail on your traffic. Evaluate it against the unquantized model with everything else held fixed:
- Fix the baseline
Run the BF16 model and the quantized model with the same prompts, chat template, and decoding settings. Greedy decoding makes differences easy to see.
- Check perplexity on held-out text
Perplexity measures how surprised the model is by real text. A small rise is normal; a large one means something broke, often a layer that should have stayed in 16 bits.
- Measure task accuracy
Score a few hundred labeled examples of the tasks you serve, plus any public benchmark that matches them. Compare the difference with the run-to-run noise of the benchmark.
- Read the differences
Count how often greedy outputs diverge from the baseline, and read the divergent ones. Include long contexts, other languages, code, and arithmetic, where quantization errors tend to show first.
- Measure speed and memory on the target GPU
Record peak memory, time to first token, inter-token latency, and throughput at the batch sizes you will run. Keep the workload identical for both models.
Try it: quantize a matrix and measure the error
The script below quantizes a 128 × 64 FP32 matrix to INT8 with one scale and zero point per output column, restores it, and compares a matrix multiplication against the FP32 result. It needs only Python 3.9 or later and NumPy. Predict the storage line before you run it; you calculated it above. The code example below the walkthrough writes this same file and runs it in one paste.
import numpy as np
rng = np.random.default_rng(10)
# Weights stored as (inputs, outputs), as in y = x @ w: 64 output columns.
w = rng.normal(0, 0.5, (128, 64)).astype(np.float32)
x = rng.normal(size=(16, 128)).astype(np.float32)
def quantize_int8(w):
"""Affine INT8 with one scale and one zero point per output column."""
low = np.minimum(w.min(axis=0), 0.0) # keep real 0 inside the range
high = np.maximum(w.max(axis=0), 0.0)
scale = ((high - low) / 255).astype(np.float32)
zero_point = np.rint(-128 - low / scale).astype(np.int32)
codes = np.clip(np.rint(w / scale) + zero_point, -128, 127).astype(np.int8)
return codes, scale, zero_point
def restore(codes, scale, zero_point):
# Widen before subtracting: in INT8, 127 - (-77) would wrap around.
return (codes.astype(np.float32) - zero_point) * scale
codes, scale, zero_point = quantize_int8(w)
restored = restore(codes, scale, zero_point)
print(f"column 0: scale {scale[0]:.6f}, zero point {zero_point[0]}")
print(" weights ", np.round(w[:4, 0], 4))
print(" codes ", codes[:4, 0])
print(" restored", np.round(restored[:4, 0], 4))
total = codes.nbytes + scale.nbytes + zero_point.nbytes
print(f"storage: {codes.nbytes:,} codes + {scale.nbytes} scales "
f"+ {zero_point.nbytes} zero points = {total:,} bytes")
print(f"FP32 needs {w.nbytes:,} bytes, {w.nbytes / total:.2f} times as many")
error = np.abs(w - restored)
print(f"largest weight error {error.max():.6f}, "
f"half the widest step {scale.max() / 2:.6f}")
print("every error within half its column's step:", bool((error <= scale / 2).all()))
exact = x @ w
approx = x @ restored
print(f"matmul: mean error {np.abs(exact - approx).mean():.6f}, "
f"mean output size {np.abs(exact).mean():.4f}")column 0: scale 0.012764, zero point -10
weights [-0.5517 -0.725 -0.6473 0.307 ]
codes [-53 -67 -61 14]
restored [-0.5489 -0.7275 -0.651 0.3063]
storage: 8,192 codes + 256 scales + 256 zero points = 8,704 bytes
FP32 needs 32,768 bytes, 3.76 times as many
largest weight error 0.006627, half the widest step 0.006628
every error within half its column's step: True
matmul: mean error 0.026402, mean output size 4.5318The storage line matches the 8,704-byte calculation. Column 0 shows the affine map at work: its values run from −1.51 to 1.75, so real zero sits a little below the middle of the range, at code −10 rather than about 0, and each restored weight lands within half a step, 0.0064, of the original. The largest error in the whole matrix, 0.006627, sits right at the bound set by the widest column’s step, and no error exceeds half of its own column’s step. The matmul error is about 0.6% of a typical output.
The script restores the weights to FP32 before it multiplies, so it saves memory but gains no speed. Real speedups need kernels that read the compact codes directly, as the section on weight-only and weight-and-activation schemes explained.
Next, compare scale granularities on a larger matrix with one outlier:
import numpy as np
rng = np.random.default_rng(0)
# Weights stored as (inputs, outputs), as in y = x @ w. Real weights are small.
w = rng.normal(0, 0.02, (512, 256)).astype(np.float32)
w[3, 5] = 1.0 # one outlier, 50 times the typical size
def quantize(w, bits, rows):
"""Symmetric quantization with one FP32 scale per block of `rows` inputs."""
top = 2 ** (bits - 1) - 1 # 127 for INT8, 7 for INT4
if rows == "all":
blocks = w.reshape(1, -1, 1) # one block holds every weight
else:
blocks = w.reshape(-1, rows, w.shape[1]) # (groups, rows, outputs)
scale = np.abs(blocks).max(axis=1, keepdims=True) / top
codes = np.clip(np.rint(blocks / scale), -top, top)
restored = (codes * scale).reshape(w.shape)
size = w.size * bits // 8 + scale.size * 4 # packed codes + FP32 scales
return restored, size, scale.size
print(f"FP32 weights: {w.nbytes:,} bytes, typical size {np.abs(w).mean():.4f}")
schemes = [
("INT8, per tensor", 8, "all"),
("INT8, per channel", 8, 512),
("INT8, groups of 128", 8, 128),
("INT4, groups of 128", 4, 128),
]
for label, bits, rows in schemes:
restored, size, scales = quantize(w, bits, rows)
error = np.abs(w - restored).mean()
print(f"{label:<20} scales {scales:>5}, {size:>8,} bytes, "
f"mean error {error:.5f}")FP32 weights: 524,288 bytes, typical size 0.0160
INT8, per tensor scales 1, 131,076 bytes, mean error 0.00197
INT8, per channel scales 256, 132,096 bytes, mean error 0.00014
INT8, groups of 128 scales 1024, 135,168 bytes, mean error 0.00011
INT4, groups of 128 scales 1024, 69,632 bytes, mean error 0.00203Compare the error with the typical weight size, 0.016. One outlier makes per-tensor INT8 about 12% wrong on average, about as wrong as 4-bit groups that take half the space. Per-channel scales cut the error about 14 times for less than 1% more storage.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| The model is 3.76 times smaller, not the 4 you promised | Scales and zero points were left out of the estimate. | Count codes plus metadata for the actual granularity. |
| A 4-bit checkpoint is 5.7 GB, not 4 GB | The embedding and output layers stayed in 16 bits. | Estimate each tensor at its stored precision. |
| Restored values jump by 256 | The zero point was subtracted in INT8 arithmetic. | Cast codes to a wider type first. |
| Most small weights round to zero | One outlier sets a per-tensor scale. | Use per-channel or per-group scales. |
| Quality drops only on certain traffic | Static activation scales were calibrated on different data. | Calibrate on representative data or use dynamic scales. |
| Memory fell but decode is no faster | The kernel converts weights to 16 bits first, or the batch is large enough to be compute-bound. | Check the kernel your engine picked, and measure at your real batch size. |
| Quantization error looks fine but answers got worse | Only the weight error was measured. | Measure task accuracy and output differences end to end. |
How real engines use quantization
- Ready-made checkpoints. Most teams serve a published quantized checkpoint. The FP8 Llama 3.1 8B checkpoint in the figure uses static per-tensor scales; the INT4 one is AWQ with groups of 128 and zero points.
- FP8 in vLLM.
--quantization fp8quantizes a BF16 model when it loads, with per-tensor scales. vLLM supports FP8 W8A8 on Hopper and Ada GPUs, and weight-only FP8 on Turing and Ampere GPUs through Marlin kernels. - Recipes you run yourself. The llm-compressor FP8 recipe in vLLM’s documentation uses static per-channel weight scales, dynamic per-token activation scales, and leaves
lm_headunquantized. - 4-bit weights. GPTQ and AWQ produce 4-bit weight-only checkpoints that engines serve with kernels such as Marlin.
- KV cache.
--kv-cache-dtype fp8halves the cache, as the KV cache lesson showed. It is independent of how the weights are stored.
The vLLM memory and quantization lesson covers these options in practice. Whatever the engine, check its startup log for the quantization method and kernel it chose, because a fallback kernel can erase the speedup silently.
Go deeperWhere the bytes of a decode step really go
The input embedding table is looked up, not multiplied: a decode step reads one 4,096-value row per token, not all 525 million values. The output layer, by contrast, is a full matrix multiplication and is read completely. So a BF16 decode step reads about 16.06 − 1.05 = 15.0 GB, and a 4-bit AWQ step about 5.73 − 1.05 = 4.7 GB. The course rounds the BF16 figure to 16 GB, which makes its speed limits slightly conservative.
Quantizing the output layer would save another 0.5 GB or more, but its errors land directly on the logits that choose each token, so most recipes leave it at 16 bits. Measure before you change that default.
Cheat sheet
- Bytes per value: FP32 4, BF16 and FP16 2, FP8 and INT8 1, INT4 0.5.
- Symmetric: scale = largest magnitude / 127. Affine: scale = (max − min) / 255 plus an integer zero point.
- Rounding error is at most half a scale step; clipping error has no bound.
- Finer scales cost metadata: groups of 128 add 0.125 bits per weight per FP16 value stored.
- Always count metadata: 8,192 INT8 codes + 64 FP32 scales + 64 INT32 zero points = 8,704 bytes.
- Weight-only quantization speeds up memory-bound decode; W8A8 also speeds up compute-bound prefill.
- Llama 3.1 8B checkpoints: 16.06 GB in BF16, 9.08 GB in FP8, 5.73 GB in 4-bit AWQ.
- Judge a quantized model by task quality and by speed on the target GPU, not by weight error alone.
Walkthrough
Quantize and restore one row of weights
Code example Optional · Write int8_quantize.py and run it
cat > int8_quantize.py <<'EOF'
import numpy as np
rng = np.random.default_rng(10)
# Weights stored as (inputs, outputs), as in y = x @ w: 64 output columns.
w = rng.normal(0, 0.5, (128, 64)).astype(np.float32)
x = rng.normal(size=(16, 128)).astype(np.float32)
def quantize_int8(w):
"""Affine INT8 with one scale and one zero point per output column."""
low = np.minimum(w.min(axis=0), 0.0) # keep real 0 inside the range
high = np.maximum(w.max(axis=0), 0.0)
scale = ((high - low) / 255).astype(np.float32)
zero_point = np.rint(-128 - low / scale).astype(np.int32)
codes = np.clip(np.rint(w / scale) + zero_point, -128, 127).astype(np.int8)
return codes, scale, zero_point
def restore(codes, scale, zero_point):
# Widen before subtracting: in INT8, 127 - (-77) would wrap around.
return (codes.astype(np.float32) - zero_point) * scale
codes, scale, zero_point = quantize_int8(w)
restored = restore(codes, scale, zero_point)
print(f"column 0: scale {scale[0]:.6f}, zero point {zero_point[0]}")
print(" weights ", np.round(w[:4, 0], 4))
print(" codes ", codes[:4, 0])
print(" restored", np.round(restored[:4, 0], 4))
total = codes.nbytes + scale.nbytes + zero_point.nbytes
print(f"storage: {codes.nbytes:,} codes + {scale.nbytes} scales "
f"+ {zero_point.nbytes} zero points = {total:,} bytes")
print(f"FP32 needs {w.nbytes:,} bytes, {w.nbytes / total:.2f} times as many")
error = np.abs(w - restored)
print(f"largest weight error {error.max():.6f}, "
f"half the widest step {scale.max() / 2:.6f}")
print("every error within half its column's step:", bool((error <= scale / 2).all()))
exact = x @ w
approx = x @ restored
print(f"matmul: mean error {np.abs(exact - approx).mean():.6f}, "
f"mean output size {np.abs(exact).mean():.4f}")
EOF
python3 int8_quantize.pyKnowledge check
A matrix has 8,192 INT8 weights, 64 FP32 scales, and 64 INT32 zero points. How many bytes does it occupy?
Sources and further reading
- Hugging Face: quantization concepts
- Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference
- FP8 formats for deep learning (E4M3 and E5M2)
- Transformer Engine: FP8 formats and ranges
- LLM.int8(): 8-bit matrix multiplication with outlier features
- SmoothQuant
- GPTQ
- AWQ: activation-aware weight quantization
- MARLIN: mixed-precision kernels for batched inference
- vLLM FP8 quantization (v0.28.0)
- NVIDIA H100 specifications
- Llama 3.1 8B Instruct in FP8 (checkpoint files)
- Llama 3.1 8B Instruct in 4-bit AWQ (checkpoint files)