Skip to content
LearnAI

4.2Quantization

Storing a model's numbers in 8 or 4 bits instead of 16, why that barely hurts quality, and the tricks (groups, outliers, GPTQ, AWQ) that make it work.

⏱ 14 minIntermediate

Fewer bits, same model

A model’s memory footprint is simple arithmetic: number of parametersParameter (weight)A number inside a model that is adjusted during training. Modern LLMs have billions to trillions of them. times bytes per parameter. Llama 3.1 70B has about 70 billion weights; in 16-bit precision (BF16BF16 (bfloat16)A 16-bit floating-point format with the same exponent range as FP32 but less precision, widely used for training. or FP16) that’s about 140 GB, more than any single 80 GB GPU holds. Store each weight in 4 bits instead and the same model needs about 35 GB plus a little overhead. It now fits on one GPU, or a high-end laptop.

Memory is not the only win. In the KV cache lesson we saw that decoding is memory-boundMemory-bound (vs compute-bound)A workload is memory-bound when its speed is limited by how fast data can be moved from memory, not by arithmetic. The deciding ratio is arithmetic intensity: FLOPs performed per byte moved.: each generated token requires streaming every weight from memory. Read a quarter of the bytes, and each step can be up to about 4× faster, even if the arithmetic itself still happens in 16-bit after the weights are unpacked.

QuantizationQuantizationStoring or computing with fewer bits per number (for example INT8 or INT4 instead of 16-bit) to save memory and time, at some cost in precision. is the process of mapping numbers onto a small set of representable values. The surprising empirical fact behind it is that LLMs are remarkably tolerant of this. At 8 bits most models are practically indistinguishable from the original; at 4 bits, with the techniques in this lesson, quality usually drops only slightly. Below about 3 bits, things start to break.

ANALOGY· A ruler with only sixteen tick marks

Imagine measuring a table of objects with a ruler that has only 16 tick marks, and you must write down the nearest tick instead of the exact length. Before measuring, you choose where the ruler starts and how far apart the ticks are. Put the ticks too far apart and small objects all round to “tick 0”; too close and long objects run off the end.

Each measurement becomes a tick number, a 4-bit integer. The tick spacing is the scale, and the ruler’s starting point is the zero-point. If one giant object is on the table, a single ruler must stretch to cover it, and every ordinary object gets measured coarsely. That’s the outlier problem. The fix: give each small group of objects its own ruler (group-wise scales), or measure the giant separately.

What gets quantized

Three kinds of tensors can be stored at lower precision, and they behave differently:

The lesson’s demo focuses on weights, but the ideas carry over to all three.

The basic recipe: scale and zero-point

The standard scheme is uniform affine quantization. Pick a range [α,β][\alpha, \beta] that your values should cover and a bit width bb, giving 2b2^b integer codes. The scale ss is the spacing between neighbouring representable values, and the zero-point zz is the integer code that represents the real value 0. To quantize, divide by the scale, round, shift by the zero-point and clamp; to dequantize, undo it:

q=clamp ⁣(round(x/s)+z,  0,  2b−1),x^=s (q−z).q = \text{clamp}\!\left(\text{round}(x / s) + z,\; 0,\; 2^b - 1\right), \qquad \hat{x} = s\,(q - z).

Symmetric quantization forces the grid to be centred on 0 (so z=0z = 0, with signed integers): simple and fast, and a good fit for weights, which are roughly symmetric around zero. Asymmetric quantization stretches the grid from the actual minimum to the actual maximum, which wastes no codes when values are lopsided, as activations after a ReLU-like function are. INT8 gives 256 levels, INT4 just 16.

The error is the gap between xx and x^\hat{x}. For values inside the range it is at most half a step, s/2s/2. Values outside the range get clipped, which can cost much more. Every design decision below is about trading those two errors against each other.

INTERACTIVEThe bits slider
Scheme
Scale per
Outliers
-4-2024← outliers down to −12outliers up to +11.5 →grid: 5 levels in view, Δ = 1.7
original weightsafter quantize → dequantizerepresentable values
original (FP32)
4-bit reconstruction
error × 5
SNR
7.0 dB
signal ÷ noise power
MSE
0.2306
mean squared error
max |error|
0.857
no clipping
effective bits/weight
4.00
70B model: 35 GB (FP16: 140)

The bulk of the weights lands on only 4 of the 16 levels. Effective bits include a 16-bit scale per group.

A 64×64 toy weight matrix (with a few huge outliers) is quantized and dequantized live. The histogram shows the original distribution in gray, the quantized values in orange and the representable grid in blue. Below, the matrix is drawn as an image so you can see the damage.

Things to try:

  1. Slide from 16 bits down to 2. At 8 bits the reconstruction is visually perfect. At 4 bits, with a single scale for the whole tensor, the image collapses into a few flat bands. The readout explains why: the bulk of the weights uses only a handful of levels.
  2. Switch “Scale per” to Group. With 4 bits and groups of 128, the picture snaps back and the SNR jumps, at a cost of about 0.125 extra bits per weight for the scales.
  3. Go back to the whole tensor and try the outlier options. “Clip range” restores the bulk’s precision but destroys the outliers (look at max error). “Keep in 16-bit” stores the six outliers separately, at a negligible memory cost, and gets the best of both.
  4. Shrink the group size to 16. Quality improves further, but now the overhead is a full extra bit per weight. Typical deployments use groups of 32 to 128.

Granularity: who shares a scale?

A scale shared by more numbers is cheaper to store but has to stretch over more extreme values. The common choices are:

  • Per-tensor: one scale for the whole matrix. Cheapest, but a single outlier ruins the grid for millions of weights, as the demo shows.
  • Per-channel: one scale per output row (or column) of the weight matrix. This is the standard for INT8 weights.
  • Group-wise: one scale per block of, say, 32, 64 or 128 consecutive weights. This is the norm for 4-bit weights. With a 16-bit scale per 128 weights, the overhead is 16/128=0.12516/128 = 0.125 bits, so “4-bit” really means about 4.1 to 4.5 bits per weight once scales and zero-points are counted.

That overhead is why the 70B example lands at about 35 to 40 GB rather than exactly 35 GB: 4-bit codes take 35 GB, group scales add a few percent, and many formats keep sensitive parts (embeddings, the output layer, sometimes attention) at higher precision.

The outlier problem

LLMs don’t have tidy Gaussian activations. The LLM.int8() paper found that once models reach about 6.7B parameters, a small number of hidden-dimension channels carry activations far larger than the rest, and that these “emergent outliers” matter a lot for model quality. Clip them and quality collapses; let them set the scale and everything else gets crushed into a few levels.

The main responses mirror the demo’s toggles:

  1. Keep the outliers in high precision. LLM.int8() splits each matrix multiply: the few outlier channels are computed in 16-bit, everything else in INT8.
  2. Move the difficulty somewhere easier. SmoothQuant divides activations by a per-channel factor and multiplies the corresponding weights by the same factor. The math is unchanged, but the outliers are tamed in the activations at a small cost to the weights.
  3. Use smaller groups, so each outlier only damages its own group.

Smarter rounding: GPTQ and AWQ

Rounding each weight to its nearest grid point is not optimal. What matters is not each weight’s own error, but the error in the layer’s output for realistic inputs. That’s the insight behind post-training quantizationPost-training quantization (PTQ)Quantizing an already-trained model's weights (and sometimes activations) without retraining it, typically using a small calibration set. GPTQ and AWQ are PTQ methods. methods that use a small calibration set, a few hundred example sequences, to decide how to round.

GPTQGPTQA post-training quantization method that rounds weights one column at a time and uses approximate second-order (Hessian) information to adjust the remaining weights, compensating for each rounding error. (Frantar et al., 2022) quantizes a weight matrix one column at a time. After rounding a column, it adjusts the not-yet-quantized columns to compensate for the error just introduced, using second-order (Hessian) information computed from the calibration activations. The paper reports quantizing 175B-parameter models to 3 or 4 bits in about four GPU hours with little loss in perplexity.

AWQAWQ (Activation-aware Weight Quantization)A post-training quantization method that uses activation statistics to find the small fraction of salient weight channels and scales them up before quantizing so they lose less precision. (Lin et al., 2023) starts from the observation that not all weights are equally important: protecting about 1% of salient weight channels greatly reduces the error. It picks those channels by looking at activation magnitudes, not weight magnitudes, then scales those channels up before quantization (and the activations down to match), so they effectively get a finer grid. No mixed-precision storage is needed.

Quantization-aware trainingQuantization-aware training (QAT)Training or fine-tuning with simulated low-precision arithmetic in the forward pass, so the model learns weights that survive quantization. goes further: the model is trained or fine-tuned with quantization simulated in the forward pass, so it learns weights that survive rounding. The rounding step has zero gradient almost everywhere, so training uses the straight-through estimator, pretending rounding is the identity during the backward pass. QAT is more expensive than PTQ but holds up better at very low bit widths, and some recent open models are released with weights already trained for 4-bit formats (see Part 5).

MATH CORNER · optionalSymmetric vs asymmetric INT4, worked by hand

Symmetric (bb-bit signed, z=0z=0): s=max⁡i∣xi∣2b−1−1s = \dfrac{\max_i |x_i|}{2^{b-1}-1},   q=clamp(round(x/s),−(2b−1−1),2b−1−1)\;q = \text{clamp}(\text{round}(x/s), -(2^{b-1}-1), 2^{b-1}-1),   x^=s q\;\hat{x} = s\,q.

Asymmetric (bb-bit unsigned): s=max⁡ixi−min⁡ixi2b−1s = \dfrac{\max_i x_i - \min_i x_i}{2^b - 1},   z=round(−min⁡ixi/s)\;z = \text{round}(-\min_i x_i / s),   q=clamp(round(x/s)+z,0,2b−1)\;q = \text{clamp}(\text{round}(x/s) + z, 0, 2^b-1),   x^=s (q−z)\;\hat{x} = s\,(q - z).

Take four lopsided values x=(−0.05, 0.31, 0.62, 0.95)x = (-0.05,\ 0.31,\ 0.62,\ 0.95) and b=4b = 4.

Symmetric: s=0.95/7≈0.1357s = 0.95/7 \approx 0.1357. Codes −7-7 to −1-1 cover [−0.95,−0.14][-0.95, -0.14], where there is no data at all: nearly half the grid is wasted.

Asymmetric: s=(0.95+0.05)/15≈0.0667s = (0.95 + 0.05)/15 \approx 0.0667 and z=round(0.05/0.0667)=round(0.75)=1z = \text{round}(0.05/0.0667) = \text{round}(0.75) = 1.

xxsym qqsym x^\hat{x}sym errorasym qqasym x^\hat{x}asym error
−0.0500.000+0.0500−0.067−0.017
0.3120.271−0.03960.333+0.023
0.6250.679+0.059100.600−0.020
0.9570.9500.000150.933−0.017

Mean squared error: about 0.00190.0019 symmetric versus 0.000380.00038 asymmetric, a 5× improvement from putting all 16 codes where the data is.

Error budget. For values inside the range, rounding error is roughly uniform on [−s/2,s/2][-s/2, s/2], so its mean square is s2/12s^2/12. Each extra bit halves ss and cuts that by 4×, which is about 6 dB of SNR per bit. Try it in the demo with group-wise scales: 6 → 7 → 8 bits should add roughly 6 dB each.

In code

Group-wise symmetric quantization fits in a few lines. Real kernels pack two 4-bit codes into each byte and fuse dequantization into the matrix multiply.

import torch

def quantize_groupwise(w, bits=4, group=128):
    """w: (out, in) weights. Returns int codes and one scale per group."""
    qmax = 2 ** (bits - 1) - 1                     # 7 for INT4
    g = w.reshape(-1, group)                       # rows of `group` weights
    scale = g.abs().amax(dim=1, keepdim=True) / qmax
    q = torch.clamp(torch.round(g / scale), -qmax, qmax).to(torch.int8)
    return q, scale.half()

def dequantize(q, scale, shape):
    return (q.float() * scale.float()).reshape(shape)

w = torch.randn(4096, 4096)
q, s = quantize_groupwise(w)
err = (dequantize(q, s, w.shape) - w).pow(2).mean()
bits = 4 + 16 / 128                                # codes + one FP16 scale per group
print(f"MSE {err:.5f}, {bits} bits/weight")
COMMON MISCONCEPTIONS
  • “4-bit quantization makes a model 4× worse.” Quality loss is far from proportional to bits removed. With group-wise scales and methods like GPTQ or AWQ, 4-bit weight quantization often costs only a small perplexity increase, while saving about 75% of memory.
  • “Quantization means the GPU computes in 4-bit.” Usually not. Weight-only schemes unpack weights to 16-bit right before the multiply; the gain comes from moving fewer bytes, which is what limits decoding.
  • “Just round each weight to the nearest level.” Round-to-nearest is a reasonable baseline, but error-compensating methods like GPTQ, and activation-aware scaling like AWQ, give noticeably better models at the same bit width.
  • “A 4-bit model is exactly a quarter of the 16-bit size.” Scales, zero-points and layers kept at higher precision add overhead, typically pushing the real figure to about 4.1 to 5 bits per weight.
  • “Outliers are noise you can clip away.” In LLMs, large-magnitude activation channels carry important information. Clipping them hurts quality badly, which is why outlier-aware methods exist.

Check your understanding

0/5 answered
  1. Q1.Why does quantizing weights to 4 bits typically speed up token-by-token generation even if the arithmetic still happens in 16-bit?

  2. Q2.A weight matrix has one weight of magnitude 12, and all others are within ±3. You use symmetric INT4 with a single per-tensor scale. What happens?

  3. Q3.You quantize to 4 bits with an FP16 scale for every group of 64 weights. Ignoring other overhead, how many bits per weight do you store?

  4. Q4.What is the key idea of GPTQ?

  5. Q5.When is asymmetric quantization most helpful?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.