AS·165
Quantization
Making models smaller and faster by using fewer bits, and knowing what it costs: how floating-point formats work (sign, exponent, mantissa) for FP32, FP16, BF16 and FP8 (E4M3, E5M2) with range and precision compared, integer quantisation from first principles (scale, zero point, symmetric and asymmetric, per-tensor, per-channel and group-wise) implemented and measured, INT8 and INT4, outliers and why LLMs are hard to quantise, weight-only vs weight-and-activation quantisation, post-training methods (round-to-nearest, LLM.int8, SmoothQuant, GPTQ's error-compensating rounding, AWQ's activation-aware scaling), NF4 and 4-bit formats including MXFP4/NVFP4, quantisation-aware training, KV-cache quantisation, GGUF and llama.cpp's k-quants, the memory ↔ speed ↔ quality triangle with worked memory arithmetic, and how to evaluate a quantised model.
Start here: storing weights in fewer bits
A model's weights are usually stored as 16-bit numbers. A 7-billion-parameter model therefore needs 14 GB just for its weights, more than many GPUs and laptops have. Quantization stores each weight in fewer bits, 8 or 4, so the same model needs about 7 GB or 3.5 GB, loads faster, and often runs faster, because generating text is mostly limited by how fast weights can be read from memory.
How it works, with four numbers
Take four weights and store them as 8-bit integers (−127 to 127). Pick a scale so the largest weight maps to 127:
weights 0.12 -0.50 0.33 0.02
scale = 0.50 / 127 = 0.003937
stored integers 30 -127 84 5
read back 0.1181 -0.5000 0.3307 0.0197 largest error 0.0019
Each weight is now one byte plus a shared scale. The error is small because the scale suits these numbers.
Why outliers are the enemy
Add one unusually large weight, 8.0, to the same group:
weights 0.12 -0.50 0.33 0.02 8.0
scale = 8.0 / 127 = 0.063
stored integers 2 -8 5 0 127
read back 0.126 -0.504 0.315 0.000 8.0
The single outlier stretched the scale, so the small weights now have only a few levels to use and 0.02 became 0. Real models contain such outliers. The fixes all amount to smaller groups with their own scales (per channel, or per group of 32–128 weights), or treating outliers specially, and the lab measures exactly how much each choice matters.
How deep to go in quantization
Volume 17 defines six mastery levels; for quantization they look like this:
| Level | You can… |
|---|---|
| L1 | explain bits, scales and the memory arithmetic |
| L2 | run a quantised model (GGUF, AWQ, GPTQ, bitsandbytes) and compare its outputs |
| L3 | explain per-tensor, per-channel and group scales, outliers, and weight-only vs weight-and-activation schemes |
| L4 | diagnose quality loss by task, layer or format and choose a better scheme |
| L5 | choose precision, method and hardware for a serving budget with a measured quality bar |
| L6 | run a quantisation pipeline across model releases with automated evaluation gates |
Why quantise
A model's weights are numbers; storing each in fewer bits shrinks memory and speeds up inference:
- Memory: an 8B-parameter model needs 32 GB in FP32, 16 GB in BF16, 8 GB in INT8, about 4.5–5 GB in 4-bit. That decides whether it fits on a phone, a laptop, a single consumer GPU, or needs a server.
- Speed: LLM decoding is memory-bandwidth-bound (chapter 156): each token reads all weights once. Half the bytes ≈ up to twice the tokens per second. Integer and low-precision tensor cores also raise compute throughput.
- Cost: fewer or cheaper GPUs per model; more concurrent users per GPU (room for KV cache).
The roadmap's triangle: memory ↔ speed ↔ quality. Fewer bits save memory and usually increase speed but lose some quality; good methods make the loss small.
Floating-point formats
A floating-point number is (−1)^sign × 1.mantissa × 2^(exponent − bias). Exponent bits set the range; mantissa bits set the precision.
| Format | Bits (sign/exp/mantissa) | Max value | Precision (≈ decimal digits) | Use |
|---|---|---|---|---|
| FP32 | 1 / 8 / 23 | ≈ 3.4 × 10³⁸ | ≈ 7 | Master weights, optimiser state, reductions |
| FP16 | 1 / 5 / 10 | 65,504 | ≈ 3.3 | Inference; training needs loss scaling (small range) |
| BF16 | 1 / 8 / 7 | ≈ 3.4 × 10³⁸ | ≈ 2.4 | Training and inference default on modern accelerators: FP32's range, less precision |
| FP8 E4M3 | 1 / 4 / 3 | 448 | ≈ 1.2 | Weights and activations (forward pass) on Hopper/Blackwell-class GPUs |
| FP8 E5M2 | 1 / 5 / 2 | 57,344 | ≈ 0.9 | Gradients (need range more than precision) |
| FP4 (E2M1) in MXFP4 / NVFP4 | 1 / 2 / 1 + shared block scale | 6 (per element, before scale) | very low | 4-bit weights/activations with per-block scales on newest hardware |
import numpy as np, torch
for dt in (torch.float32, torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2):
fi = torch.finfo(dt)
print(f"{str(dt):22} max={float(fi.max):.4g} eps={float(fi.eps):.3g}")
# float16 max 65504, eps 0.000977 · bfloat16 max 3.39e38, eps 0.0078 · e4m3fn max 448 · e5m2 max 57344
x = torch.tensor([1.0001, 300.0, 70000.0])
x.to(torch.float16), x.to(torch.bfloat16) # fp16: 70000 → inf (overflow) · bf16: 70000 → 70144 (coarse) · both: 1.0001 → 1.0
Integer quantisation from first principles
Map real values in a range [min, max] onto 2^b integer levels:
q = clamp(round(x / s) + z, q_min, q_max), x̂ = s · (q − z)
- Scale s: the real-valued step between levels.
- Zero point z: the integer that represents real 0.
- Symmetric (z = 0): s = max|x| / (2^(b−1) − 1), range [−127, 127] for INT8. Simple, common for weights.
- Asymmetric: s = (max − min)/(2^b − 1), z = round(−min/s). Uses the full range when values are skewed (e.g. after ReLU).
Granularity: one scale per tensor (cheap, but one outlier wastes range for everyone), per channel (per output row of a weight matrix), or per group of g consecutive weights (g = 32–128; the norm for 4-bit LLM weights). Smaller groups → lower error, but more scales to store (a 16-bit scale per 128 weights adds 0.125 bits per weight).
def quantize_symmetric(w, bits=8, group=None):
qmax = 2 ** (bits - 1) - 1
W = w.reshape(-1, group) if group else w.reshape(1, -1) # rows = groups sharing a scale
scale = np.abs(W).max(axis=1, keepdims=True) / qmax
q = np.clip(np.round(W / scale), -qmax, qmax).astype(np.int8)
return q, scale
def dequantize(q, scale, shape): return (q * scale).reshape(shape)
rng = np.random.default_rng(0)
w = rng.normal(0, 0.02, size=(4096, 4096)).astype(np.float32)
w[0, :8] = 0.6 # a few large outliers, as in real LLMs
def rel_error(w, w_hat): return np.linalg.norm(w - w_hat) / np.linalg.norm(w)
for bits, group in [(8, None), (8, 128), (4, None), (4, 128), (4, 32)]:
q, s = quantize_symmetric(w, bits, group)
print(bits, group, round(rel_error(w, dequantize(q, s, w.shape)), 4))
# relative error — int8: 6.8% per-tensor (outliers stretch the scale) vs 0.65% with groups of 128
# int4: 95% per-tensor (ruined) vs 11.7% (g=128) and 9.7% (g=32)
Why LLMs are hard to quantise
- Outlier features: beyond a few billion parameters, Transformers develop a small number of activation dimensions with magnitudes 10–100× larger than the rest (LLM.int8 paper, 2022). Per-tensor activation quantisation then wastes nearly all levels on the outliers.
- Errors accumulate through many layers and through autoregressive generation.
- Some layers are more sensitive (embeddings, the output head, first and last blocks, attention projections in some models).
Responses: keep sensitive parts in higher precision, use fine granularity, handle outliers specially, and choose rounding that minimises the output error rather than the weight error.
Weight-only vs weight-and-activation
| Scheme | What's quantised | Benefit | Typical formats |
|---|---|---|---|
| Weight-only (W4A16, W8A16) | Weights; activations stay BF16/FP16; dequantise on the fly in the matmul kernel | Memory and bandwidth: ideal for decode-bound, small-batch serving and local inference | GPTQ, AWQ, GGUF, bitsandbytes NF4 |
| Weight + activation (W8A8, FP8, W4A4) | Both; matmuls run on low-precision tensor cores | Compute throughput: helps prefill and large-batch serving | SmoothQuant INT8, FP8 (E4M3), MXFP4/NVFP4 |
| KV cache | Cached keys/values (chapter 154) | More concurrent sequences and longer contexts per GPU | FP8 or INT8 (sometimes INT4) KV |
Post-training quantisation methods
Post-training quantisation (PTQ) quantises a trained model with no or little data; quantisation-aware training (QAT) fine-tunes with simulated quantisation so the model adapts.
- Round-to-nearest (RTN): quantise each weight independently. Fine at 8 bits; degrades at 4 bits, especially per-tensor.
- LLM.int8() (Dettmers et al., 2022): 8-bit matmul for most dimensions, with outlier feature dimensions kept in FP16 (mixed-precision decomposition).
- SmoothQuant (2022): activations have outliers but weights don't, so mathematically move the difficulty: scale activation channels down and the corresponding weight rows up (Y = (X·diag(s)⁻¹)(diag(s)·W)), making both quantisable to INT8.
- GPTQ (Frantar et al., 2022): quantise weights one column at a time and, using second-order information (the inverse Hessian of the layer's output error estimated from a small calibration set), adjust the not-yet-quantised weights to compensate for each rounding error. Accurate 4-bit (and 3-bit) weights in hours on one GPU.
- AWQ (Activation-aware Weight Quantization, 2023): not all weights matter equally: those multiplied by large activations do. Find per-channel scales (from calibration activations) that protect salient channels before rounding; no back-propagation, robust across domains.
- HQQ, SpQR, QuIP#, AQLM: further methods (calibration-free, sparse outliers, incoherence processing with rotations, vector/additive codebooks) pushing toward 2–3 bits.
- Rotation-based methods (QuaRot, SpinQuant): multiply by orthogonal matrices that spread outliers across dimensions before quantising, enabling 4-bit weights and activations.
NF4 and 4-bit formats
NF4 (QLoRA, chapter 163) chooses the 16 levels at quantiles of a standard normal distribution (normalised to [−1, 1]), since pre-trained weights are roughly normal: each level is used about equally often, minimising expected error for normally distributed weights. Used with block-wise absmax scaling (block 64) and double quantisation of the scales.
Microscaling formats (MXFP4, MXFP8, NVFP4) are hardware-supported: blocks of 16–32 low-bit floats share an 8-bit scale, giving 4-bit storage with float-like dynamic range; native on recent NVIDIA (Blackwell-class) and other accelerators, and used for some open-weight model releases distributed directly in 4-bit (e.g. gpt-oss in MXFP4).
from scipy.stats import norm
def nf4_levels():
"""Approximate NF4: 8 positive and 7 negative normal quantiles plus an exact zero, scaled to [-1, 1]."""
pos = norm.ppf(np.linspace(0.5, 0.9677, 9)[1:]) # 8 positive quantiles
neg = -norm.ppf(np.linspace(0.5, 0.9677, 8)[1:]) # 7 negative quantiles
levels = np.sort(np.concatenate([neg, [0.0], pos]))
return levels / np.abs(levels).max()
def quantize_codebook(w, levels, block=64):
W = w.reshape(-1, block); absmax = np.abs(W).max(1, keepdims=True)
idx = np.abs((W / absmax)[..., None] - levels).argmin(-1) # nearest level per weight
return idx.astype(np.uint8), absmax
def dequantize_codebook(idx, absmax, levels, shape): return (levels[idx] * absmax).reshape(shape)
w_normal = rng.normal(0, 0.02, size=(1024, 1024))
nf4 = nf4_levels(); uniform4 = np.linspace(-1, 1, 16)
for name, lv in [("NF4", nf4), ("uniform int4", uniform4)]:
idx, am = quantize_codebook(w_normal, lv)
print(name, round(rel_error(w_normal, dequantize_codebook(idx, am, lv, w_normal.shape)), 4))
# NF4 ≈ 9.2% vs uniform 4-bit ≈ 10.0% relative error on normally distributed weights
Quantisation-aware training
QAT inserts "fake quantisation" (quantise then dequantise) into the forward pass during fine-tuning, and passes gradients straight through the non-differentiable rounding (straight-through estimator). The model learns weights that survive quantisation. More expensive than PTQ but recovers most of the quality at 4 bits and below; several model families ship QAT 4-bit checkpoints (for example, some Gemma releases) intended for on-device use. Distillation from the full-precision model during QAT helps further.
GGUF and llama.cpp
llama.cpp runs LLMs efficiently on CPUs, Apple silicon, consumer GPUs and phones. Its file format GGUF packages weights, tokenizer, chat template and metadata in one memory-mappable file.
- K-quants (Q2_K … Q6_K) use super-blocks of 256 weights with sub-block scales and mins, in mixed bit widths; variants like Q4_K_M keep sensitive tensors (attention value/output projections, some FFN layers) at higher precision. Q4_K_M ≈ 4.8 bits/weight is a popular quality/size balance; Q5_K_M and Q6_K are closer to lossless; Q8_0 is nearly indistinguishable from FP16.
- I-quants (IQ2_XS, IQ3_M, IQ4_XS…) use lattice/codebook schemes for very low bit widths.
- Importance matrices (imatrix) computed from calibration text weight the rounding toward weights that matter, similar in spirit to AWQ.
- Used by Ollama, LM Studio, and many local-AI tools; on Apple silicon, MLX offers its own quantised formats.
Memory arithmetic
Weights memory ≈ parameters × bits / 8, plus a little for scales and higher-precision layers:
def weights_gb(params_billion, bits_per_weight):
return params_billion * 1e9 * bits_per_weight / 8 / 1e9
for p in (8, 70, 405):
print(p, {b: round(weights_gb(p, b), 1) for b in (16, 8, 4.8, 4)})
# 8B: 16 → 16 GB, 8 → 8, 4.8 (Q4_K_M) → 4.8, 4 → 4 · 70B: 140, 70, 42, 35 · 405B: 810, 405, 243, 202.5
def kv_cache_gb(layers, kv_heads, head_dim, tokens, batch=1, bytes_per=2):
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per / 1e9
kv_cache_gb(80, 8, 128, 32_000, batch=8) # ≈ 84 GB in BF16 for 8 × 32k-token sequences (70B-class GQA)
kv_cache_gb(80, 8, 128, 32_000, batch=8, bytes_per=1) # ≈ 42 GB with FP8 KV cache
The KV cache often dominates memory in serving (chapter 166); quantising it can matter as much as quantising weights.
Evaluating a quantised model
- Perplexity on held-out text (quick sanity check; small perplexity increases can hide task-specific damage).
- Task benchmarks relevant to you: your evaluation set (chapter 175), plus general checks (reasoning, coding, instruction following, multilingual).
- Long-context and structured-output tests: quantisation errors can show up in long generations, exact JSON, arithmetic and code.
- Compare at equal memory: a larger model at 4-bit often beats a smaller model at 16-bit in the same memory budget.
- Measure speed on the target hardware and batch sizes: weight-only quantisation helps decode; FP8/INT8 W8A8 helps prefill and throughput; some kernels are slower than BF16 on unsupported hardware.
Rules of thumb (they vary by model and method): 8-bit (INT8/FP8) is close to lossless; good 4-bit methods (AWQ, GPTQ, Q4_K_M, NF4) lose a little, more on hard reasoning and for small models; below 4 bits quality drops quickly unless using QAT or advanced codebook methods.
Lab: quantising a tiny GPT's weights
Setup. PyTorch on 2 CPU threads; chapter 156's GPT (2,197,632 parameters, 2,162,688 of them in weight matrices). All 2-D weight matrices (including the tied embedding/output matrix) are quantised and immediately dequantised ("fake quantisation") with symmetric round-to-nearest, then validation loss is measured on held-out textbook text (60 batches; fp32 baseline 4.2064). Sizes count weights at the stated bits plus one 16-bit scale per group and the remaining small parameters at 16 bits. Scope: plain round-to-nearest with no calibration; GPTQ, AWQ and similar methods do better at low bits, and tiny models have milder outliers than large ones.
Experiment 1: formats and granularity
| Format | Val loss | Δ vs fp32 | Size |
|---|---|---|---|
| fp32 | 4.2064 | — | 8.79 MB |
| fp16 / bf16 | 4.2064 / 4.2063 | 0.0000 | 4.40 MB |
| int8 per tensor | 4.2069 | +0.0005 | 2.23 MB |
| int8 per output channel | 4.2066 | +0.0002 | 2.23 MB |
| int4 per tensor | 4.3657 | +0.1593 | 1.15 MB |
| int4 per output channel | 4.2367 | +0.0304 | 1.15 MB |
| int4, groups of 32 | 4.2213 | +0.0149 | 1.29 MB |
| int3, groups of 32 | 4.3082 | +0.1018 | 1.02 MB |
| int2, groups of 32 | 5.4705 | +1.2641 | 0.75 MB |
- 16-bit and 8-bit were essentially free. At 4 bits, granularity decided the outcome: one scale per matrix cost 10× more than one scale per 32 weights, for 12% more storage.
- Below 4 bits quality fell off a cliff with this simple method. Practical low-bit schemes (GPTQ, AWQ, QuIP#, AQLM, trellis/vector codebooks in llama.cpp's IQ formats) exist because round-to-nearest stops working there.
Experiment 2: outliers, made safely
Injecting a huge weight changes what the model computes, so instead the lab made an outlier channel without changing the function: in every block, LayerNorm output dimension 7 was divided by 20 and the matching input column of the next weight matrix multiplied by 20. The fp32 loss stayed exactly 4.2064. The same quantisers then gave:
| Quantiser | Normal model Δ | With the outlier channel Δ |
|---|---|---|
| int8 per tensor | +0.0005 | +0.0061 (12×) |
| int8 per output channel | +0.0002 | +0.0008 |
| int4 per output channel | +0.0304 | +0.5930 (20×) |
| int4 groups of 32 along the input | +0.0149 | +0.0487 (3×) |
A large input column shows up in every row, so per-output-channel scales can't isolate it: each row's scale was stretched by the outlier. Groups along the input dimension confined the damage to one group of 32 per row. This is the problem large LLMs have with real activation outliers (a few residual-stream dimensions far larger than the rest), and the idea behind SmoothQuant and AWQ, which move scale between activations and weights in exactly this function-preserving way, but in the direction that helps.
Statistics of this model: weights have standard deviation 0.053 and a maximum of 8.4 standard deviations (kurtosis 4.7); in the final block's output the median activation magnitude was 1.9 and the largest 23.3, with four dimensions near 20: the same "a few big channels" pattern, mildly.
Experiment 3: does int8 run faster here?
PyTorch dynamic int8 quantisation of the Linear layers, forward pass on 8 × 128 tokens: 35.8 ms → 23.1 ms, validation loss 4.2087 (+0.002). The speed-up depends entirely on having kernels for the format: on GPUs, weight-only int4 kernels speed up memory-bound decoding, while int8/fp8 matrix-multiply units speed up compute-bound prefill and large batches.
Try it yourself
- Quantise only the attention or only the MLP weights to int3 and find which part is more sensitive.
- Keep the 1% largest-magnitude weights per matrix in fp16 and the rest at int3; how much loss returns?
- Implement the SmoothQuant transform (migrate scale from activations to weights by the square root of their ratio) and quantise activations to int8.
- Measure greedy-generation agreement (same next token) between fp32 and each format on 1,000 positions.
Revision sheet: quantization
Key ideas
- Quantisation stores numbers in fewer bits: smaller models, less memory traffic, often faster inference and cheaper hardware.
- Formats: fp32, fp16, bf16 (fp32's range, less precision), fp8 (E4M3/E5M2), int8, int4, and lower-bit codebook formats.
- Symmetric (scale) vs asymmetric (scale + zero point); granularity: per tensor, per channel, per group (32–128).
- LLMs are hard because of outliers, especially in activations; fixes: finer groups, mixed precision, SmoothQuant, AWQ, rotations (QuaRot, SpinQuant).
- Weight-only (W4A16, W8A16) speeds memory-bound decoding; weight-and-activation (W8A8, FP8) speeds compute-bound prefill.
- PTQ methods: round-to-nearest, GPTQ (second-order error compensation), AWQ (activation-aware scaling); QAT trains with quantisation in the loop.
- GGUF / llama.cpp K-quants and I-quants for CPUs and Macs; KV-cache quantisation saves memory for long contexts.
- Evaluate on your tasks: perplexity hides losses in maths, code, long context and less common languages.
Numbers to remember
- Weights memory = parameters × bits / 8 (7B: 14 GB fp16, 7 GB int8, ~3.5–4 GB int4).
- Lab: int8 Δ +0.0002–0.0005; int4 per tensor +0.159; per channel +0.030; groups of 32 +0.015; int2 +1.26.
- Lab: an outlier input channel made int4 per-channel 20× worse; groups of 32 only 3×.
Pitfalls
- Using per-tensor scales at 4 bits.
- Judging a quantised model by perplexity alone.
- Expecting speed-ups without kernels for the format on your hardware.
- Forgetting the KV cache and activations in memory budgets.
- Comparing quantised models built with different calibration data without saying so.
Glossary
- Scale / zero point: the parameters mapping integers back to real values.
- Group-wise quantisation: one scale per block of weights.
- PTQ / QAT: post-training quantisation / quantisation-aware training.
- W4A16: 4-bit weights, 16-bit activations.
- Outlier channel: a feature dimension with much larger magnitudes than others.