In short
Quantization stores a model's weights, and sometimes its activations and KV cache, in fewer bits than the 16 it was trained to use: 8-bit integers or floats, or 4-bit integers with a scale for every small group of weights. Because decoding is limited by memory bandwidth, fewer bytes per weight means a smaller model that also generates faster, with more room left for KV cache and larger batches. The hard part is accuracy: a few large outlier values make naive rounding fail, so methods such as LLM.int8(), SmoothQuant, GPTQ and AWQ handle the outliers or choose the rounding with calibration data, and the result has to be checked with perplexity and with evaluations of the tasks you actually run.
Key points
- Weight memory is parameters times bits per weight: an 8B model needs about 16 GB in 16-bit, 8 GB in 8-bit and a little over 4 GB in 4-bit with group scales.
- Weight-only quantization, such as 4-bit weights with 16-bit activations, shrinks memory and speeds up memory-bound decoding; weight-and-activation quantization, such as W8A8 or FP8, also uses faster low-precision matrix units, which matters more for prefill and large batches.
- Granularity decides accuracy: one scale per tensor fails at 4 bits, one per output channel is the norm at 8 bits, and one per group of 32 to 128 weights is the norm at 4 bits.
- Large activation outliers in a few fixed channels break naive 8-bit quantization of big models. LLM.int8() keeps them in 16-bit; SmoothQuant moves the difficulty into the weights.
- GPTQ corrects rounding error with second-order information from calibration data, AWQ protects the weights that large activations depend on, and NF4 places its 16 levels where normally distributed weights fall.
- Check every quantized model with perplexity on held-out text and with your own task evaluations; perplexity alone can hide failures in reasoning, code and structured output.
Why quantize a language model
Language models are usually released with 16-bit weights. Every weight is read from memory at every decoding step, and the arithmetic done with it is tiny, so decoding speed is set mostly by the bytes moved per token. Storing weights in 8 bits halves those bytes; 4 bits quarters them.
That buys three things, and the order matters for deciding what to quantize:
- Fit: a model that needs two accelerators at 16-bit may fit on one at 8 or 4 bits, which removes the communication cost of splitting it.
- Decode speed: fewer bytes per weight means each memory-bound decoding step finishes sooner, as long as the dequantization kernels are efficient.
- Capacity: memory freed from weights becomes room for KV cache, so the server can hold more sequences and longer contexts at once.
The price is accuracy, and it is not uniform. It depends on the number format, the granularity of the scales, the method used to choose the rounding, the model and the task. The rest of this post works through each of those. How a serving engine turns freed memory into batch capacity is covered in LLM inference serving and batching.
Memory arithmetic for weights and the KV cache
Weight memory is parameters times bits per weight, divided by eight. Group-wise formats also store a scale for every group of weights, which adds to the bits per weight: a 16-bit scale for every 128 weights adds 0.125 bits, and for every 32 weights it adds 0.5. The KV cache is separate and grows with every token held: per token it stores one key and one value vector for every layer and every key-value head. The sketch below uses round numbers, and a hypothetical model shape of 80 layers with 8 key-value heads of dimension 128:
def weight_gb(params, bits_per_weight):
return params * bits_per_weight / 8 / 1e9
for params in (8e9, 70e9):
row = [f'{weight_gb(params, b):6.1f}' for b in (16, 8, 4.125, 4.5)]
print(f'{params / 1e9:4.0f}B FP16 {row[0]} GB INT8 {row[1]} GB INT4 g128 {row[2]} GB INT4 g32 {row[3]} GB')
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value):
return 2 * layers * kv_heads * head_dim * bytes_per_value # 2: one key and one value vector
for label, b in (('FP16', 2), ('FP8', 1), ('INT4', 0.5)):
per_tok = kv_bytes_per_token(80, 8, 128, b)
print(f'KV cache {label}: {per_tok / 1024:6.0f} KiB per token, {per_tok * 32768 / 2**30:5.1f} GiB per 32k-token sequence') 8B FP16 16.0 GB INT8 8.0 GB INT4 g128 4.1 GB INT4 g32 4.5 GB
70B FP16 140.0 GB INT8 70.0 GB INT4 g128 36.1 GB INT4 g32 39.4 GB
KV cache FP16: 320 KiB per token, 10.0 GiB per 32k-token sequence
KV cache FP8: 160 KiB per token, 5.0 GiB per 32k-token sequence
KV cache INT4: 80 KiB per token, 2.5 GiB per 32k-token sequenceTwo things stand out. Quantizing a 70B model from 16 to 4 bits saves about 100 GB of weights, the difference between several accelerators and one or two. And at long contexts the KV cache is not small: in this shape, one 32k-token sequence needs 10 GiB of 16-bit cache, and four such sequences take more memory than the 4-bit weights of the whole model. That is why KV-cache quantization, covered below, matters as much as weight quantization for long-context serving. The INT4 cache line ignores the space for scales, which real schemes also store. These figures cover weights and cache only; activations, the runtime and fragmentation take more.
Number formats: FP16, BF16, FP8, INT8, INT4 and NF4
| Format | Bits | Layout | Range and precision | Typical use in LLMs |
|---|---|---|---|---|
| FP16 | 16 | 1 sign, 5 exponent, 10 fraction bits | Fine precision, narrow range; large values can overflow | Inference, mixed-precision training with loss scaling |
| BF16 | 16 | 1 sign, 8 exponent, 7 fraction bits | About the range of FP32, roughly two to three decimal digits of precision | Training and the usual release format for weights |
| FP8 E4M3 | 8 | 1 sign, 4 exponent, 3 mantissa bits | Largest normal value 448; no infinities | Weights and activations for inference and the forward pass |
| FP8 E5M2 | 8 | 1 sign, 5 exponent, 2 mantissa bits | Largest normal value 57,344; coarser steps | Gradients in training; one option for the KV cache |
| INT8 | 8 | Integer from -127 to 127 times a scale | Even steps across the scaled range | W8A8 inference, 8-bit weight-only inference |
| INT4 | 4 | Integer from -8 to 7 (or 0 to 15 with a zero point) times a scale | Sixteen even steps; needs a scale per small group | Weight-only inference with GPTQ or AWQ |
| NF4 | 4 | Index into 16 fixed levels at quantiles of a normal distribution, times a block scale | Levels dense near zero and sparse in the tails | Frozen base weights in QLoRA fine-tuning |
Floating-point formats spend bits on an exponent, so their steps are fine near zero and coarse for large values, and they need no external scale for a wide range. BF16 keeps FP32's 8 exponent bits and gives up precision, so it covers roughly the same range as FP32; FP16 keeps more precision and much less range. Integer formats have evenly spaced steps over a range set by a scale factor stored next to them, so their accuracy depends entirely on choosing that scale well.
FP8 comes in two encodings, defined in the 2022 paper by Micikevicius and colleagues. Its authors recommend E4M3 for weights and activations and E5M2 for gradients, and E4M3 gives up infinities and all but one mantissa pattern of its not-a-number codes to extend its range. Even so, the paper found that some networks need per-tensor scaling factors. In its 1.3B GPT experiment, casting the matrix-multiply inputs and the residual connections to E4M3 with one fixed exponent bias gave a perplexity of 12.59 against 10.19 for BF16, while calibrated per-tensor scales brought it to 10.44. In other words, FP8 behaves like the integer formats in one respect: it works best with a scale.
Scales, zero points and granularity
Integer quantization maps a range of real values onto a small set of integers. In symmetric quantization, the scale is the largest absolute value in the block divided by the largest integer, 127 for INT8 or 7 for a symmetric INT4, and each value is divided by the scale, rounded and clipped. Dequantizing multiplies back. Asymmetric quantization adds a zero point so that the integer range can cover a range that is not centered on zero, which helps for values such as post-activation outputs that are mostly positive.
The choice that matters most is granularity: how many values share one scale. A single scale per tensor is cheap, but one large value anywhere stretches the range for everything else. One scale per output channel, a row of the weight matrix, is the usual choice for 8-bit weights. At 4 bits, with only 16 levels, even that is too coarse, and the standard practice is group-wise quantization: one scale for every 32, 64 or 128 consecutive weights. The experiment below quantizes a synthetic 1024 by 4096 layer, normally distributed with a few large weights mixed in as real layers have, and measures the relative error of the weights and of the layer's outputs on 64 random inputs. It needs only numpy:
import numpy as np
rng = np.random.default_rng(0)
W = rng.normal(0, 0.02, size=(1024, 4096)).astype(np.float32) # one linear layer: out x in
W[rng.random(W.shape) < 0.001] *= 8 # a few large weights, as real layers have
X = rng.normal(0, 1, size=(64, 4096)).astype(np.float32) # 64 tokens of activations
def quantize(w, bits, group=None):
"""Symmetric round-to-nearest. group=None: one scale per row; group=g: one scale per g weights."""
qmax = 2 ** (bits - 1) - 1 # 127 for INT8, 7 for INT4
rows, cols = w.shape
g = cols if group is None else group
wg = w.reshape(rows, cols // g, g)
scale = np.abs(wg).max(axis=-1, keepdims=True) / qmax # absmax per row or per group
q = np.clip(np.round(wg / scale), -qmax, qmax).astype(np.int8)
return (q * scale).reshape(rows, cols), scale.size # dequantized weights, number of scales
def per_tensor(w, bits):
qmax = 2 ** (bits - 1) - 1
scale = np.abs(w).max() / qmax
return np.clip(np.round(w / scale), -qmax, qmax) * scale, 1
def rel(a, b):
return np.linalg.norm(a - b) / np.linalg.norm(b)
Y = X @ W.T
print('scheme bits/weight weight err output err')
for name, bits, fn in [
('INT8 per-tensor', 8, lambda: per_tensor(W, 8)),
('INT8 per-channel', 8, lambda: quantize(W, 8)),
('INT4 per-tensor', 4, lambda: per_tensor(W, 4)),
('INT4 per-channel', 4, lambda: quantize(W, 4)),
('INT4 group 128', 4, lambda: quantize(W, 4, 128)),
('INT4 group 32', 4, lambda: quantize(W, 4, 32)),
]:
Wq, n_scales = fn()
bpw = bits + 16 * n_scales / W.size # each scale stored as FP16
print(f'{name:22} {bpw:11.3f} {rel(Wq, W):10.4f} {rel(X @ Wq.T, Y):10.4f}')Running it with numpy 2.0 prints:
scheme bits/weight weight err output err
INT8 per-tensor 8.000 0.0704 0.0707
INT8 per-channel 8.004 0.0276 0.0277
INT4 per-tensor 4.000 0.9344 0.9368
INT4 per-channel 4.004 0.4856 0.4883
INT4 group 128 4.125 0.1556 0.1563
INT4 group 32 4.500 0.1083 0.1085Per-tensor INT4 is useless here: the scale is set by the single largest weight, so most normal weights round to zero and the output error is above 90 percent. Per-channel scales halve that, and groups of 128 cut it to about 16 percent for an extra eighth of a bit per weight; groups of 32 do better again for half a bit. At 8 bits even a per-tensor scale is tolerable, and per-channel scales bring the error under 3 percent. This is plain round-to-nearest. The methods below keep the same storage format and choose the rounding and scales more carefully, using calibration data, to reduce the output error further.
Weight-only versus weight-and-activation quantization
Schemes are often named by their bits for weights and activations: W4A16 means 4-bit weights and 16-bit activations, W8A8 means both in 8 bits. The two families speed up different things.
- Weight-only (W8A16, W4A16): weights are stored in low precision and expanded to 16-bit inside the matrix-multiply kernel, so the arithmetic is still 16-bit. It shrinks memory and speeds up memory-bound decoding, especially at small batch sizes. It does little for compute-bound prefill, and the dequantization work can eat into the gain at large batch sizes.
- Weight and activation (W8A8 in INT8 or FP8): both operands are low precision, so the matrix multiply itself runs on the accelerator's 8-bit units, at higher throughput than 16-bit where the hardware supports it. It helps prefill and large batches as well as memory. It is harder, because activations are computed on the fly, change with every input and contain outliers.
Activation scales are either static, fixed in advance from calibration data, or dynamic, computed per token or per tensor at run time. Dynamic scales follow the data better and cost a small reduction step in every layer. A practical reading: for a single user or a small batch on a model that barely fits, 4-bit weight-only quantization is usually the first thing to try; for a high-throughput server on hardware with fast 8-bit units, FP8 or INT8 W8A8 is.
Outliers, and why LLM.int8() exists
Activations in large transformers are not well-behaved. Dettmers and colleagues, in the LLM.int8() paper (NeurIPS 2022), describe highly systematic emergent features: a few hidden dimensions whose values are far larger than the rest. They define an outlier as a magnitude of at least 6.0, and report that at around 6.7B parameters a phase shift occurs, after which all transformer layers and about 75 percent of sequence dimensions are affected. Beyond 2.7B parameters, the standard 8-bit methods they tested, absmax, row-wise and zero-point quantization, got worse as models grew; at 13B, absmax 8-bit perplexity was 19.08 against 12.45 in 32-bit.
The reason is the same as the per-tensor INT4 failure above. A per-tensor or per-token scale is set by the largest value, so one huge channel leaves only a few integer levels for every other channel. Continuing the script above with one activation channel 60 times larger than the rest shows the effect, and a fix:
# Activation outliers: one hidden channel 60x larger than the rest, as LLM.int8() describes
Xo = X.copy()
Xo[:, 42] *= 60
for label, A in [('no outlier', X), ('one outlier channel', Xo)]:
s = np.abs(A).max() / 127 # per-tensor INT8 for activations
Aq = np.clip(np.round(A / s), -127, 127) * s
normal = np.delete(np.arange(4096), 42)
print(f'INT8 activations, {label:20} error on the other channels: {rel(Aq[:, normal], A[:, normal]):.4f}')
# SmoothQuant-style migration: divide each activation channel by s, multiply the weight column by s
def w8a8(A, Wm):
s = np.abs(A).max() / 127
Aq = np.clip(np.round(A / s), -127, 127) * s # INT8 activations, per tensor
Wq, _ = quantize(Wm, 8) # INT8 weights, per output channel
return Aq @ Wq.T
s = np.sqrt(np.abs(Xo).max(axis=0) / np.abs(W).max(axis=0)) # alpha = 0.5
Yo = Xo @ W.T
print(f'W8A8 output error, outlier channel, plain: {rel(w8a8(Xo, W), Yo):.4f}')
print(f'W8A8 output error, outlier channel, smoothed: {rel(w8a8(Xo / s, W * s), Yo):.4f}')INT8 activations, no outlier error on the other channels: 0.0107
INT8 activations, one outlier channel error on the other channels: 0.2829
W8A8 output error, outlier channel, plain: 0.2069
W8A8 output error, outlier channel, smoothed: 0.0308One outlier channel raises the INT8 error on all the other channels from about 1 percent to 28 percent. LLM.int8() handles it by decomposition: vector-wise quantization, with separate normalization constants for each inner product in the matrix multiply, plus a mixed-precision split that sends the outlier feature dimensions through a 16-bit multiply. The authors report that fewer than 0.1 percent of values take the 16-bit path, that memory for inference roughly halves, and that models up to 175B parameters run without performance degradation. The cost is speed: the paper says the overhead can slow inference compared with FP16 for models below 6.7B parameters.
SmoothQuant, from Xiao and colleagues, takes the other route for W8A8. Outliers sit in fixed channels, consistent across tokens, so their scale can be measured offline. Each input channel j is divided by a factor s_j in the activations and multiplied by the same factor in the matching weight column, which leaves the layer's output mathematically unchanged while flattening the activations; the weights, which are easy to quantize, absorb the difficulty. The factor is s_j = max|X_j|^α / max|W_j|^(1 - α), and the authors call α = 0.5 a well-balanced point for most models they tested, with larger values for models with stronger outliers. In the experiment above, that migration cut the W8A8 output error from 21 percent to 3 percent. The authors report up to 1.56 times speedup and 2 times memory reduction with negligible accuracy loss, across models including OPT, BLOOM, Llama, Falcon, Mistral and Mixtral.
GPTQ and AWQ: 4-bit weights that keep their accuracy
At 4 bits, rounding each weight to its nearest level is not good enough, even with group scales. The two most widely used post-training methods improve on it in different ways, and both store the result in a standard group-wise INT4 layout that fast kernels can read.
GPTQ, from Frantar and colleagues (ICLR 2023), quantizes one layer at a time to minimize the squared error of that layer's outputs on calibration inputs, not the error of the weights themselves. It quantizes the weight matrix one column at a time, and after each column it adjusts the columns not yet quantized to compensate for the rounding error, using the inverse of a Hessian built from the calibration inputs. Lazy updates in blocks of 128 columns and a Cholesky reformulation make it fast and stable at scale. The paper calibrates on 128 random 2,048-token segments of the C4 dataset, reports that group size 128 costs about 0.15 extra bits per weight and noticeably improves accuracy, and quantizes 175B-parameter models to 3 or 4 bits with negligible accuracy loss in about four GPU hours, with end-to-end speedups over FP16 of about 3.25 times on an A100 and 4.5 times on an A6000.
AWQ, from Lin and colleagues (MLSys 2024), starts from an observation: protecting only about 1 percent of salient weights can greatly reduce quantization error, and the salient weights are the ones that multiply large activations, not the ones that are large themselves. Keeping those weights in 16-bit would make a mixed-precision format that is hard to implement efficiently, so AWQ scales the salient input channels up before quantizing, and the activations down by the same factor, which reduces their relative rounding error. The scale is the average activation magnitude per channel raised to a power α, found by a fast grid search between 0 and 1, and the paper uses group size 128 throughout. AWQ needs no backpropagation or reconstruction, which the authors say helps it generalize across domains without overfitting the calibration set; they report more than 3 times speedup over the Hugging Face FP16 implementation with their own inference engine.
Both need calibration data. Use text that resembles your traffic: chat for a chat model, code for a code model, and your languages, not only English web text.
NF4 and QLoRA
Integer formats space their levels evenly, but trained weights are not spread evenly: they cluster around zero in a roughly normal shape. NormalFloat 4 (NF4), introduced with QLoRA by Dettmers and colleagues (2023), puts its 16 levels where a normal distribution puts its probability mass. The levels are quantiles of a standard normal distribution, rescaled to the range from -1 to 1, built asymmetrically so that zero is represented exactly. Each block of 64 weights is divided by its absolute maximum and mapped to the nearest level. The authors describe NF4 as information-theoretically optimal for normally distributed weights.
QLoRA adds double quantization, which quantizes the block scales themselves to 8-bit in blocks of 256, saving about 0.37 bits per parameter by the authors' count, and paged optimizers to absorb memory spikes. In their comparison, the mean perplexity on Pile Common Crawl across a range of models from 125M to 13B parameters was 34.34 for Int4, 31.07 and 29.48 for two FP4 variants, and 27.41 for NF4 with double quantization, lower being better. On MMLU, averaged over their fine-tuning runs, NF4 with double quantization scored 53.1 against 53.0 for BF16.
NF4 is mainly a storage format for a frozen base model during fine-tuning: weights are dequantized to BF16 for every multiply, so the arithmetic stays in 16-bit. For serving, INT4 group-wise layouts from GPTQ or AWQ usually have faster kernels. How adapters are trained on top of an NF4 base, and the caveats of merging them back, are covered in LoRA fine-tuning explained.
Quantizing the KV cache
The KV cache stores each token's keys and values for every layer, and as the memory arithmetic showed, it can rival the weights at long contexts or large batches. Quantizing it lets the same memory hold more tokens, and so more concurrent sequences or longer contexts. It is a different problem from weight quantization: the cache is written at run time, so its scales have to be fixed in advance or computed as tokens arrive, and errors in keys change which tokens attention picks.
The common production option is an 8-bit floating-point cache. vLLM, for example, documents FP8 KV caches in both E4M3 and E5M2, and says this lets a server store more tokens, which can improve throughput and allow longer contexts. Its documentation also notes that by default the scales are all set to 1.0 without calibration, recommends calibrating per-tensor or per-head scales on a dataset for the best accuracy, and allows sensitive layers, such as sliding-window attention layers, to stay in the model's native type.
Lower bit widths need structure. Liu and colleagues, in the KIVI paper (ICML 2024), find that keys and values behave differently: the key cache should be quantized per channel, grouping elements along the channel dimension, and the value cache per token. With that split they quantize the cache to 2 bits without tuning, and report nearly the same quality on Llama, Falcon and Mistral models, 2.6 times less peak memory including weights, up to 4 times larger batches and 2.35 to 3.47 times higher throughput on their workload. Quantizing the cache composes with prefix caching, which reuses the cache across requests; see prompt caching and the KV cache for what the cache holds and how it is shared.
Evaluating a quantized model
Every paper above reports perplexity, the exponential of the average negative log-likelihood on held-out text, because it is cheap and comparable. It is a good first filter: a large jump means something broke. It is not enough on its own. Perplexity is averaged over many easy tokens, and quantization damage can concentrate in the rare tokens that decide an answer: a digit in arithmetic, a bracket in code, a field name in JSON, a tool name in a function call. Long generations also compound small errors in a way a single next-token score does not show.
- Fix the baseline: the 16-bit model, served by the same engine with the same prompts and sampling settings.
- Measure perplexity on held-out text close to your domain, for the baseline and each quantized variant. Treat a clear increase as a stop sign before running anything else.
- Run your task evaluations: the graded examples you already use for the application, including structured output validity, tool call accuracy, long-context retrieval and every language you serve.
- Compare the outputs directly: the share of greedy outputs that change, and on which inputs, is a quick way to find where the damage is.
- Measure what you quantized for: memory per replica, tokens per second and latency at your real batch sizes, since a format without fast kernels on your hardware can be smaller and slower.
- Evaluate the exact artifact you deploy, with its calibration set, group size and KV-cache setting, and rerun the suite whenever any of them changes.
Putting that suite into CI makes a quantization change one more change that has to pass the evals; see AI agent evals in CI. Quantization is one of several levers on latency and memory; speculative decoding and batching are the others, and how to reduce LLM costs covers the wider list.
If you are building an AI agent or assistant that has to run a model within tight memory and latency limits, see our AI agent development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Dettmers et al., LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale (arXiv, NeurIPS 2022)
- Xiao et al., SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models (arXiv)
- Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (arXiv, ICLR 2023)
- Lin et al., AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration (arXiv, MLSys 2024)
- Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs (arXiv, 2023)
- Micikevicius et al., FP8 Formats for Deep Learning (arXiv, 2022)
- Liu et al., KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache (arXiv, ICML 2024)
- vLLM documentation: Quantized KV Cache
- Wikipedia: bfloat16 floating-point format
- Google Cloud TPU documentation: Improve your model's performance with bfloat16