Part 09›
✎

04. Quantization#

Level: Practitioner · Reading time: 22 min · Exercise: 60 min Prerequisites: Neural Network Basics for Efficiency, Pruning and Sparsity

In one sentence: After this chapter you can quantize a trained model to 8-bit or 4-bit weights with post-training quantization, judge whether the quality loss needs quantization-aware training, and read a floating-point format from its bit layout.

Why this matters#

You want to run a 7-billion-parameter model on a laptop with 8 GB of memory. In 16-bit, the weights need 14 GB. The model does not load. In 4-bit they need 3.5 GB. It loads, and it answers faster, because there is less to move from memory.

What did that cost in quality? Where is the loss coming from? And what do you do when it is too large? Quantization is very widely used in industry (Lecture 6, 0:00), and in practice most failures come from three decisions: the scale, the range and the granularity.

The core idea#

Quantization constrains values to a small discrete set (Han's Lecture 5, slide 22). The difference between a value and its quantized replacement is the quantization error.

Han's slide shows the idea with a picture: reduce a photograph to 16 colors, with a palette. Each pixel keeps its nearest palette entry. The analogy breaks in one place. A picture is converted once. A network applies its rounding at every layer, for every input, and errors from early layers feed into later ones. That is why networks need calibration or retraining and photographs do not.

Model size is parameters times bits per parameter (Lecture 5, 0:00). Pruning cuts the first factor; quantization cuts the second. Low bit widths also save energy. Han's slide 3, citing Horowitz's 2014 measurements at 45 nm, lists a 32-bit floating-point multiply at 3.7 picojoules and an 8-bit integer multiply at 0.2 (as reported on the slide).

How it works, step by step#

1. Know the number formats#

Format Sign / exponent / fraction bits Range of values Typical use
INT8 8-bit two's complement integers from −128 to 127, fixed steps quantized weights and activations
FP32 1 / 8 / 23 about ±3 × 10³⁸, 24 significant bits training
FP16 1 / 5 / 10 about ±65,504, 11 significant bits activations
BF16 1 / 8 / 7 same range as FP32, 8 significant bits training
FP8 (E4M3, E5M2) 1 / 4 / 3 and 1 / 5 / 2 E4M3 up to 448; E5M2 for gradients training and inference on new hardware
FP4 (for example E2M1) 1 / 2 / 1 0, 0.5, 1, 1.5, 2, 3, 4, 6 and negatives weights on supporting hardware

A floating-point number is (−1)^s × (1 + fraction) × 2^(exponent − bias), where s is the sign bit, the exponent picks the power of two and the fraction (or mantissa) holds the digits after the leading 1. Han's rule: exponent width sets the range, fraction width sets the precision (slide 17).

Worked example from his slide 18. The FP16 bits are 1 10001 1100000000:

2. Linear quantization: map reals to integers#

Han's slides 47 and 48 give the affine mapping:

r = S × (q − Z)

With symmetric quantization, Z is 0 and S = |r|max / q_max. Han notes that weights are distributed around zero, so Z can be dropped for weights, which removes a whole term from the arithmetic (Lecture 5, 58:00).

Worked numbers. Quantize the weights [2.09, −0.98, 1.48, 0.09].

Bits q_max Scale Quantized weights Largest error
2 1 2.09 2.09, 0, 2.09, 0 0.98
8 127 2.09 / 127 = 0.0165 2.09, −0.99, 1.48, 0.08 0.008

Two bits is unusable here: 1.48 becomes 2.09. Eight bits keeps every weight within half a step, S / 2.

Once weights and activations are integers, the multiply-accumulate runs in integer arithmetic. The result is rescaled by Sw × Sx / Sy, and the additions use 32-bit integers to avoid overflow (Lecture 5, 52:00, slides 55 to 57). This is what makes linear quantization faster as well as smaller.

Han groups quantization into three families (Lecture 5, slide 44):

Family Storage Arithmetic What you gain
K-means with a codebook small indices plus a table of representative values floating point (values are looked up first) storage only
Linear integers integer storage and speed
Binary and ternary 1 or 2 bits XNOR and popcount on special hardware storage and speed, at a large accuracy cost

For k-means, his example stores 16 weights with 2-bit indices: a 4-byte index map and a 16-byte table (the codebook, the list of allowed values), 20 bytes instead of 64 (34:00). The saving is about 32 divided by the bit width: 16 times at 2 bits, 8 times at 4 bits. His verdict on it: "It saved the storage, but it doesn't save the computation" (48:00). It still pays off for a single user generating text, because that workload is limited by memory.

3. Post-training quantization#

Post-training quantization (PTQ) converts a trained model without retraining it. Han organizes the choices in three topics (Lecture 6, 4:00):

Granularity: how many weights share one scale.

Clipping: where to cut the range. A single large value, an outlier, forces a large scale and therefore coarse steps for all the other values. Activations change with every input, so their range has to be collected first: by tracking an exponential moving average of the minimum and maximum during training, or by gathering statistics from sample inputs before deployment (24:00). Cutting the range below the maximum is a trade-off. Han's example is an activation distribution that reaches about 400 with a long tail, while most values sit below 40: cutting the range near 50 clips the whole tail onto one value. He names KL-divergence calibration, where the KL divergence measures how one distribution differs from another, as a widely used way to choose the cut, because it minimizes the information lost between the distributions before and after quantization (30:00).

Rounding. Round to nearest is the default. Alternatives are stochastic rounding and learned rounding, where the network learns whether each weight should round up or down (Han mentions AdaRound at 38:00).

The procedure:

  1. Fix a float baseline. Record its accuracy on held-out data.
  2. Compute scales for the weights (per channel, or per group below 8 bits).
  3. Run a few hundred representative inputs through the model and record the range of each activation.
  4. Choose the clipping range and quantize.
  5. Evaluate again, on real tasks and not on one prompt.
  6. If the drop is too large, go finer in granularity. If it is still too large, move to quantization-aware training.

Figure 1. Post-training quantization: one pass, one decision, and where quantization-aware training begins.

flowchart TD
    A["Record float baseline accuracy"] --> B["Compute weight scales"]
    B --> C["Record activation ranges on sample inputs"]
    C --> D["Choose the clipping range and quantize"]
    D --> E["Evaluate again"]
    E -->|"drop acceptable"| K["Ship the quantized model"]
    E -->|"drop too large"| F["Go finer in granularity"]
    F --> D
    F -->|"still too large"| Q["Quantization-aware training"]

Post-training quantization needs only sample inputs, not training; quantization-aware training is the fallback once finer scales stop helping.

Outliers in language models: the SmoothQuant idea#

Large language models have a few activation channels with much larger values than the rest. Quantizing those activations to 8 bits with one scale fails. In Lecture 1, Han describes the fix that came out of a course project: the outliers sit in the activations, and since matrix multiplication is linear, you can scale the weights and the activations so that the two are equalized and smoothed, which makes both easier to quantize over the full dynamic range (34:00).

The SmoothQuant paper picks the factor per input channel so that both sides end up with the same maximum:

Y = (X / s) × (s × W),    s_j = max|X_j| ^ 0.5 / max|W_j| ^ 0.5

Worked numbers: activation column j peaks at 20, weight column j peaks at 0.02. Then s_j is the square root of 20 / 0.02, about 31.6. The activation column now peaks at 0.63 and the weight column at 0.63. Both fit an 8-bit range.

4. Quantization-aware training#

Quantization-aware training (QAT) fine-tunes the model with the quantization in place, so that the weights adapt to it. Han notes that even with every post-training technique, small models such as MobileNet still lost accuracy in his experiments, which is where QAT starts (Lecture 6, 40:00). The reverse holds for language models: since they are very costly to train, he says, the goal there is post-training quantization with no fine-tuning at all (46:00).

  1. Keep a full-precision copy of every weight.
  2. In the forward pass, quantize and immediately dequantize, so the next layer sees rounded values.
  3. In the backward pass, pretend the rounding step is the identity function and pass the gradient through unchanged. This is the straight-through estimator (46:00).
  4. Update the float copy. Repeat.

5. Mixed precision#

Not every layer needs the same bit width. Han's advice (Lecture 6, 66:00): cheap or memory-bound layers can stay in FP16 or FP32; compute-bound layers should go lower if they are not sensitive. Choosing per layer gives higher accuracy at the same latency, or the same accuracy at a lower latency, and the choice can be made automatically: the same hardware-aware search, Han says, can target model size, latency or energy.

What each option costs and when to choose it#

Option Size versus FP16 Accuracy cost Data needed Choose when
PTQ, 8-bit weights and activations 1/2 near zero for most models a few hundred samples default on phones and servers
PTQ, 4-bit weights in groups, float activations 1/4 small; grows for small models and hard tasks a little language models on one machine
QAT, 8-bit or 4-bit 1/2 to 1/4 smaller than PTQ training data and compute PTQ lost too much
K-means codebook 1/8 at 4 bits small after fine-tuning none to quantize storage is the only concern
Binary or ternary 1/8 to 1/16 large training special hardware

Worked example#

Symmetric linear quantization in NumPy, on a weight block with one outlier.

import numpy as np

def quantize(r, bits=8, axis=None):
    """Symmetric linear quantization: r is approximated by q * scale."""
    qmax = 2 ** (bits - 1) - 1                         # largest signed value
    scale = np.abs(r).max(axis=axis, keepdims=True) / qmax
    q = np.clip(np.round(r / scale), -qmax - 1, qmax)
    return q.astype(np.int32), scale                   # dequantize with q * scale

def mean_error(q, scale):
    return np.abs(q * scale - W).mean()

rng = np.random.default_rng(0)
W = rng.standard_normal((4, 1000)) * 0.01              # four channels of small weights
W[0, 0] = 1.0                                         # one outlier in channel 0

q, s = quantize(W)                                    # one scale for everything
print(f"8-bit per-tensor:   mean error {mean_error(q, s):.5f}")
q, s = quantize(W, axis=1)                            # one scale per channel
print(f"8-bit per-channel:  mean error {mean_error(q, s):.5f}")
q, s = quantize(W, bits=4)
print(f"4-bit per-tensor:   mean error {mean_error(q, s):.5f}")
q, s = quantize(W, bits=4, axis=1)
print(f"4-bit per-channel:  mean error {mean_error(q, s):.5f}")

What to observe:

What the practitioners say#

Pitfalls#

  1. Quantizing every layer to the same width. Embeddings (the layers that turn tokens into vectors), the first layer, the last layer and the final normalization are sensitive. Fix: keep them in 16 bits.
  2. Using one scale at 4 bits. Fix: per-channel scales, and group scales below 8 bits.
  3. Ignoring activation outliers in language models. Fix: smooth them into the weights, or quantize weights only.
  4. Judging quality by one prompt or by perplexity alone (how well the model predicts text). Fix: run your evaluation set against the float baseline.
  5. Assuming a smaller file means a faster model. Fix: check that your inference engine has a fast kernel for that format; otherwise you saved memory only.
  6. Forgetting the cache of past tokens. With long inputs it can outweigh the weights. See efficient LLM inference.

Try it#

Quantize the weights of a small trained classifier with the quantize function above; activations stay in floating point. Put the dequantized weights, q * scale, back into the model before you measure accuracy.

  1. Record float accuracy and file size.
  2. Apply 8-bit per-tensor quantization to every weight. Record accuracy and size.
  3. Repeat with 4-bit per-tensor and 4-bit per-channel.
  4. Write one paragraph that explains the differences using the scale of each layer.

You are done when you have a four-row table (float, INT8, INT4 per-tensor, INT4 per-channel) with accuracy, bytes, and the largest scale you found.

Stretch: implement the SmoothQuant rescaling on one layer with an activation outlier and show the 8-bit error before and after.

Key takeaways#

Self-check#

  1. A model has 3 billion parameters. What is its weight memory at 16-bit, 8-bit and 4-bit?
  2. In r = S × (q − Z), what do S and Z mean, and when can Z be dropped?
  3. FP16 has 5 exponent bits and 10 fraction bits. BF16 has 8 and 7. Which has the wider range, and which the finer precision?
  4. A small model loses 4 accuracy points after 4-bit post-training quantization. What do you try before quantization-aware training?
  5. What does the straight-through estimator do?
  6. Why does k-means codebook quantization not speed up arithmetic on its own?
Show answers 1. 6 GB, 3 GB and 1.5 GB. 2. `S` is the real size of one integer step. `Z` is the integer that represents the real 0. It can be dropped for symmetric ranges, such as weights centered on zero. 3. BF16 has the wider range. FP16 has the finer precision. 4. Use per-channel or group scales, and check the clipping range. Only then move to QAT. 5. It lets the gradient pass through the rounding step as if rounding were the identity function. 6. The indices are looked up in a floating-point table first, and the arithmetic stays floating point. Only storage shrinks.

Sources#

Next#

→ Knowledge Distillation, which changes the model instead of its storage, or jump to Efficient LLM Inference and Deployment to see where quantized weights pay off most.