Quantisation: INT8, INT4, GPTQ, AWQ¶
Quantisation stores and computes a trained network with fewer bits per number: 8, 4, even fewer instead of 16. The idea to walk away with: the rounding error is noise you can measure and steer. Good methods choose which numbers get the error and how the rest of the layer compensates, so a 4-bit model behaves almost like the 16-bit one at a quarter of the bytes.
10,000 ft
LLM inference is mostly a memory problem: generating a token reads every weight once, so decode speed is bytes ÷ bandwidth. Every bit you remove from a weight is a bit you never move. Quantisation is why a 70 B model runs on a workstation, an 8 B model runs on a phone or laptop, and QLoRA fine-tunes a 65 B model on one 48 GB GPU. It sits downstream of mixed precision, which covers the floating-point formats used in training. Quantisation is mostly a post-training compression problem, though it is moving into training too: FP8 and FP4 training, and models released natively in 4-bit. It also feeds serving, where the KV cache is quantised as well, and it shares its central problem with numerical computing: what happens to a computation when every number is rounded.
2,000 ft
A quantisation scheme answers five questions:
- What to quantise: weights only (W4A16, best for memory-bound decode), weights and activations (W8A8 / FP8, uses faster integer or FP8 tensor cores), or the KV cache.
- Which format: integers (INT8, INT4) on a uniform grid, or small floats (FP8, FP4, NF4), whose levels are denser near zero.
- Granularity: one scale per tensor, per output channel, or per group of 32–128 weights. Smaller groups track the data better and cost a few extra bits per weight.
- How to round: plain round-to-nearest (RTN); GPTQ, which quantises one column at a time and corrects the remaining columns using second-order information; AWQ, which rescales the channels that see large activations before rounding; or rotations that spread outliers out.
- When: after training with a small calibration set (PTQ), or during training with the rounding simulated in the forward pass (QAT).
Ground level¶
Why fewer bits make a model faster¶
Start from the arithmetic of compute maths. Llama 3 70B has about \(70.6\times10^9\) parameters. At batch 1, an H100 decoding it must stream every weight from HBM for each token, at 3.35 TB/s:
| Weights stored as | Bits per weight | Weight bytes | Bandwidth bound (tokens/s, batch 1) |
|---|---|---|---|
| BF16 | 16 | 141 GB (does not fit in 80 GB) | 24 |
| INT8 / FP8 | 8 | 70.6 GB | 47 |
| INT4, group 128, FP16 scale + zero | 4.25 | 37.5 GB | 89 |
| INT3, group 128 | 3.25 | 28.7 GB | 117 |
Two things change at once. The model fits on fewer GPUs, so it costs less to host. And each decode step moves fewer bytes, so each user gets tokens faster. Nothing in this table touches FLOPs. Weight-only quantisation (written W4A16: 4-bit weights, 16-bit activations) dequantises weights inside the matmul kernel and still computes in BF16. It speeds up the memory-bound decode phase and does almost nothing for compute-bound prefill. To speed up prefill or large-batch serving you must also quantise activations, so the tensor cores themselves run in INT8 or FP8, which on an H100 have twice the BF16 peak. That is the W8A8 / FP8 family.
The affine map: scale and zero-point¶
Uniform quantisation maps a real number \(x\) to a \(b\)-bit integer \(q\) with a scale \(s\) (the step size) and a zero-point \(z\) (the integer that represents real 0):
\(\hat{x}\) is the dequantised value the network actually uses. Two common choices:
- Symmetric (absmax): \(z = 0\), \(s = \max|x| / (2^{b-1}-1)\). Real 0 maps exactly to integer 0. The grid is centred, so one level is wasted if the data are lopsided.
- Asymmetric (min-max): \(s = (\max x - \min x)/(2^b - 1)\), \(z = \operatorname{round}(-\min x / s)\). It uses all \(2^b\) levels across the actual range.
Worked example: quantise eight weights to 4 bits.
| \(w\) | 0.42 | −0.13 | 0.07 | −0.88 | 0.25 | 0.61 | −0.04 | 0.19 |
|---|---|---|---|---|---|---|---|---|
| symmetric \(q\) (\(s = 0.88/7 = 0.1257\)) | 3 | −1 | 1 | −7 | 2 | 5 | 0 | 2 |
| dequantised | 0.377 | −0.126 | 0.126 | −0.880 | 0.251 | 0.629 | 0 | 0.251 |
| asymmetric \(q\) (\(s = 1.49/15 = 0.0993\), \(z = 9\)) | 13 | 8 | 10 | 0 | 12 | 15 | 9 | 11 |
| dequantised | 0.397 | −0.099 | 0.099 | −0.894 | 0.298 | 0.596 | 0 | 0.199 |
The symmetric version uses only 15 of 16 levels and has RMS error 0.0365. The asymmetric version uses all 16 and has RMS error 0.0289. Both numbers are almost exactly \(s/\sqrt{12}\) (0.0363 and 0.0287), the error of a uniform rounding noise derived in the maths. Notice that −0.88 dequantised to −0.894 in the asymmetric case. Rounding the zero-point to an integer shifts the whole grid slightly. That is the price of exact zero.
How an integer matmul works. For W8A8 with symmetric scales \(s_x\) (per token) and \(s_w\) (per output channel),
The inner sum is pure INT8 × INT8 accumulated in INT32, which tensor cores do at full speed. The rescale happens once per output. Zero-points would add cross terms (\(z_x\sum_k q^w_{jk} + z_w\sum_k q^x_{ik} + \dots\)), which is why weights are usually quantised symmetrically. Activations, which are often lopsided (all-positive after a ReLU, for instance), sometimes get a zero-point.
Rounding error is noise: about 6 dB per bit¶
If values fall anywhere between grid points, rounding error is roughly uniform on \([-s/2, s/2]\), with variance \(s^2/12\). Each extra bit halves \(s\) and so halves the error's standard deviation: about 6 dB of signal-to-noise per bit. That is why 8-bit is usually near-lossless and 4-bit is not free. Going from 8 to 4 bits multiplies the noise power by \(2^{8} = 256\).
There is a second error: clipping. The scale is set by the largest value in the group, so a single outlier stretches the grid for everyone. For \(n\) Gaussian weights the expected maximum is about \(\sigma\sqrt{2\ln n}\): 2.4σ for a group of 32, 2.8σ for 128, 3.8σ for 4,096 (measured in NumPy). A per-tensor scale over millions of weights wastes most of the grid on values that almost never occur. Clipping the range below the true maximum trades a large error on a few values for a smaller step for all of them. MSE-optimal clipping is a standard refinement in the white paper by Nagel et al..
Granularity: one scale for how many numbers?¶
| Granularity | One scale per | Overhead | Use |
|---|---|---|---|
| per-tensor | whole matrix | ~0 | activations in FP8/INT8 with per-tensor calibration |
| per-channel | output row of \(W\) | ~0 | INT8 weights; standard for W8A8 |
| per-token | row of \(X\) | ~0 | dynamic activation quantisation |
| per-group | \(g\) consecutive weights in a row | \(32/g\) bits for a 16-bit scale + zero | INT4/INT3 weights; \(g = 128\) is the default |
| micro-block | 16 or 32 elements | 8 bits per block | MXFP4, NVFP4, GGUF k-quants |
With \(g = 128\) and an FP16 scale and zero-point, each weight costs \(4 + 32/128 = 4.25\) bits. The Build it experiment on a Gaussian layer measures the relative output error of INT4 round-to-nearest as 22.1% per-tensor, 15.8% per-channel and 11.8% per group of 128. Dettmers and Zettlemoyer ran more than 35,000 quantisation experiments from 19 M to 176 B parameters. They found that small block sizes and the choice of data type were the only reliable improvements, and that 4-bit is almost universally the best precision for a fixed budget of model bits (k-bit inference scaling laws). A 60 B model in 4-bit beats a 30 B model in 8-bit.
Number formats: integers, small floats, NormalFloat and microscaling¶
Trained weights are roughly bell-shaped, with most values near zero and a few in the tails. A uniform grid spends as many levels on the rare tails as on the crowded centre. Three 4-bit answers:
- INT4 / INT8: uniform. Simple, fast integer arithmetic, and the default for weight-only GPU kernels.
- FP8: two variants standardised by NVIDIA, Arm and Intel (Micikevicius et al. 2022). E4M3 (4 exponent bits, 3 mantissa bits, maximum 448) is used for weights and activations. E5M2 (maximum 57,344) has more range and less precision, for gradients. Hopper and Blackwell tensor cores run FP8 at twice the BF16 rate. FP8 W8A8 with per-tensor or per-channel scales is now a routine, near-lossless serving choice.
- NF4 (4-bit NormalFloat): introduced by QLoRA. The 16 levels are quantiles of a standard normal, rescaled to \([-1, 1]\) with an exact zero, so each level is equally likely for Gaussian weights. Values are dequantised to BF16 for compute. NF4 is a storage format, not a compute format.
- FP4 E2M1 with block scales (microscaling): an FP4 element has only the magnitudes \(\{0, 0.5, 1, 1.5, 2, 3, 4, 6\}\), so it is useless without a scale. The OCP MX formats share one 8-bit power-of-two scale (E8M0) per block of 32 elements (Rouhani et al. 2023). MXFP4 costs \(4 + 8/32 = 4.25\) bits per weight. NVIDIA's NVFP4 uses blocks of 16 with an FP8 E4M3 scale plus one FP32 scale per tensor, trading a little storage for a finer-grained scale (NVIDIA blog). Blackwell GPUs compute in these formats natively. OpenAI's gpt-oss models (August 2025) ship their MoE weights, over 90% of all parameters, in MXFP4, which is what lets the 117 B model fit on one 80 GB GPU (model card).
The outlier problem: why activations are hard¶
Weights are well-behaved. Activations are not. Dettmers et al. found that once transformers reach about 6.7 B parameters, a handful of hidden dimensions carry values up to 20× larger than the rest, in every layer and in about 75% of sequence positions. In a 13 B model, up to 150,000 outliers per 2,048-token sequence fell in at most 7 feature dimensions (LLM.int8(), §4). They matter: zeroing those dimensions cut the top-1 attention probability by more than 20% and worsened perplexity by 600–1,000%. Zeroing the same number of random dimensions cost about 0.1%.
Per-tensor INT8 then fails. One value of 60 sets the scale, and every ordinary activation near 1 rounds to one of a few levels around zero. Their C4 perplexities for a 13 B model:
| Method (13 B model) | C4 perplexity |
|---|---|
| 32-bit float | 12.45 |
| INT8 absmax (per-tensor) | 19.08 |
| INT8 vector-wise (per-row × per-column scales) | 16.48 |
| LLM.int8(): vector-wise + FP16 outlier columns | 12.45 |
LLM.int8() splits the matmul. Any input column with a value above 6.0 goes through a small FP16 matmul, and the other 99.9% of the work runs in INT8. It made 175 B models usable on one server without degradation, but the decomposition adds overhead: below 6.7 B parameters it runs slower than FP16. Later methods remove the outliers instead of routing around them:
- SmoothQuant (Xiao et al. 2022) notes that \(XW^\top = (X\operatorname{diag}(s)^{-1})(W\operatorname{diag}(s))^\top\) exactly. Dividing each input channel \(j\) by \(s_j = \max|X_j|^\alpha / \max|W_j|^{1-\alpha}\) and multiplying the matching weight column by \(s_j\) moves the difficulty from activations, which are hard to quantise, to weights, which are easy. The division folds into the preceding LayerNorm, so it costs nothing at run time. With \(\alpha = 0.5\) it gives W8A8 with negligible loss, up to 1.56× speed-up and 2× memory reduction. In Build it, on a layer with six outlier channels, it cuts the W8A8 error from 19.7% (per-tensor activations) to 1.8%.
- Rotations: multiply the hidden state by an orthogonal matrix \(R\) (and the weights by \(R^\top\)) and the output is unchanged. A random or Hadamard rotation smears an outlier evenly across all dimensions. QuaRot (Ashkboos et al. 2024) uses this to run all matmuls, plus the KV cache, in 4 bits. Llama 2 70B loses at most 0.47 WikiText-2 perplexity. SpinQuant (Liu et al. 2024) learns the rotations.
Why do outliers exist at all? Bondarenko et al. traced the strongest ones to attention heads learning to do nothing. To put near-zero attention on everything useful, a head dumps its weight on a delimiter-like token, which requires pushing softmax inputs to extremes (Quantizable Transformers). It is the same phenomenon as attention sinks. Change the attention (clipped softmax, gating) and the outliers shrink.
GPTQ: rounding decisions that know about each other¶
Round-to-nearest treats every weight independently. But the layer's output is what matters, and errors in different weights can cancel. GPTQ (Frantar et al. 2022) solves, for each linear layer with calibration inputs \(X\):
(Here \(X\) is \(d_{in}\times n\), with one column per calibration token.) The loss is a quadratic in each row of \(W\) with the same Hessian \(H = 2XX^\top\) for every row. GPTQ comes from the Optimal Brain Surgeon line of work. Quantise one weight \(w_q\), and the best change to the not-yet-quantised weights \(F\) that keeps the output closest is
The error from rounding one weight is pushed onto the weights that remain, in the directions where the inputs are correlated. Its predecessor OBQ did this greedily, weight by weight, at a cost of \(O(d_{row} d_{col}^3)\), which is hopeless for a 12,288-wide layer. GPTQ added three ideas:
- Same column order for every row. Quantise column 1 of all rows, then column 2, and so on. Order turns out to matter little for large layers. Since \(H\) depends only on \(X\), the inverse-Hessian updates are shared across rows, and cost drops to \(O(\max(d_{row}d_{col}^2, d_{col}^3))\).
- Lazy batches. Updates to column \(i\) only affect later columns, so process 128 columns at a time inside a block and apply the accumulated update to the rest of the matrix once. This turns memory-bound rank-1 updates into compute-bound matmuls.
- Cholesky. Every row of \(H^{-1}\) that the algorithm needs is a row of the Cholesky factor of \(H^{-1}\), computed once. Add dampening of 1% of the mean diagonal, and the method is numerically stable at 175 B scale.
The calibration set is tiny: 128 random 2,048-token segments of C4. Because each Transformer block is quantised in turn on the outputs of the already-quantised blocks before it, a single A100 suffices. Results from the paper (WikiText-2 perplexity, lower is better):
| Model | FP16 | 4-bit RTN | 4-bit GPTQ | 3-bit RTN | 3-bit GPTQ | 3-bit GPTQ, g128 |
|---|---|---|---|---|---|---|
| OPT-175B | 8.34 | 10.54 | 8.37 | 7,300 | 8.68 | 8.45 |
| BLOOM-176B | 8.11 | 8.37 | 8.21 | 571 | 8.64 | 8.26 |
| OPT-1.3B | 14.62 | 48.17 | 15.47 | 13,000 | 20.97 | — |
Runtime: 4.2 GPU-hours for OPT-175B on one A100. At 3 bits, OPT-175B takes about 63 GB and runs on one 80 GB A100 at 71 ms per token, against 230 ms in FP16 on five, a 3.24× speed-up that comes entirely from moving fewer bytes. Two patterns recur across the quantisation literature: RTN collapses at 3 bits while error-compensating methods do not, and larger models are easier to quantise (OPT-1.3B loses 0.85 perplexity at 4-bit GPTQ, OPT-175B loses 0.03).
AWQ: protect the weights that see large activations¶
AWQ (Lin et al. 2023, MLSys 2024 best paper) starts from an experiment. Quantise OPT-6.7B to INT3 (g128) with RTN: perplexity goes from 10.86 to 23.54. Now keep just 1% of input channels in FP16:
| Channels kept in FP16 (1%) chosen by | WikiText-2 perplexity |
|---|---|
| none (RTN) | 23.54 |
| random | 24.23 |
| largest weight norm | 22.37 |
| largest average activation magnitude | 11.39 |
Which weights matter is decided by the activations: a weight multiplied by a large input contributes a large output error when rounded. Mixed precision is awkward for kernels, so AWQ protects salient channels by scaling them. For a weight \(w\) with input \(x\), quantise \(ws\) and feed \(x/s\):
The rounding error is still about half a step, but it is now divided by \(s\). If scaling one channel barely changes the group maximum (\(\Delta' \approx \Delta\)), the error on that channel shrinks by \(1/s\). Push \(s\) too high and \(\Delta'\) grows for the rest of the group, so there is a sweet spot. For OPT-6.7B, \(s = 2\) gives 11.92. AWQ picks a per-channel scale \(s = \bar{s}_X^{\,\alpha}\), where \(\bar{s}_X\) is the mean activation magnitude, by grid search over \(\alpha \in [0, 1]\) to minimise the layer's output error. There is no backpropagation and no regression, so it overfits the calibration set less than GPTQ and generalises better to instruction-tuned and multimodal models.
AWQ's results on Llama 2 (WikiText-2 perplexity, group size 128):
| 7B | 13B | 70B | |
|---|---|---|---|
| FP16 | 5.47 | 4.88 | 3.32 |
| INT4 RTN | 5.73 | 4.98 | 3.46 |
| INT4 GPTQ | 5.69 | 4.98 | 3.42 |
| INT4 GPTQ with reordering | 5.63 | 4.99 | 3.43 |
| INT4 AWQ | 5.60 | 4.97 | 3.41 |
| INT3 RTN | 6.66 | 5.52 | 3.98 |
| INT3 AWQ | 6.24 | 5.32 | 3.74 |
The paper's roofline analysis on an RTX 4090 (165 TFLOP/s, about 1 TB/s, so a ridge near 165) explains why the method is weight-only. Decode has arithmetic intensity about 1 in FP16, and 4-bit weights raise it to about 4, a 4× higher ceiling. Their TinyChat kernels achieve more than 3× over the Hugging Face FP16 implementation.
Quantising the KV cache¶
At long context the KV cache outgrows the weights. FP8 KV caches halve it at little cost and are a standard serving option. Going lower needs care, because keys and values have different shapes of difficulty. KIVI (Liu et al. 2024) found that keys have fixed outlier channels and so should be quantised per-channel, while values should be quantised per-token. At 2 bits that gave 2.6× less peak memory, up to 4× larger batches and 2.35–3.47× throughput. The serving page shows how the freed memory turns into concurrency.
Training for low precision: QAT, QLoRA and native low-bit models¶
Quantisation-aware training (QAT) inserts "fake quantisation" (quantise, then immediately dequantise) into the forward pass, so the network learns weights that survive rounding. Rounding has zero gradient almost everywhere, so the backward pass uses the straight-through estimator and pretends rounding is the identity. QAT recovers most of the 4-bit and lower gap but needs training compute and data. LLM-QAT (Liu et al. 2023) uses text the model generates itself, so no original training data is needed.
QLoRA (Dettmers et al. 2023) runs the other way round. It freezes the base model in NF4 and trains 16-bit LoRA adapters on top, with gradients flowing through the dequantised weights. Double quantisation quantises the per-block scales as well: with 64-weight blocks, a 32-bit scale costs 0.5 bits per weight, and 8-bit scales with their own second-level constants cost 0.127, saving about 0.37 bits per parameter. The result: a 65 B model fine-tunes on a single 48 GB GPU with no loss against 16-bit fine-tuning.
Some models are now born low-precision. BitNet b1.58 (Ma et al. 2024) trains ternary weights \(\{-1, 0, 1\}\) from scratch and matches an FP16 model of the same size and data in its experiments. gpt-oss was post-trained with its MoE weights in MXFP4. There is a catch, measured by Kumar et al. (2024) in their Scaling Laws for Precision: the damage from post-training quantisation grows with the amount of pre-training data. Heavily over-trained small models pack more information into each weight and have less slack to give up. This is a reason to evaluate 4-bit versions of recent small models carefully rather than trust older rules of thumb.
How much quality do you lose?¶
Rules of thumb as of 2026. Each is a starting hypothesis to measure, not a guarantee:
- 8-bit weights, or FP8 / SmoothQuant W8A8: near-lossless for most LLMs.
- 4-bit weight-only with groups of 128 and GPTQ or AWQ: a small perplexity increase (Llama 2 7B: 5.47 → 5.60 with AWQ), shrinking with model size. This is the default for local inference and for single-user GPU serving.
- 3-bit: a visible loss with good methods and collapse with plain RTN.
- 2-bit: needs vector or lattice codebooks (QuIP#, AQLM) or QAT.
- Perplexity understates damage on long-context retrieval, maths, code and low-resource languages. Always evaluate the quantised model on your own task. That is the theme of evals in practice.
First principles¶
Why rounding a trained network works at all. A trained network sits in a broad, flat region of the loss surface. SGD found it amid gradient noise, and flat minima are widely associated with good generalisation. A small random perturbation of every weight moves the loss by roughly \(\tfrac12\delta^\top H_{\mathcal{L}}\,\delta\). In flat directions that is tiny. Quantisation noise is exactly such a perturbation, with a known variance \(s^2/12\) per weight. It fails when the perturbation is not small relative to what a weight carries (too few bits, or one scale stretched by an outlier) or when it lands in sharp directions. GPTQ attacks the second with \(H\).
Why weights are easy and activations are hard. Weights are fixed, so you can inspect every one of them offline and choose scales per channel or per group. Activations are created at run time, differ for every token, and a per-group scale for them would have to be computed on the fly inside the matmul. Activations also carry the systematic outlier channels. Weight-only methods dodge the problem; W8A8 methods either measure it (per-token scales), move it (SmoothQuant) or dissolve it (rotations).
Why smaller groups help, and why they stop helping. The step is set by the maximum of the group, and the expected maximum of \(n\) Gaussians grows as \(\sqrt{2\ln n}\). Going from per-row (4,096) to 128 cuts the step by about 25% at a cost of 0.25 bits per weight. Going from 128 to 32 cuts it by another 17% for another 0.75 bits with a 16-bit scale and zero, which is why small blocks use 8-bit scales (MX, GGUF). There is a fixed budget of bits, and a smaller step for the elements competes with the bits spent on scales.
Why error compensation beats independent rounding. Rounding each weight to its nearest grid point minimises \(\lVert w - \hat{w}\rVert^2\), the wrong objective. The right one is \((w - \hat{w})^\top H (w - \hat{w})\), the output error. When inputs are correlated, \(H\) has large off-diagonal terms, and an error in one weight can be cancelled by a deliberate error in its correlated neighbours. Real hidden states are highly correlated (low effective rank), so the gain is large. On uncorrelated inputs, GPTQ reduces to RTN.
Why 4 bits is the sweet spot for a fixed memory budget. Going from 16 to 8 bits frees half the memory at almost no loss: spend it on a model twice as large. Going from 8 to 4 does the same at a small loss, still worth it. At 3 bits the loss per halving overtakes the gain from a larger model. This is the empirical finding of the k-bit scaling-law paper, and it rests on the 6-dB-per-bit noise law meeting a loss curve that improves only as a power of model size.
The maths¶
Notation. \(b\) = bits; \(s\) = scale (step); \(z\) = zero-point; \(Q(x) = s(\operatorname{clip}(\operatorname{round}(x/s)+z) - z)\); \(W \in \mathbb{R}^{d_{out}\times d_{in}}\) with rows \(\mathbf{w}^\top\); calibration inputs \(X \in \mathbb{R}^{d_{in}\times n}\).
Derivation: uniform quantisation noise has variance s²/12, about 6 dB per bit
Assume \(x\) is spread over many steps, so its position within a step is uniform. Then the error \(e = Q(x) - x\) is uniform on \([-s/2, s/2]\):
For a symmetric \(b\)-bit grid covering \([-R, R]\), \(s = 2R/(2^b - 1) \approx 2R\cdot2^{-b}\). The signal-to-quantisation-noise ratio for a signal of variance \(\sigma^2\) is
Each bit adds 6.02 dB. The second term is the clipping trade-off: a larger range \(R\) relative to \(\sigma\) (to avoid clipping outliers) costs SQNR at every bit width. With Gaussian data and \(R = \max|x| \approx \sigma\sqrt{2\ln n}\), the penalty grows with group size \(n\). That is the formal case for small groups.
Output error of a quantised layer. With \(\Delta W = \hat{W} - W\) and independent rounding errors of variance \(s_j^2/12\) in input channel \(j\),
The error in channel \(j\) is weighted by \(x_j^2\). This one line is AWQ's insight: channels with large activations dominate the output error, so their weights deserve the smallest effective step. It is also SmoothQuant's: if a few \(x_j\) are huge, per-tensor scales on \(X\) are hopeless.
Derivation: the GPTQ / Optimal Brain Surgeon update
For one row \(\mathbf{w}\) the layer-wise loss is \(E(\mathbf{w}+\boldsymbol\delta) - E(\mathbf{w}) = \boldsymbol\delta^\top X X^\top \boldsymbol\delta = \tfrac12\boldsymbol\delta^\top H\boldsymbol\delta\) with \(H = 2XX^\top\). It is exactly quadratic, because the layer is linear. We must move weight \(q\) onto the grid: \(\mathbf{e}_q^\top\boldsymbol\delta = \operatorname{quant}(w_q) - w_q\). Minimise with a Lagrange multiplier:
Setting \(\nabla_{\boldsymbol\delta} = 0\) gives \(\boldsymbol\delta = -\lambda H^{-1}\mathbf{e}_q\). The constraint gives \(\lambda = -(\operatorname{quant}(w_q) - w_q)/[H^{-1}]_{qq}\). So
After weight \(q\) is fixed, it is removed from the problem. The inverse Hessian of the remaining weights is obtained by one step of Gaussian elimination: \(H^{-1}_{-q} = H^{-1} - \frac{1}{[H^{-1}]_{qq}}H^{-1}_{:,q}H^{-1}_{q,:}\). If columns are processed in the fixed order \(1, 2, \dots, d_{in}\), the rows of \(H^{-1}\) needed at each step, restricted to the remaining columns, are exactly the rows of the upper Cholesky factor \(U\) of \(H^{-1}\) (\(H^{-1} = U^\top U\)), up to a factor \(1/U_{qq}\). Hence the update in Algorithm 1 of the paper: \(e = (w_q - \operatorname{quant}(w_q))/U_{qq}\), then \(\mathbf{w}_{q:} \mathrel{-}= e\,U_{q,q:}\).
Derivation: SmoothQuant's migration strength
\(Y = XW^\top = (X\operatorname{diag}(\mathbf{s})^{-1})(W\operatorname{diag}(\mathbf{s}))^\top\) for any positive \(\mathbf{s}\). After scaling, input channel \(j\) has range \(\max|X_j|/s_j\) and weight column \(j\) has range \(s_j\max|W_j|\). Equalising the two, \(\max|X_j|/s_j = s_j\max|W_j|\), gives \(s_j = \sqrt{\max|X_j|/\max|W_j|}\), which is \(\alpha = 0.5\). General \(\alpha\) interpolates: \(s_j = \max|X_j|^\alpha/\max|W_j|^{1-\alpha}\). Larger \(\alpha\) pushes more of the difficulty into the weights, which helps when activation outliers are extreme, and the paper tunes it per model family.
Bits per weight with block scales. For elements of \(b\) bits in blocks of \(g\), with a scale of \(b_s\) bits and an optional zero-point of \(b_z\) bits:
INT4 g128 with FP16 scale and zero: \(4 + 32/128 = 4.25\). MXFP4: \(4 + 8/32 = 4.25\). NVFP4: \(4 + 8/16 = 4.5\) (plus a negligible per-tensor FP32). NF4 with double quantisation: \(4 + 8/64 + 32/(64\cdot256) \approx 4.127\).
Build it¶
Two NumPy experiments. The first shows granularity, outliers and SmoothQuant on one synthetic layer whose inputs have six outlier channels.
import numpy as np
rng = np.random.default_rng(0)
def quant(x, bits, axis=None, group=None, sym=True):
"""Fake-quantise x (quantise then dequantise). axis: reduce over it for one scale per slice."""
shp = x.shape
if group: # groups of `group` consecutive input weights
x = x.reshape(shp[0], -1, group); axis = -1
if sym:
qmax = 2 ** (bits - 1) - 1
s = np.abs(x).max(axis=axis, keepdims=True) / qmax
q = np.clip(np.round(x / s), -qmax - 1, qmax)
y = q * s
else:
lo, hi = x.min(axis=axis, keepdims=True), x.max(axis=axis, keepdims=True)
s = (hi - lo) / (2 ** bits - 1); z = np.round(-lo / s)
q = np.clip(np.round(x / s) + z, 0, 2 ** bits - 1)
y = (q - z) * s
return y.reshape(shp)
d_in, d_out, T = 4096, 1024, 256
W = rng.normal(0, 0.02, (d_out, d_in)) # one row per output channel
X = rng.normal(0, 1.0, (T, d_in))
X[:, rng.choice(d_in, 6, replace=False)] *= 60 # six outlier feature dims (cf. LLM.int8)
Y = X @ W.T
err = lambda Yq: np.linalg.norm(Yq - Y) / np.linalg.norm(Y)
print("weight-only (activations kept in 16-bit):")
for bits in (8, 4, 3):
r = {"tensor": quant(W, bits), "channel": quant(W, bits, axis=1),
"g128": quant(W, bits, group=128), "g128 asym": quant(W, bits, group=128, sym=False)}
print(f" INT{bits}: " + " ".join(f"{k} {100*err(X @ v.T):5.2f}%" for k, v in r.items()))
print("W8A8 (activations quantised too):")
Wq = quant(W, 8, axis=1)
print(f" per-tensor A8 {100*err(quant(X, 8) @ Wq.T):6.2f}%")
print(f" per-token A8 {100*err(quant(X, 8, axis=1) @ Wq.T):6.2f}%")
for a in (0.5, 0.75): # SmoothQuant: s_j = max|X_j|^a / max|W_j|^(1-a)
s = np.abs(X).max(0) ** a / np.abs(W).max(0) ** (1 - a)
Xs, Ws = X / s, W * s # X W^T unchanged mathematically
print(f" SmoothQuant a={a} {100*err(quant(Xs, 8, axis=1) @ quant(Ws, 8, axis=1).T):6.2f}%")
weight-only (activations kept in 16-bit):
INT8: tensor 1.22% channel 0.87% g128 0.65% g128 asym 0.60%
INT4: tensor 22.09% channel 15.78% g128 11.77% g128 asym 10.10%
INT3: tensor 52.05% channel 37.18% g128 27.24% g128 asym 21.64%
W8A8 (activations quantised too):
per-tensor A8 19.68%
per-token A8 9.52%
SmoothQuant a=0.5 1.81%
SmoothQuant a=0.75 3.64%
The second is a 30-line GPTQ next to RTN and an AWQ-style scale search. Its inputs are correlated, with a decaying spectrum like real hidden states, and have uneven channel magnitudes. Errors are measured on held-out tokens.
import numpy as np
rng = np.random.default_rng(1)
d_in, d_out = 512, 256
basis, _ = np.linalg.qr(rng.normal(size=(d_in, d_in)))
mix = basis * (10 / np.arange(1, d_in + 1) ** 0.5) @ basis.T # decaying spectrum, like real hidden states
loud = np.exp(rng.normal(0, 0.8, d_in)) # uneven channel magnitudes
tokens = lambda n: (rng.normal(size=(n, d_in)) @ mix) * loud
X, X_test = tokens(2048), tokens(2048) # calibration set, held-out set
W = rng.normal(0, 0.02, (d_out, d_in))
def rtn(w, s, z, bits): # round-to-nearest on a fixed asymmetric grid
return (np.clip(np.round(w / s) + z, 0, 2**bits - 1) - z) * s
def make_grid(W, bits, group=None): # scale s and zero-point z per row (or group)
Wg = W.reshape(W.shape[0], -1, group or W.shape[1])
lo, hi = Wg.min(-1, keepdims=True), Wg.max(-1, keepdims=True)
s = (hi - lo) / (2**bits - 1)
return s, np.round(-lo / s), Wg.shape
def rtn_matrix(W, bits, group=None):
s, z, shp = make_grid(W, bits, group)
return rtn(W.reshape(shp), s, z, bits).reshape(W.shape)
def gptq(W, X, bits, damp=0.01):
s, z, _ = make_grid(W, bits); s, z = s[:, 0, 0], z[:, 0, 0]
W, Q = W.copy(), np.zeros_like(W)
H = 2 * X.T @ X
H += damp * np.mean(np.diag(H)) * np.eye(d_in) # 1% dampening, as in the paper
U = np.linalg.cholesky(np.linalg.inv(H)).T # upper factor: H^-1 = U^T U
for i in range(d_in): # one column at a time
Q[:, i] = rtn(W[:, i], s, z, bits)
e = (W[:, i] - Q[:, i]) / U[i, i]
W[:, i:] -= np.outer(e, U[i, i:]) # spread the error over later columns
return Q
def awq(W, X, bits, group=128): # scale salient input channels, then RTN
best = None
for alpha in np.linspace(0, 1, 21): # alpha = 0 is plain RTN
sc = np.abs(X).mean(0) ** alpha; sc /= np.sqrt(sc.max() * sc.min())
Wq = rtn_matrix(W * sc, bits, group) / sc
e = np.linalg.norm(X @ (Wq - W).T)
if best is None or e < best[0]: best = (e, Wq, alpha)
return best[1], best[2]
rel = lambda Wq, X: np.linalg.norm(X @ (Wq - W).T) / np.linalg.norm(X @ W.T)
for bits in (4, 3):
a, alpha = awq(W, X, bits)
res = {"RTN row": rtn_matrix(W, bits), "GPTQ row": gptq(W, X, bits),
"RTN g128": rtn_matrix(W, bits, 128), f"AWQ g128 (a={alpha:.2f})": a}
print(f"INT{bits} " + " ".join(f"{k} {100*rel(v, X_test):5.2f}%" for k, v in res.items()))
INT4 RTN row 11.85% GPTQ row 7.88% RTN g128 9.97% AWQ g128 (a=0.20) 8.93%
INT3 RTN row 25.00% GPTQ row 16.87% RTN g128 21.41% AWQ g128 (a=0.30) 18.86%
GPTQ, with a single scale per row, beats RTN with 32 scales per row (g128), because it exploits the correlation between inputs. AWQ beats plain g128 RTN by using the uneven channel magnitudes. The two exploit different structure, which is why production tools often combine them with grouping.
Things to try
- In the first script, remove the outlier line. How much do per-tensor activations improve, and does SmoothQuant still help?
- In the second, replace
mixwith the identity (uncorrelated inputs). Predict GPTQ's advantage over RTN before you run it, then explain the result using \(H\). - Add grouping to
gptq(recomputes, zfor each group of 128 columns from the updated weights as the loop reaches it). Does GPTQ + g128 beat both? - Implement NF4: divide each block of 64 by its absmax and round to the nearest of the 16 levels −1, −0.6962, −0.5251, −0.3949, −0.2844, −0.1848, −0.0910, 0, 0.0796, 0.1609, 0.2461, 0.3379, 0.4407, 0.5626, 0.7230, 1. Compare with INT4 g64 on Gaussian and on Laplace-distributed weights.
- Quantise
X_testwith a different distribution (e.g.loudshuffled) and watch AWQ's advantage shrink. That is calibration mismatch.
In practice¶
| Situation (as of 2026) | Usual choice | Tools |
|---|---|---|
| GPU serving, many concurrent users, Hopper/Blackwell | FP8 W8A8 (or NVFP4 on Blackwell), FP8 KV cache | vLLM, TensorRT-LLM, SGLang; llm-compressor to produce checkpoints |
| GPU serving, low batch, memory-limited | W4A16 with GPTQ or AWQ, g128 | llm-compressor, GPTQModel (successor to AutoGPTQ) |
| Laptop / desktop / phone | 4–5-bit block formats | GGUF k-quants in llama.cpp, MLX 4-bit; see on-device AI |
| Fine-tuning on one GPU | NF4 base + LoRA (QLoRA) | bitsandbytes, PEFT |
| Need below 4 bits | QAT, or codebook methods (QuIP#, AQLM) | torchao QAT |
- Calibration data should look like your traffic. 128–512 samples of a few thousand tokens is typical. Calibrating a chat model on raw web text can hurt instruction following, and calibrating on one domain can overfit to it (AWQ is less sensitive than GPTQ).
- Leave the sensitive parts in higher precision. The embedding and the output projection
(
lm_head) are usually left in 16-bit, as are norms, router weights in MoE layers and often sometimes the first and last blocks. They are small and disproportionately sensitive. - Kernels decide the speed. A 4-bit format with no fused kernel for your GPU is slower than BF16. Check that the serving engine has a kernel for the exact format, group size and hardware.
- AutoAWQ is deprecated. Its maintainer stopped development and the functionality moved into
llm-compressor. Older guides still say
pip install autoawq. - Measure what users feel. Report perplexity and task metrics, and look at long-context retrieval, tool-call formatting and maths, which tend to degrade first.
Common misconceptions¶
\"4-bit weights make the model 4× faster.\"
Only the memory-bound part, and only up to the bandwidth bound. Prefill is compute-bound and W4A16 does not speed it up; dequantisation adds instructions; at large batch the KV cache, not the weights, dominates bytes moved. Expect 2–3.5× on decode at small batch, less elsewhere.
\"Same perplexity means same model.\"
Perplexity averages over easy tokens. Quantisation errors concentrate in rare, high-information tokens: numbers, code, names, long-range retrievals. Two models within 0.1 perplexity can differ visibly on a maths benchmark.
\"Quantisation is a fixed recipe I can apply to any model.\"
Outlier structure differs by architecture and training run. Heavily over-trained small models degrade more than older ones of the same size (Kumar et al. 2024). Re-evaluate every new model.
\"Quantising the KV cache is the same problem as quantising weights.\"
Keys have persistent outlier channels and values do not. KIVI quantises keys per-channel and values per-token. Applying a per-token scheme to keys is a common source of long-context degradation.
Check yourself¶
A 32 B model runs in BF16 on an H100 (3.35 TB/s). Estimate batch-1 decode speed in BF16 and with INT4 g128 weights.
BF16: 64 GB of weights, 3.35e12 / 64e9 ≈ 52 tokens/s upper bound. INT4 g128 at 4.25 bits per weight: 32e9 × 4.25 / 8 = 17 GB, so about 197 tokens/s upper bound, 3.8× faster. Real kernels get perhaps 60–80% of the bound, and the KV cache adds bytes at long context.
Why does the symmetric INT4 quantisation of the eight-weight example use only 15 levels, and when is asymmetric quantisation worth its cost?
With \(z = 0\) and \(s = \max|x|/7\), integers run from −7 to 7; −8 is never produced. Asymmetric quantisation uses all 16 levels across \([\min, \max]\) and pays off when the data are lopsided (post-ReLU activations, or a small group whose values happen to be mostly positive). For weights the gain is modest, and the zero-point adds cross terms to integer matmuls.
In LLM.int8(), why are the outliers handled by columns of X (feature dimensions) rather than rows (tokens)?
The outliers are systematic. They appear in the same few hidden dimensions across almost all tokens and layers, so they occupy whole columns of the activation matrix. Per-token (row) scales cannot help, because every row contains the outlier. Pulling out those few columns and the matching rows of \(W\) into an FP16 matmul isolates them cheaply (≤7 of thousands of dimensions).
Show that SmoothQuant does not change the layer's output in exact arithmetic, and say where the division by s is paid for at run time.
\((X\operatorname{diag}(s)^{-1})(W\operatorname{diag}(s))^\top = X\operatorname{diag}(s)^{-1}\operatorname{diag}(s)W^\top = XW^\top\). The weight-side multiply is done once offline. The activation-side division folds into the preceding operation: LayerNorm/RMSNorm has a per-channel gain \(\gamma\), replaced by \(\gamma/s\). So it is free at run time.
GPTQ quantises columns in a fixed order and pushes each column's rounding error onto later columns. What happens to the last column, and why is that acceptable?
The last column has nobody left to absorb its error. It is plain RTN. The paper's observation is that for large layers the order matters little: early errors are compensated with many degrees of freedom, and the final few columns are a small fraction of thousands. (GPTQ with "act-order" processes columns in order of decreasing \(H_{jj}\), so the most important columns are quantised first while compensation capacity is greatest.)
Why does AWQ's scaling trick help a salient channel, but hurt if s is pushed too far?
Scaling \(w\) by \(s\) and \(x\) by \(1/s\) divides the rounding error on that product by \(s\), as long as the group's step \(\Delta\) is unchanged. Once \(ws\) becomes the group's maximum, \(\Delta\) grows in proportion, and every other weight in the group gets a coarser grid. In the paper, \(s = 4\) increased \(\Delta\) for 21% of groups and perplexity rose again from 11.92 (at \(s=2\)) to 12.36.
Hard: a 70 B model must fit in 48 GB including an 8 GB KV-cache budget. Which formats are possible, and which would you try first?
40 GB for 70.6 B weights is 4.5 bits per weight at most. INT4 g128 (4.25 bpw, 37.5 GB), MXFP4 (4.25) and NF4 with double quantisation (~4.13) fit; NVFP4 (4.5, 39.7 GB) only just fits with no room for runtime buffers. Try AWQ or GPTQ INT4 g128 first, since kernels are mature. Keep embeddings and lm_head in higher precision only if the budget allows (each is about 2.1 GB in BF16 for a 128 k vocabulary at d = 8,192). Quantise the KV cache to FP8 to double concurrency within the 8 GB.
Hard: why might post-training quantisation hurt a 1 B model trained on 15 T tokens more than one trained on 100 B tokens?
More pre-training data packs more information into each parameter, so the weights' precise values matter more and there is less redundancy to absorb noise. Kumar et al.'s Scaling Laws for Precision model this as quantisation reducing an effective parameter count, with a penalty that grows with tokens per parameter, to the point where extra pre-training can make the quantised model worse.
Go deeper¶
Papers
- A White Paper on Neural Network Quantization — Nagel et al., 2021. The best single introduction to the fundamentals: affine quantisation, range setting, PTQ vs QAT.
- LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale — Dettmers et al., 2022. §4 on emergent outlier features is essential reading.
- GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers — Frantar et al., 2022. §3–4 for the OBS update and the three engineering ideas; Algorithm 1 is 12 lines.
- Optimal Brain Compression — Frantar and Alistarh, 2022. OBQ, GPTQ's slower and more exact parent.
- AWQ: Activation-aware Weight Quantization — Lin et al., 2023. Tables 1–2 are the cleanest experiment in the field; §4 explains on-device kernels.
- SmoothQuant — Xiao et al., 2022. The equivalent-transformation idea behind most W8A8 work.
- QLoRA: Efficient Finetuning of Quantized LLMs — Dettmers et al., 2023. NF4, double quantisation, paged optimisers.
- The case for 4-bit precision: k-bit Inference Scaling Laws — Dettmers and Zettlemoyer, 2022. Why 4 bits for a fixed memory budget.
- QuaRot: Outlier-Free 4-Bit Inference in Rotated LLMs — Ashkboos et al., 2024. Rotations as a general cure for outliers.
- Microscaling Data Formats for Deep Learning — Rouhani et al., 2023. The MX block formats that hardware now implements.
- Scaling Laws for Precision — Kumar et al., 2024. Why over-trained models quantise worse.
- KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache — Liu et al., 2024. Keys per-channel, values per-token.
Videos and lectures
- Quantization explained with PyTorch — Umar Jamil. Affine quantisation, calibration and QAT, coded live.
- MIT 6.5940 TinyML and Efficient Deep Learning Computing — Song Han. Two quantisation lectures plus LLM-specific ones, from the AWQ/SmoothQuant lab.
Articles and blog posts
- A Visual Guide to Quantization — Maarten Grootendorst. Dozens of diagrams covering everything on this page; ideal for a second pass.
- LLM.int8() and Emergent Features — Tim Dettmers, 2022. The author's own account of the outlier phase shift.
- Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA — Hugging Face, 2023. NF4 and QLoRA in practice.
- Introducing NVFP4 — NVIDIA. Two-level FP4 scaling on Blackwell.
Code
- IST-DASLab/gptq — The reference implementation;
gptq.pyis short enough to read in one sitting. - mit-han-lab/llm-awq — AWQ and TinyChat.
- vllm-project/llm-compressor — Production GPTQ, AWQ, SmoothQuant and FP8 recipes for vLLM.
Where this leads¶
- Serving LLMs: how quantised weights and KV caches become more concurrent users per GPU.
- On-device AI: GGUF k-quants and MLX, quantisation formats designed for CPUs and Apple Silicon.
- Parameter-efficient fine-tuning: QLoRA, the bridge from quantised inference to cheap fine-tuning.
- Mixed precision: the floating-point formats used in training, and FP8 training.
- Kernels: CUDA and Triton: how a fused dequantise-and-multiply kernel is written.