7 Inference and Serving 5 / 8
  1. In this chapter
  2. Your first inference service
  3. Decoding and Sampling
  4. KV Cache and Inference Performance
  5. Prefix Caching and PD Disaggregation
  6. Model Quantization
  7. LLM Inference Serving
  8. Continuous Batching and PagedAttention
  9. Speculative Decoding
All chapters →

Chapter 7 · Inference and Serving 7.5

Model Quantization: INT8, INT4, GPTQ and AWQ Explained and Measured

Quantization stores weights, activations or the KV cache in fewer bits. This page starts from the memory budget, builds up from scales and groups, measures INT8 and INT4 on Qwen2.5-0.5B, implements SmoothQuant, AWQ-style scaling, GPTQ and KV-cache quantization, and ends with a selection guide.

Intermediate 55 min read Updated Companion code ↓

After this page you will be able to

  • Work out how much memory a model's weights and KV cache take, and explain why quantization mainly speeds up decode.
  • Write down symmetric and grouped quantization and explain the "effective bit-width".
  • Explain why INT8 is nearly lossless, why INT4 needs groups and calibration, and why activations are harder to quantize than weights.
  • Implement SmoothQuant, AWQ-style scaling, GPTQ and KV-cache quantization yourself and compare them by perplexity.
  • Choose a quantization scheme according to whether the bottleneck is the weights, the KV cache or compute, and know what to check before going live.
On this page
  1. Why Quantize: A Memory and Bandwidth Budget
  2. What to Quantize and When
  3. The Math of Quantization: Scales, Zero Points and Groups
  4. Try it: bit-width, groups and outliers
  5. Hands-on: Four Experiments on Qwen2.5-0.5B
  6. Experiment 1: Bit-width and Granularity of Weights
  7. Not Every Layer Is Equally Sensitive
  8. Experiment 2: Why Activations Are Harder to Quantize
  9. Experiment 3: Reducing the Error with Calibration Data
  10. Experiment 4: KV-Cache Quantization
  11. Putting the Results Together
  12. Choosing and Shipping
  13. Identify the Bottleneck First
  14. Tools and Formats
  15. Symptoms, Causes and Actions
  16. Common Misconceptions
  17. Research example: vary KV cache precision across layers
  18. Summary and Exercises
  19. Quick quiz
  20. Further Reading
  21. FAQ

Why Quantize: A Memory and Bandwidth Budget

The cost of serving a large model comes mainly from three things: the memory taken by the weights, the memory taken by the KV cache, and the memory bandwidth needed to read all the weights once for every generated token. Quantization represents numbers with fewer bits and reduces all three (why reading all the weights once per token becomes the bottleneck is explained in GPUs and the Roofline Model; how FP16, BF16 and FP8 spend their bits, and how each fails, in Numerical Precision). Start with the arithmetic. The code below counts parameters from the config.json of Llama-3-8B, assumes a memory bandwidth of 2 TB/s, and assumes 90% of an 80 GB card is usable (the rest is left for activations and other overhead; in vLLM the --gpu-memory-utilization flag controls this fraction, and its default has changed between versions).

import torch
from transformers import AutoConfig, AutoModelForCausalLM

cfg = AutoConfig.from_pretrained("NousResearch/Meta-Llama-3-8B")
with torch.device("meta"):  # build the skeleton only, no memory allocated
    skel = AutoModelForCausalLM.from_config(cfg)
n_emb = skel.get_input_embeddings().weight.numel()  # input embedding
n_head = skel.lm_head.weight.numel()  # output head (not tied to embedding)
n_lin = sum(m.weight.numel() for n, m in skel.named_modules()
            if isinstance(m, torch.nn.Linear) and ".layers." in n)
n_all = sum(p.numel() for p in skel.parameters())
print(f"Llama-3-8B: {n_all / 1e9:.2f}B parameters, "
      f"decoder linear layers {n_lin / 1e9:.2f}B,")
print(f"embedding {n_emb / 1e9:.2f}B, output head {n_head / 1e9:.2f}B")

BW, MEM = 2e12, 0.9 * 80e9  # assume 2 TB/s bandwidth; 90% of an 80 GB card
kv_tok = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * \
    (cfg.hidden_size // cfg.num_attention_heads)  # K and V elements per token
print(f"KV cache per token: {kv_tok * 2} bytes (BF16); "
      f"one 8K-token sequence {kv_tok * 2 * 8192 / 1e9:.2f} GB")
print("weights + KV   weights GB  read/step GB  tokens/s bound  8K seqs")
for tag, w_bits, kv_bits in (("BF16 + BF16", 16, 16),
                             ("INT4 + BF16", 4.125, 16),
                             ("INT4 + INT8", 4.125, 8.125)):
    lin = n_lin * w_bits / 8  # quantize decoder linears only; the rest BF16
    weights = lin + (n_emb + n_head) * 2
    read = lin + n_head * 2  # a decode step reads linears + head (1 emb row)
    seqs = (MEM - weights) // (kv_tok * kv_bits / 8 * 8192)
    print(f"{tag:<14}{weights / 1e9:11.1f}{read / 1e9:14.1f}"
          f"{BW / read:16.0f}{seqs:9.0f}")

Output:

Llama-3-8B: 8.03B parameters, decoder linear layers 6.98B,
embedding 0.53B, output head 0.53B
KV cache per token: 131072 bytes (BF16); one 8K-token sequence 1.07 GB
weights + KV   weights GB  read/step GB  tokens/s bound  8K seqs
BF16 + BF16          16.1          15.0             133       52
INT4 + BF16           5.7           4.6             430       61
INT4 + INT8           5.7           4.6             430      121

Four things to read from this table:

  1. The weights do not shrink 4 times. Only the linear layers of the decoder (6.98B) are quantized to INT4, and each group also stores a scale, so they count as 4.125 bits. The input embedding and the output layer, 0.53B each, stay in BF16, so the weights fall from 16.1 GB to 5.7 GB, about 2.8 times.
  2. The speed limit of decode comes from how many bytes are read per step. Generating each token reads the weights of the linear layers and the output layer from memory once: 15.0 GB in BF16, which a 2 TB/s bandwidth supports at 133 tokens/s at most; INT4 reads only 4.6 GB, for an upper bound of 430 tokens/s, about 3.2 times higher. This is the bound for batch size 1; real speed is further limited by kernel efficiency, KV-cache reads and scheduling overhead.
  3. The KV cache decides concurrency. The KV cache of Llama-3-8B takes 131,072 bytes per token (2 × 32 layers × 8 KV heads × 128 dimensions × 2 bytes), so one sequence of 8K tokens takes 1.07 GB. After the BF16 weights, an 80 GB card has room for about 52 such sequences; compressing the weights to INT4 raises that only to 61; compressing the KV cache to INT8 as well (one scale per 128-dimensional vector, 8.125 bits) reaches 121. When concurrency is limited by memory, compressing the KV cache is more effective than compressing the weights.
  4. Prefill does not necessarily get faster. Prefill processes the whole prompt at once and is bound by compute. W4A16 kernels usually dequantize the weights to 16 bits in registers and then multiply (the TinyChat section of the AWQ paper discusses this), so the benefit for prefill is limited; to make the matrix multiplication itself run in low precision (W8A8, FP8), the activations must be quantized too, which is the subject of Experiment 2.

What to Quantize and When

Quantization can happen in three places: weights are static and can be calibrated offline, the most mature case; activations change with the input and are harder; the KV cache grows during inference and decides concurrency. In terms of timing there are two routes. Post-training quantization (PTQ) quantizes a finished model directly; it is cheap and the most common route for open models. Quantization-aware training (QAT) simulates the quantization error during training so that the model adapts to low-bit representations; it can reach better accuracy but is complex and expensive. All experiments on this page are PTQ.

Quantization targets and routes The top half separates weights, activations and the KV cache as quantization targets, with their main benefit and risk; the bottom half compares the PTQ and QAT routes in training cost and accuracy. Quantization answers two questions: what to compress, and when 1. What to quantize Weights The most common first step Benefit: fits in less memory Activations Compresses runtime tensors Risk: harder to calibrate KV cache For long context and concurrency Risk: decode stability, support 2. When to quantize PTQ: quantize after training QAT: simulate it in training Costlier, but steadier accuracy
In practice, PTQ is used first to settle whether the model fits and whether throughput is acceptable; QAT is considered only if the accuracy gain is worth the extra cost.

The Math of Quantization: Scales, Zero Points and Groups

Start by writing quantization as a formula. For a group of floating-point weights xx, find a scale ss, divide every number by ss and round to an integer qq; when the weight is used, multiply by ss again to get the restored value x^\hat{x}. Symmetric quantization maps 0 to the integer 0, so the scale depends only on the number with the largest magnitude:

s=max⁡i∣xi∣2b−1−1,qi=clip(round(xi/s),  −(2b−1−1),  2b−1−1),x^i=s qis = \frac{\max_i |x_i|}{2^{b-1}-1},\qquad q_i = \mathrm{clip}\Big(\mathrm{round}\big(x_i / s\big),\; -(2^{b-1}-1),\; 2^{b-1}-1\Big),\qquad \hat{x}_i = s\, q_i

Asymmetric quantization stores one more number, a zero point zz, so that the integer range [0,2b−1][0, 2^b-1] exactly covers [xmin⁡,xmax⁡][x_{\min}, x_{\max}]:

s=xmax⁡−xmin⁡2b−1,z=round(−xmin⁡/s),qi=clip(round(xi/s)+z,  0,  2b−1),x^i=s (qi−z)s = \frac{x_{\max}-x_{\min}}{2^b-1},\qquad z = \mathrm{round}\big(-x_{\min}/s\big),\qquad q_i = \mathrm{clip}\big(\mathrm{round}(x_i / s) + z,\; 0,\; 2^b-1\big),\qquad \hat{x}_i = s\,(q_i - z)

Unless a value is clipped, the error of each weight is at most s/2s/2. Every extra bit halves the step ss and cuts the noise power to a quarter, so the signal-to-noise ratio rises by about 20log⁡102≈620\log_{10}2 \approx 6 dB.

Grouping decides how many weights share one ss. One scale for the whole tensor is the cheapest, but a single outlier inflates ss and squeezes all the other weights into a handful of integer levels. With one scale per gg weights, an outlier only affects its own group. The price is one extra 16-bit scale per group (plus a zero point for asymmetric quantization), so 4 bits with g=128g=128 is an “effective bit-width” of 4+16/128=4.1254 + 16/128 = 4.125 bits. The common GPTQ and AWQ configuration is exactly 4 bits with group size 128.

Try it: bit-width, groups and outliers

The data in the widget are 1024 standard normal random numbers with a fixed seed. They are illustrative data, not the weights of a real model; real weights have heavier tails and more outliers. Things to try:

  1. Each extra bit adds about 6 dB of SNR. For symmetric, whole-tensor quantization, the SQNR at 2 to 8 bits is 1.1, 9.6, 16.9, 23.5, 29.8, 35.6 and 42.1 dB. Two-bit symmetric has only the three levels −1,0,1-1, 0, 1 and is nearly unusable.
  2. One outlier can ruin whole-tensor quantization. Tick “Insert one outlier (20 standard deviations)”. At 4 bits with a whole-tensor scale, SQNR falls from 16.9 dB to 3.7 dB (all other weights are squeezed into a few levels). With group size 128 it is 11.6 dB, with 64 it is 14.7 dB and with 16 it is 19.1 dB (the effective bit-width rises to 5.0). This is why 4-bit weight quantization uses groups, and it is the starting point of LLM.int8(), which pulls the outlier dimensions of the activations out and computes them separately in 16 bits.
  3. Asymmetric is slightly more accurate for a little extra storage. At 4 bits, g=128g=128, no outlier: symmetric 18.1 dB (4.125 bits), asymmetric 19.6 dB (4.156 bits).
  4. Look at the size. The BF16 weights of a 7B model are 14 GB; 4-bit symmetric with g=128g=128 is about 3.6 GB (4.125×7×109÷84.125 \times 7\times10^9 \div 8 bytes).

Hands-on: Four Experiments on Qwen2.5-0.5B

The four experiments use the same model: Qwen2.5-0.5B (24 layers, hidden size 896, 14 attention heads with 2 KV heads, weights released in BF16). The metric is perplexity: the exponential of the average negative log-likelihood on the first 40 windows of 512 tokens of the WikiText-2 test set (20,480 tokens in all); lower is better. It is used because it is sensitive to quantization error and cheap to compute, but it is not the accuracy of a downstream task, so evaluate on your own tasks before going live. Small models are also more fragile under quantization than large ones (see the end of Experiment 1), so the absolute numbers here are pessimistic; the relative trends are the point.

All experiments use fake quantization: the weights are quantized to integers and immediately multiplied back by the scale to restore floating point, and then an ordinary floating-point matrix multiplication runs. This measures the accuracy loss of the algorithm itself, not speed, and does not depend on a particular GPU kernel; in a real deployment the weights are stored as integers and the kernel dequantizes them as it reads. Below, WxAy means x-bit weights and y-bit activations; W8A16 is INT8 weight-only quantization.

First load the model, define perplexity, and back up the 168 linear layers to be quantized (the embedding and the output layer are tied and are left as they are):

import math

import pandas as pd
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer

dev = "mps" if torch.backends.mps.is_available() else "cpu"
name = "Qwen/Qwen2.5-0.5B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
model = model.to(dev).eval()


def wikitext(split):
    path = hf_hub_download(
        "Salesforce/wikitext",
        f"wikitext-2-raw-v1/{split}-00000-of-00001.parquet",
        repo_type="dataset")
    return "".join(pd.read_parquet(path)["text"])


CTX = 512  # 512 tokens per window
ids = tok(wikitext("test"), return_tensors="pt").input_ids[0]
test = ids[:40 * CTX].view(40, CTX).to(dev)  # first 40 windows of the test set


@torch.no_grad()
def ppl(make_cache=None):
    """Perplexity: exp of the mean negative log-likelihood; lower is better."""
    nll = 0.0
    for x in test.split(4):
        kw = {}
        if make_cache:  # used by experiment 4: swap in a quantized KV cache
            kw = {"past_key_values": make_cache(), "use_cache": True}
        logits = model(x, **kw).logits[:, :-1].float()
        nll += F.cross_entropy(logits.reshape(-1, logits.size(-1)),
                               x[:, 1:].reshape(-1), reduction="sum").item()
    return math.exp(nll / (len(test) * (CTX - 1)))


# Quantize only the linear layers in the decoder blocks; the embedding
# (shared with the output head) stays as it is
names = [n for n, m in model.named_modules()
         if isinstance(m, nn.Linear) and ".layers." in n]
linears = [model.get_submodule(n) for n in names]
orig = [m.weight.data.clone() for m in linears]  # backup, restored per run
n_w = sum(w.numel() for w in orig)
n_all = sum(p.numel() for p in model.parameters())
n_emb = model.get_input_embeddings().weight.numel()
print(f"Total {n_all / 1e6:.0f}M parameters: linear layers "
      f"{n_w / 1e6:.0f}M, embedding {n_emb / 1e6:.0f}M (tied)")
print(f"BF16 storage: linear layers {n_w * 2 / 1e6:.0f} MB, "
      f"whole model {n_all * 2 / 1e6:.0f} MB")
print(f"Baseline (BF16 weights, FP32 compute): perplexity {ppl():.2f}")

Output:

Total 494M parameters: linear layers 358M, embedding 136M (tied)
BF16 storage: linear layers 716 MB, whole model 988 MB
Baseline (BF16 weights, FP32 compute): perplexity 16.25

The baseline perplexity is 16.25. Note that the embedding has 136M parameters, 28% of the whole model; we will come back to this.

Experiment 1: Bit-width and Granularity of Weights

The simplest method is called RTN (Round To Nearest): look at no data and quantize every weight directly with the formulas of the previous section. fake_quant is the code for those formulas; the grid combines bit-width (INT8, INT4, INT3) and granularity (whole tensor, per row, or one group per gg weights):

def fake_quant(w, bits, group):
    """Symmetric absmax quantization, then back to float.
    group: "tensor", "row" or an integer."""
    qmax = 2 ** (bits - 1) - 1
    if group == "tensor":
        g = w.reshape(1, -1)  # one scale for the whole tensor
    elif group == "row":
        g = w  # one per output channel (row)
    else:
        g = w.reshape(-1, group)  # one per `group` weights
    s = (g.abs().amax(dim=1, keepdim=True) / qmax).clamp(min=1e-8)
    return ((g / s).round().clamp(-qmax, qmax) * s).reshape(w.shape)


def n_scales(w, group):
    if group == "tensor":
        return 1
    return w.shape[0] if group == "row" else w.numel() // group


def set_weights(fn):  # fn(layer index, original weight) -> new weight
    for i, (m, w) in enumerate(zip(linears, orig)):
        m.weight.data = fn(i, w)


def eff_bits(bits, group):  # each scale takes 16 bits, spread over weights
    return bits + 16 * sum(n_scales(w, group) for w in orig) / n_w


grid = [(8, "tensor"), (8, "row"), (4, "tensor"), (4, "row"),
        (4, 128), (4, 64), (4, 32), (4, 16), (3, 128)]
for bits, group in grid:
    set_weights(lambda i, w: fake_quant(w, bits, group))
    eff = eff_bits(bits, group)
    print(f"INT{bits} {str(group):<7} effective bits {eff:5.3f}  "
          f"weights {n_w * eff / 8e6:4.0f} MB  perplexity {ppl():8.2f}")
set_weights(lambda i, w: w.clone())  # restore

# Why per-tensor INT4 collapses: the max dwarfs a typical weight, so most
# weights round to 0
r = torch.stack([w.abs().max() / w.abs().median() for w in orig])
print(f"max|w| / median|w| per layer: median {r.median():.0f}, "
      f"max {r.max():.0f}")
for group in ("tensor", "row", 128):
    z = [(fake_quant(w, 4, group) == 0).float().mean().item() for w in orig]
    print(f"INT4 {str(group):<7} share of weights rounded to 0: "
          f"{sum(z) / len(z):.1%}")

Output:

INT8 tensor  effective bits 8.000  weights  358 MB  perplexity    17.24
INT8 row     effective bits 8.014  weights  358 MB  perplexity    16.29
INT4 tensor  effective bits 4.000  weights  179 MB  perplexity 82798903.47
INT4 row     effective bits 4.014  weights  180 MB  perplexity    36.35
INT4 128     effective bits 4.125  weights  185 MB  perplexity    22.41
INT4 64      effective bits 4.250  weights  190 MB  perplexity    20.36
INT4 32      effective bits 4.500  weights  201 MB  perplexity    19.50
INT4 16      effective bits 5.000  weights  224 MB  perplexity    18.08
INT3 128     effective bits 3.125  weights  140 MB  perplexity   223.43
max|w| / median|w| per layer: median 27, max 117
INT4 tensor  share of weights rounded to 0: 74.3%
INT4 row     share of weights rounded to 0: 26.4%
INT4 128     share of weights rounded to 0: 19.7%
  1. INT8 is nearly lossless, provided the scales are per row (or finer). With one scale per row, perplexity is 16.29, only 0.04 above the baseline; with a single scale for the whole tensor it rises to 17.24 (up 6%), because a few rows of weights are especially large and inflate the scale of the whole tensor.
  2. Per-tensor INT4 collapses completely, to perplexity 8×1078\times10^{7}, more than 500 times worse than guessing uniformly from the vocabulary (whose perplexity equals the vocabulary size, 151,936). The end of the output shows why: the median over layers of max⁡∣w∣/median∣w∣\max|w|/\mathrm{median}|w| is 27; INT4 has only the 15 levels from −7-7 to 77, the scale is s=max⁡∣w∣/7s=\max|w|/7, and every weight whose magnitude is below s/2s/2 is rounded to 0. With one scale per tensor, 74.3% of the weights become 0 on average, with one scale per row 26.4%, and with one scale per 128 weights 19.7%.
  3. Grouping trades storage for accuracy, with diminishing returns. Reducing the group size from 128 to 64, 32 and 16 gives effective bit-widths of 4.125, 4.25, 4.5 and 5.0 bits and perplexities of 22.41, 20.36, 19.50 and 18.08; the gap to the baseline shrinks from 6.16 to 4.11, 3.25 and 1.83. The three steps cost 0.125, 0.25 and 0.5 extra bits and lower perplexity by 2.05, 0.86 and 1.42; per extra bit that is 16.4, 3.4 and 2.8, so the first bit of storage spent is the best value.
  4. RTN is unusable at 3 bits. INT3 with group size 128 gives 223.43. Going lower needs the calibration methods of Experiment 3.
  5. Small models are more fragile. The GPTQ paper observed on OPT and BLOOM that at the same bit-width, larger models are generally easier to quantize (OPT-66B is an exception): 4-bit RTN raises the perplexity of OPT-175B from 8.34 to 10.54 and that of OPT-1.3B from 14.63 to 48.17 (the paper’s RTN is asymmetric quantization with one scale per row, not exactly the symmetric quantization used here). The 0.5B model on this page is at the harder end.

Not Every Layer Is Equally Sensitive

Beneath the overall numbers, layers differ in sensitivity. Below, each run quantizes only one kind of linear layer (or a few layers) to INT4 with group size 128 and leaves the rest alone; at the end we look at the embedding:

# Sensitivity: quantize one kind of linear layer to INT4 g128 at a time
for kind in ("q_proj", "k_proj", "v_proj", "o_proj",
             "gate_proj", "up_proj", "down_proj"):
    set_weights(lambda i, w: fake_quant(w, 4, 128)
                if names[i].endswith(kind) else w.clone())
    print(f"only {kind:<9} perplexity {ppl():.2f}")

# By depth: quantize only a few layers
for lo, hi in ((0, 4), (10, 14), (20, 24)):
    set_weights(lambda i, w: fake_quant(w, 4, 128)
                if lo <= int(names[i].split(".")[2]) < hi else w.clone())
    print(f"only layers {lo}-{hi - 1}  perplexity {ppl():.2f}")

# The embedding (shared with the output head) is usually left alone:
# what if we quantize it, and how much smaller is the whole model?
set_weights(lambda i, w: fake_quant(w, 4, 128))
emb = model.get_input_embeddings().weight
emb_orig = emb.data.clone()
print(f"INT4 g128 linears, embedding untouched: perplexity {ppl():.2f}")
emb.data = fake_quant(emb_orig, 4, 128)
print(f"INT4 g128 linears and embedding: perplexity {ppl():.2f}")
emb.data = emb_orig
set_weights(lambda i, w: w.clone())
size = n_w * eff_bits(4, 128) / 8 + (n_all - n_w) * 2  # bytes
print(f"INT4 g128 linears, rest BF16: whole model {size / 1e6:.0f} MB, "
      f"{size / (n_all * 2):.0%} of BF16")

Output:

only q_proj    perplexity 16.37
only k_proj    perplexity 16.38
only v_proj    perplexity 16.89
only o_proj    perplexity 16.67
only gate_proj perplexity 16.85
only up_proj   perplexity 17.29
only down_proj perplexity 17.88
only layers 0-3  perplexity 17.76
only layers 10-13  perplexity 16.66
only layers 20-23  perplexity 17.87
INT4 g128 linears, embedding untouched: perplexity 22.41
INT4 g128 linears and embedding: perplexity 24.71
INT4 g128 linears, rest BF16: whole model 457 MB, 46% of BF16
  1. By type, baseline 16.25: q_proj and k_proj are the least sensitive (up 0.12 and 0.13), o_proj is up 0.42, gate_proj 0.60, v_proj 0.64, up_proj 1.04, and down_proj is the most sensitive, up 1.63.
  2. By depth, the first 4 layers are up 1.51, the last 4 layers up 1.62 and the 4 middle layers only 0.41. The layers at both ends are more sensitive.
  3. The embedding is a sizeable share. With the linear layers in INT4 g128 and the embedding left in BF16, the whole model takes 457 MB, 46% of BF16 rather than 25%. Quantizing the embedding (tied to the output layer) to INT4 g128 as well raises perplexity from 22.41 to 24.71. In a 0.5B model the embedding is 28% of the parameters; in Llama-3-8B the embedding and the output layer together are only 13%, so quantizing larger models comes closer to “4 times smaller”.
  4. The practical consequence is mixed precision: keep the sensitive parts (the first and last layers, down_proj, the embedding and the output layer) at a higher bit-width and use 4 bits for the insensitive parts.

Experiment 2: Why Activations Are Harder to Quantize

Weights are fixed once training ends, so quantizing them only requires looking at the weights themselves. Activations change with the input, and their quantization has to cope with whatever values appear at run time. Below we first look at the inputs of the linear layers in layer 12 (q/k/v share one input, and so do gate/up), then compare three settings: weight-only quantization (W8A16), and INT8 for both weights and activations with the activation scale either per tensor or per token (W8A8, dynamic quantization, the scale computed afresh on each forward pass):

def act_quant(x, per_token):
    """INT8 dynamic activation quantization: one scale per tensor, or one
    per token."""
    s = x.abs().amax(dim=-1, keepdim=True) if per_token else x.abs().amax()
    s = (s / 127).clamp(min=1e-8)
    return (x / s).round().clamp(-127, 127) * s


# 1) What activations look like: inputs of layer 12's linears (one window)
which = {"q/k/v": "self_attn.q_proj", "o": "self_attn.o_proj",
         "gate/up": "mlp.gate_proj", "down": "mlp.down_proj"}
seen, hooks = {}, []
for key, sub in which.items():
    layer = model.get_submodule(f"model.layers.12.{sub}")
    hooks.append(layer.register_forward_pre_hook(
        lambda mod, args, key=key: seen.__setitem__(key, args[0][0].abs())))
with torch.no_grad():
    model(test[:1])
for h in hooks:
    h.remove()
for key, a in seen.items():  # a: magnitudes, 512 tokens x channels
    med = a.median(0).values  # each channel's median over the 512 tokens
    top = med.argmax().item()  # channel with the largest median
    share = (a.argmax(1) == top).float().mean().item()
    tk, ch = divmod(a.argmax().item(), a.size(1))  # position of the max
    print(f"{key:<8} median of all {a.median():.3f}; "
          f"median of per-token max {a.amax(1).median():.2f}")
    print(f"{'':<8} max {a.max():.1f}: token {tk}, channel {ch}; "
          f"that channel's median {med[ch]:.2f}")
    print(f"{'':<8} largest-median channel {top}: {med[top]:.2f}; "
          f"the max of {share:.0%} of tokens")

# 2) INT8 weights (one scale per row) + INT8 activations: tensor vs token
set_weights(lambda i, w: fake_quant(w, 8, "row"))
print(f"W8A16 (weights only)       perplexity {ppl():.2f}")
for per_token in (False, True):
    hooks = [m.register_forward_pre_hook(
        lambda mod, args: (act_quant(args[0], per_token),))
        for m in linears]
    print(f"W8A8 (activations per {'token' if per_token else 'tensor'})"
          f"  perplexity {ppl():.2f}")
    for h in hooks:
        h.remove()
set_weights(lambda i, w: w.clone())

Output:

q/k/v    median of all 0.454; median of per-token max 11.88
         max 39.2: token 0, channel 62; that channel's median 0.74
         largest-median channel 646: 9.36; the max of 44% of tokens
o        median of all 0.138; median of per-token max 1.72
         max 5.2: token 439, channel 2; that channel's median 0.46
         largest-median channel 14: 0.67; the max of 5% of tokens
gate/up  median of all 0.431; median of per-token max 11.06
         max 26.6: token 0, channel 62; that channel's median 0.49
         largest-median channel 570: 9.69; the max of 58% of tokens
down     median of all 0.047; median of per-token max 1.55
         max 7.8: token 445, channel 961; that channel's median 0.05
         largest-median channel 1671: 0.49; the max of 0% of tokens
W8A16 (weights only)       perplexity 16.29
W8A8 (activations per tensor)  perplexity 111.78
W8A8 (activations per token)  perplexity 16.75
  1. Activations have two kinds of large values. The first kind sits in fixed channels: in the input of q/k/v (the output of the RMSNorm), channel 646 has a median magnitude of 9.36, 21 times the overall median of 0.454, and it is the largest entry in 44% of the tokens; in the input of gate/up, channel 570 behaves the same way (median 9.69, 58% of the tokens). These are the “outlier channels” that LLM.int8() and SmoothQuant talk about. The second kind is a spike on a single token: the maximum of the q/k/v input, 39.2, is at channel 62 of the first token (token 0), while the median of that channel over the window is only 0.74. Sun et al. (2024) call such extreme values far larger than the rest of the activations massive activations. The inputs of o and down have no channel this prominent in this layer (the channel with the largest median is below 0.7 and is the largest entry in only 5% and 0% of the tokens, respectively), but they are heavy-tailed too: the maximum of the down input, 7.8, is about 166 times its median of 0.047. This is an observation of one layer and one window; other layers differ in position and size.
  2. A per-tensor scale is set by the maximum. W8A16 gives 16.29, W8A8 with a per-tensor scale 111.78 and with a per-token scale 16.75. Take the q/k/v input: the per-tensor scale is s=39.2/127≈0.31s=39.2/127\approx0.31, so a typical element (0.454) spans only about 1.5 quantization steps; with per-token scales, the median over tokens of each token’s maximum is 11.88, s≈0.094s\approx0.094, and a typical element spans about 5 steps. A per-token scale removes the effect of the spike on token 0, but the large values in the fixed channels remain, so it eases the problem by a bit more than 3 times without removing it.
  3. Two industrial remedies. LLM.int8() (Dettmers et al., 2022) pulls out the few feature dimensions that contain outliers (the paper uses a threshold of 6.0; they make up about 0.1%) and computes them in 16 bits, quantizing the other 99.9% to 8 bits with vector-wise scales. SmoothQuant (Xiao et al., 2022) uses a mathematically equivalent transformation to migrate the outlier magnitudes of the activations to the weights channel by channel, sj=max⁡∣Xj∣α/max⁡∣Wj∣1−αs_j=\max|X_j|^{\alpha}/\max|W_j|^{1-\alpha}: the activations are divided by sjs_j and the weights multiplied by sjs_j, after which both are easy to quantize; the paper reports up to 1.56 times speed-up and 2 times memory reduction.

Experiment 3: Reducing the Error with Calibration Data

RTN looks only at the weights themselves, regardless of what inputs those weights will be multiplied with. What we really want to control is the output error of each layer. Let the weight of a layer be WW, the quantized weight W^\hat W, and XX the input of this layer on NN calibration tokens (d×Nd\times N). Then

∥(W−W^)X∥F2=tr(ΔW H ΔW⊤),H=XX⊤,ΔW=W−W^\|(W-\hat W)X\|_F^2=\mathrm{tr}\big(\Delta W\,H\,\Delta W^{\top}\big),\qquad H=XX^{\top},\quad \Delta W=W-\hat W

HH is a second-order statistic of the input (for this least-squares objective it differs from the Hessian only by a constant factor; it is d×dd\times d and independent of the number of tokens). SmoothQuant, AWQ and GPTQ all estimate statistics of the input from a small batch of calibration data and quantize accordingly. The code below uses the first 64 windows of the training set (32,768 tokens, disjoint from the test set) to collect three things: HH of every layer, the mean magnitude of every input channel (used by AWQ) and its maximum magnitude (used by SmoothQuant):

train_ids = tok(wikitext("train")[:500_000], return_tensors="pt").input_ids[0]
calib = train_ids[:64 * CTX].view(64, CTX).to(dev)  # first 64 train windows
H = [torch.zeros(m.in_features, m.in_features, device=dev) for m in linears]
amean = [torch.zeros(m.in_features, device=dev) for m in linears]
amax = [torch.zeros(m.in_features, device=dev) for m in linears]


def collect(i):
    def hook(mod, args):
        x = args[0].reshape(-1, mod.in_features)
        H[i] += x.T @ x  # second-order statistic: sum of x xᵀ
        amean[i] += x.abs().sum(0)  # mean magnitude per input channel (sum)
        amax[i] = torch.maximum(amax[i], x.abs().amax(0))  # max magnitude
    return hook


hooks = [m.register_forward_pre_hook(collect(i))
         for i, m in enumerate(linears)]
with torch.no_grad():
    for x in calib.split(4):
        model(x)
for h in hooks:
    h.remove()
for i in range(len(linears)):
    H[i] /= calib.numel()
    amean[i] /= calib.numel()
print(f"Calibration: {len(calib)} windows, {calib.numel()} tokens; "
      f"Hessians take {sum(h.numel() for h in H) * 4 / 1e9:.1f} GB")

Output:

Calibration: 64 windows, 32768 tokens; Hessians take 2.7 GB

First, SmoothQuant to fix the problem of Experiment 2. Below, every linear layer is smoothed by sjs_j, the weights still use INT8 with a scale per row, the activations use a per-tensor INT8 scale (computed afresh on each forward pass), and we sweep α\alpha:

def smooth(alpha):
    """SmoothQuant: migrate the activation outliers to the weights, channel
    by channel, with a mathematically equivalent transform."""
    scales = []

    def one(i, w):
        w_max = w.abs().amax(0).clamp(min=1e-5)  # max weight per input channel
        s = (amax[i].clamp(min=1e-5) ** alpha / w_max ** (1 - alpha))
        scales.append(s.clamp(min=1e-5))
        return fake_quant(w * scales[-1], 8, "row")  # scale weights, quantize

    set_weights(one)
    return scales


for alpha in (0.3, 0.5, 0.7, 0.8, 0.9, 1.0):
    scales = smooth(alpha)
    hooks = [m.register_forward_pre_hook(  # divide activations by s, then
        lambda mod, args, i=i: (act_quant(args[0] / scales[i], False),))
        for i, m in enumerate(linears)]  # quantize them per tensor
    print(f"SmoothQuant alpha={alpha}: W8A8 (per-tensor activations) "
          f"perplexity {ppl():.2f}")
    for h in hooks:
        h.remove()
set_weights(lambda i, w: w.clone())

Output:

SmoothQuant alpha=0.3: W8A8 (per-tensor activations) perplexity 96.26
SmoothQuant alpha=0.5: W8A8 (per-tensor activations) perplexity 25.10
SmoothQuant alpha=0.7: W8A8 (per-tensor activations) perplexity 18.76
SmoothQuant alpha=0.8: W8A8 (per-tensor activations) perplexity 18.12
SmoothQuant alpha=0.9: W8A8 (per-tensor activations) perplexity 18.57
SmoothQuant alpha=1.0: W8A8 (per-tensor activations) perplexity 19.21
  1. Smoothing rescues whole-tensor INT8 W8A8. Without it the perplexity is 111.78; with α=0.8\alpha=0.8 it falls to 18.12, only 1.83 above the 16.29 of W8A16.
  2. α\alpha is a knob with a sweet spot. If α\alpha is too small, the large activation values are not tamed (96.26 at 0.3, 25.10 at 0.5); if it is too large, all the difficulty is pushed onto the weights (19.21 at 1.0). The best value here is 0.8. The paper uses α=0.5\alpha=0.5 as the default for OPT and BLOOM and 0.75 for GLM-130B, whose activations are harder to quantize, and suggests a grid search on a small batch of data. The optimum for this model differs from the paper’s default, so search for it on your own model.
  3. A whole-tensor scale is the cheapest option. The paper treats the scheme in which weights and activations both use whole-tensor scales, with the activation scale fixed in advance from calibration data (O3), as its most efficient configuration, which is why smoothing is worth the trouble. If you can afford to compute the maximum per token at run time, smoothing helps less (Exercise 5).

Now low-bit weight quantization: AWQ and GPTQ. They address the weight error of INT4 and INT3.

AWQ (Activation-aware Weight Quantization) starts from the idea that weights are not equally important: if the activations of input channel jj are large, the weight error in that channel is amplified. Multiplying the weights of such a channel by sj>1s_j>1 before quantizing reduces their relative error, and dividing the input by sjs_j keeps the result mathematically equivalent (in a real implementation 1/sj1/s_j is folded into the previous operator). The paper takes s=sXαs=s_X^{\alpha}, where sXs_X is the mean activation magnitude of the channel, searches α\alpha on a grid over [0,1][0,1] for the smallest output error, and also clips the weights. The awq below is a simplified teaching version: it searches layer by layer independently, with 11 grid points, and does no clipping.

def rtn(w, H, a, bits, group):  # same signature for all; only AWQ uses a
    return fake_quant(w, bits, group)


def awq(w, H, a, bits, group):
    """AWQ style: scale up input channels by activation magnitude before
    quantizing; search the exponent alpha that minimizes the output error."""
    best = (float("inf"), None)
    for alpha in [i / 10 for i in range(11)]:  # alpha=0 is plain RTN
        s = a.clamp(min=1e-5) ** alpha
        s = s / (s.max() * s.min()).sqrt()
        wq = fake_quant(w * s, bits, group) / s
        d = w - wq
        err = ((d @ H) * d).sum().item()  # output error tr(d H dᵀ) on calib
        best = min(best, (err, wq), key=lambda t: t[0])
    return best[1]


def evaluate(tag, fn, bits, group):
    rel = []

    def one(i, w):
        wq = fn(w, H[i], amean[i], bits, group)
        d = w - wq
        rel.append((((d @ H[i]) * d).sum() / ((w @ H[i]) * w).sum()).item())
        return wq

    set_weights(one)
    print(f"{tag:<5} INT{bits} g{group}  relative output error "
          f"{sum(rel) / len(rel):.4f}  perplexity {ppl():.2f}")


for bits in (4, 3):
    for tag, fn in (("RTN", rtn), ("AWQ", awq)):
        evaluate(tag, fn, bits, 128)
set_weights(lambda i, w: w.clone())

Output:

RTN   INT4 g128  relative output error 0.0151  perplexity 22.41
AWQ   INT4 g128  relative output error 0.0111  perplexity 20.16
RTN   INT3 g128  relative output error 0.0742  perplexity 223.43
AWQ   INT3 g128  relative output error 0.0574  perplexity 75.18

GPTQ quantizes the weights column by column: after each column is quantized, its quantization error is compensated onto the not-yet-quantized columns according to H−1H^{-1}. Concretely, take the Cholesky factorization of H−1H^{-1} to get an upper-triangular matrix UU (H−1=U⊤UH^{-1}=U^{\top}U); the quantization error of column jj is ej=(wj−qj)/Ujje_j=(w_j-q_j)/U_{jj}, and every later column k>jk>j is updated as wk←wk−ejUjkw_k\leftarrow w_k-e_jU_{jk}. The paper has three engineering tricks: all rows share the same column order, so H−1H^{-1} is computed only once; the updates are done lazily in blocks of 128 columns, which improves the ratio of computation to memory access; and 1% of the average diagonal value is added to the diagonal as damping for numerical stability. Below is an implementation of under 30 lines, with the block size equal to the group size, 128, computed in float64 on the CPU:

def gptq(w, H, a, bits, group, damp=0.01):
    """GPTQ: quantize column by column and spread each column's error over
    the columns not yet quantized, weighted by the inverse of H."""
    w, H = w.cpu().double(), H.cpu().double()
    n = w.shape[1]
    dead = H.diag() == 0  # input channels that never fired
    H[dead, dead] = 1
    w[:, dead] = 0
    H += damp * H.diag().mean() * torch.eye(n, dtype=H.dtype)  # damping
    L = torch.linalg.cholesky(H)
    Hinv = torch.cholesky_solve(torch.eye(n, dtype=H.dtype), L)
    U = torch.linalg.cholesky(Hinv, upper=True)  # Cholesky factor of H⁻¹
    qmax = 2 ** (bits - 1) - 1
    q = torch.zeros_like(w)
    for i1 in range(0, n, group):  # block size = group size
        i2 = i1 + group
        s = (w[:, i1:i2].abs().amax(1) / qmax).clamp(min=1e-8)
        err = torch.zeros(w.shape[0], group, dtype=w.dtype)
        for j in range(group):
            col, d = w[:, i1 + j], U[i1 + j, i1 + j]
            q[:, i1 + j] = (col / s).round().clamp(-qmax, qmax) * s
            err[:, j] = (col - q[:, i1 + j]) / d
            w[:, i1 + j:i2] -= err[:, j:j + 1] * U[i1 + j, i1 + j:i2]
        w[:, i2:] -= err @ U[i1:i2, i2:]  # push the block's error onward
    return q.float().to(dev)


for bits in (4, 3):
    evaluate("GPTQ", gptq, bits, 128)
set_weights(lambda i, w: w.clone())

Output:

GPTQ  INT4 g128  relative output error 0.0055  perplexity 18.40
GPTQ  INT3 g128  relative output error 0.0286  perplexity 47.01

RTN, AWQ and GPTQ side by side (group size 128, baseline 16.25):

MethodINT4 relative output errorINT4 perplexityINT3 relative output errorINT3 perplexity
RTN0.015122.410.0742223.43
AWQ-style0.011120.160.057475.18
GPTQ0.005518.400.028647.01
  1. The ranking by output error matches the ranking by perplexity: RTN, AWQ, GPTQ get better in that order. At INT4, GPTQ cuts the gap to the baseline from 6.16 to 2.15 (a 65% reduction) and the teaching version of AWQ to 3.91.
  2. Calibration is like saving bits. The perplexity of GPTQ at 4.125 bits (18.40) is close to what RTN without calibration needs 5 bits for (group size 16, 18.08).
  3. Three bits is still a stretch. Calibration pulls INT3 back from collapse (223) to 75 and 47, still far from the baseline of 16.25 and unusable on a 0.5B model. A larger model, smaller groups, or keeping the sensitive layers at a higher bit-width is the practical way out.
  4. This is the teaching version, not the full result of the papers. The teaching version of AWQ searches ss for each linear layer independently; in a real implementation, layers that share an input (q/k/v, gate/up) must share one ss because 1/s1/s is folded into the previous RMSNorm, so the effect is slightly worse than here, and the paper adds a weight-clipping step. The calibration set for GPTQ has only 64 windows and comes from the same WikiText as the test set; with data from a very different domain the gain shrinks. The AWQ paper stresses that it uses only the mean activation magnitude, depends little on the calibration set and does not overfit easily.
  5. The costs differ. RTN needs no data; AWQ needs only statistics of the activations and its search is cheap; GPTQ must store the HH of every layer (2.7 GB in total on this page), do Cholesky factorizations and run a serial loop over columns, which makes it much slower (the slowest step of the experiments on this page).

Experiment 4: KV-Cache Quantization

The KV cache grows linearly with context length and concurrency (see the budget at the start). Qwen2.5-0.5B uses GQA with only 2 KV heads, so each token takes only 12,288 bytes, and a single 32K-token sequence still takes 403 MB, about 41% of the BF16 weights (988 MB). Below, the K and V written to the cache are quantized to INT8 or INT4. By default there is one scale per token and per head (shared by 64 numbers); for K we also try per-channel scales: one scale per channel and per 32 tokens, which is the treatment of K in the KIVI paper (Liu et al., 2024).

from transformers import DynamicCache

cfg = model.config
head_dim = cfg.hidden_size // cfg.num_attention_heads
per_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * head_dim * 2
print(f"KV cache per token: {per_token} bytes (BF16); "
      f"one 32K-token sequence {per_token * 32768 / 1e6:.0f} MB")


def kv_quant(x, bits, per_channel=False, g=32):
    """x: (batch, heads, seq, 64). Default: one scale per token and head.
    per_channel: one scale per channel per g tokens (KIVI's way for K)."""
    b, h, n, d = x.shape
    if per_channel:
        x = x.reshape(b, h, n // g, g, d).transpose(3, 4)
    q = fake_quant(x.reshape(-1, x.size(-1)), bits, "row").reshape(x.shape)
    return q.transpose(3, 4).reshape(b, h, n, d) if per_channel else q


def kv_cache(k_bits, k_chan, v_bits):
    class QuantCache(DynamicCache):
        def update(self, k, v, layer_idx, cache_kwargs=None):
            if k_bits < 16:  # 16 means leave as is
                k = kv_quant(k, k_bits, k_chan)
            if v_bits < 16:
                v = kv_quant(v, v_bits)
            return super().update(k, v, layer_idx, cache_kwargs)

    return QuantCache


cases = [(16, False, 16), (8, False, 8), (4, False, 4), (4, False, 16),
         (16, False, 4), (8, True, 8), (4, True, 4)]
for k_bits, k_chan, v_bits in cases:
    tag = "K " + ("as is" if k_bits == 16 else
                  f"INT{k_bits}{' per channel' if k_chan else ''}")
    tag += ", V " + ("as is" if v_bits == 16 else f"INT{v_bits}")
    print(f"{tag}: perplexity {ppl(kv_cache(k_bits, k_chan, v_bits)):.2f}")

Output:

KV cache per token: 12288 bytes (BF16); one 32K-token sequence 403 MB
K as is, V as is: perplexity 16.25
K INT8, V INT8: perplexity 16.95
K INT4, V INT4: perplexity 62.46
K INT4, V as is: perplexity 59.62
K as is, V INT4: perplexity 16.51
K INT8 per channel, V INT8: perplexity 16.26
K INT4 per channel, V INT4: perplexity 18.00
  1. INT8 depends on how K is quantized. With per-token scales for both K and V, INT8 gives perplexity 16.95 (up 0.70); with K per channel, INT8 is nearly lossless (16.26).
  2. At INT4, almost all the error comes from K. Quantizing only V to INT4 gives 16.51 (up 0.26); quantizing only K to INT4 gives 59.62; per-token scales for both give 62.46, which is unusable.
  3. Per-channel scales for K largely solve the problem. With K per channel and V per token, both at INT4, perplexity is 18.00. This is the same observation as KIVI: K should be quantized per channel, V per token.
  4. The price. The per-channel scale has one factor per 32 tokens, so the effective bit-width of K is 4.5 bits against 4.25 for per-token; and a group of tokens has to accumulate before it can be quantized, which KIVI handles by keeping the most recent tokens in a full-precision buffer. This experiment writes the whole window at once and does not simulate that, so the per-channel numbers are a little optimistic.

Putting the Results Together

Qwen2.5-0.5B weight quantization: bit-width vs perplexity The x-axis is the effective bit-width including scales; the y-axis is perplexity on a log scale. RTN falls as the group size shrinks; at group size 128 both the AWQ-style method and GPTQ beat RTN, with GPTQ lowest. At 3 bits RTN is off the chart and the calibrated methods remain far above baseline. 20 30 50 100 3 3.5 4 4.5 5 Effective bits per weight (including scales) Perplexity (log scale, lower is better) BF16 baseline 16.25 per row g128 g64 g32 g16 RTN INT3: 223.43 (off the chart) per-tensor INT4: 8.3×10⁷ (off the chart) RTN AWQ-style GPTQ
Effective bit-width vs perplexity for weight-only quantization of Qwen2.5-0.5B (first 40 windows of the WikiText-2 test set, log-scale y-axis). The blue line is RTN: per-row scaling, then group sizes 128, 64, 32 and 16 from left to right. The AWQ-style method and GPTQ were run at group size 128 only. Per-tensor INT4 and 3-bit RTN lie above the top edge; their values are printed next to the arrows. INT8, activation and KV-cache results are in the table below.
SchemeWhat is quantizedEffective bitsPerplexityGap to baseline
BF16 baselinenothing1616.250
INT8, per-row RTNweights8.01416.290.04
INT4, g128, RTNweights4.12522.416.16
INT4, g128, AWQ-styleweights4.12520.163.91
INT4, g128, GPTQweights4.12518.402.15
INT3, g128, GPTQweights3.12547.0130.76
W8A8, per-token activationsweights and activations816.750.50
W8A8, SmoothQuant (α=0.8), per-tensor activationsweights and activations818.121.87
KV: K and V both INT8, per tokenKV cache8.2516.950.70
KV: K per channel, V per token, both INT4KV cacheK 4.5, V 4.2518.001.75

Choosing and Shipping

Identify the Bottleneck First

Your bottleneckDo this firstEvidence
The weights do not fit, or decode is slow (memory-bound)Weight quantization: INT8 first (per-row scales); if that is not enough, INT4 g128 calibrated with AWQ or GPTQExperiments 1 and 3: INT8 is nearly lossless, INT4 needs groups and calibration, small models are more fragile
The KV cache is too small for high concurrency or long contextsKV-cache quantization (this page measures the algorithms with INT8 and INT4; in vLLM the counterpart is the FP8 KV cache), together with PagedAttentionExperiment 4 and the budget at the start: the KV cache decides concurrency; INT4 needs per-channel scales for K
Prefill or large batches are compute-boundW8A8 or FP8, with per-token activation scales or with SmoothQuant smoothing firstExperiments 2 and 3: outlier channels and spikes in the activations
Fine-tuning runs out of memoryQLoRA: freeze a 4-bit NF4 base model and train only LoRA adaptersThe QLoRA paper: a 65B model can be fine-tuned on a single 48 GB GPU
Quality dropped after quantization and you cannot tell whereGo back to INT8 for a baseline; measure sensitivity by layer type and depth; keep sensitive parts at a higher bit-widthThe sensitivity table after Experiment 1

Tools and Formats

NameUseNotes
bitsandbytesLLM.int8() and NF4 (the 4-bit data type of QLoRA)Quantizes on load, needs no calibration data
GPTQModel, AutoAWQProduce and load GPTQ- and AWQ-format quantized modelsBoth are weight-only (W4A16 and similar)
LLM CompressorA quantization library for vLLM deployment; supports FP8, INT8 W8A8, INT4 W4A16 and moreSee the vLLM documentation
llama.cpp (GGUF)A format and runtime for local inference, with many block-wise quantization typesSuited to laptops and edge devices
vLLMA serving framework that supports many weight-quantization formats; its quantized KV cache is mostly FP8 (--kv-cache-dtype fp8)Supported formats change between versions, so check its documentation (this page consulted the documentation of November 2026)

Symptoms, Causes and Actions

What you seeThe more likely problemA better action
Memory is saved but speed barely improvesNot too few bits, but a mismatched kernel, weak framework support, or the real bottleneck being the KV cache and schedulingCompare tokens/s under identical conditions, check GPU utilization, and confirm that the framework really supports the quantization format
Answer quality drops noticeably once 4 bits is onThe task is sensitive to precision, the calibration set is unsuitable, or some layers are especially fragileGo back to INT8 for a baseline, compare AWQ and GPTQ, keep sensitive layers at a higher bit-width, and look at the distribution of degradation on real business samples
The model is smaller but long contexts still run out of memoryWhat was compressed is the weights, while the KV cache, concurrency or request length is what blows upLimit context and concurrency, quantize the KV cache, and use PagedAttention with continuous batching
It looks worse but you cannot say where it brokeThere is no high-precision baseline, no fixed sample set and no way backKeep a high-precision baseline and a fixed evaluation set before arguing about whether quantization is better

A checklist before going live: a BF16 or FP16 baseline exists; the evaluation set contains your own task samples, not only perplexity and public benchmarks; memory, tokens/s and quality are recorded together; the versions of the quantization format and the serving framework are pinned; and there is a rollback path that can switch quickly back to the high-precision model.

Common Misconceptions

  1. Equating fewer bits with always faster. Weight quantization speeds up only the memory-bound decode and does less when the kernel does not match; prefill and large batches are compute-bound and need W8A8 or FP8.
  2. Looking only at perplexity or public benchmarks. Perplexity is sensitive to quantization but need not move together with your task; some models lose little on public benchmarks and still lose clearly on a vertical task.
  3. Ignoring what is being quantized. Weights, activations and the KV cache have different difficulties and benefits: weights need groups and calibration, activations have outlier channels and spikes, and in the KV cache K is more sensitive than V.
  4. Treating simulated quantization as a real deployment. Simulated quantization measures the accuracy loss of the algorithm; real kernels add details such as accumulation precision, data layout and fusion, so test again with the real format before going live.
  5. Having no rollback path. If quality becomes a problem after quantization is deployed, you should be able to switch back to the high-precision model quickly; otherwise troubleshooting is expensive.

Research example: vary KV cache precision across layers

Berkeley Scalable AI’s EchoKV project explores per-layer KV cache precision. A short high-precision reference helps track error, and a controller uses that signal to allocate bit widths. This makes precision an allocation problem under a memory budget and adds reference storage, error estimation, and switching costs.

Distinguish frozen and live protocols. Freezing assignments lets you compare output differences between uniform and per-layer precision at comparable memory budgets. Live operation calls for separate measurements of updates, switching, and end-to-end latency. The report identifies a separate live-controller benchmark as follow-up work. Use identical token trajectories to study local error, then let each configuration generate freely to measure how accumulated errors affect the task.

Summary and Exercises

Key points:

  1. Quantization pays off in three places: the memory taken by the weights, the bytes read per step (the speed limit of decode), and the KV cache (how many requests fit). The bottlenecks differ, so find yours before choosing a method. On an 80 GB card, Llama-3-8B fits about 52 sequences of 8K tokens in BF16; quantizing only the weights to INT4 gives 61, and also quantizing the KV cache to INT8 gives 121.
  2. Symmetric quantization uses s=max⁡∣x∣/(2b−1−1)s=\max|x|/(2^{b-1}-1) and the error is at most s/2s/2. A single outlier inflates ss, so 4-bit quantization uses groups; the effective bit-width is the number of bits plus 16 divided by the group size, 4.125 bits for group size 128.
  3. On Qwen2.5-0.5B, INT8 with a scale per row is nearly lossless (16.25 to 16.29); per-tensor INT4 collapses, and RTN with group size 128 reaches 22.41. Calibration methods bring the same 4.125 bits down to 20.16 (AWQ-style) and 18.40 (GPTQ), close to what RTN needs 5 bits for (group size 16, 18.08).
  4. Activations have large values in fixed channels and spikes on individual tokens: W8A8 with a per-tensor INT8 scale gives 111.78, and a per-token scale (16.75) or SmoothQuant (18.12) rescues it.
  5. In the KV cache, K is more sensitive than V: quantizing K per channel and V per token keeps INT4 at 18.00, while using per-token scales for both gives 62.46.
  6. Simulated quantization only measures the loss of the algorithm. Before going live, use the real kernels and formats, check memory, tokens/s and task quality together, and keep a way to roll back.

Quick quiz

1. A 70B-parameter model stores its weights in INT4 (group size 128, effective bit-width 4.125). Counting the weights only, how much memory do they take?

  • About 70 GB
  • About 36 GB
  • About 17.5 GB
  • About 140 GB

70×109×4.125/8≈3.6×101070\times10^{9}\times4.125/8\approx3.6\times10^{10} bytes, about 36 GB. 70 GB is the INT8 figure, 140 GB is BF16, and 17.5 GB is what 2 bits would need.

2. Per-tensor INT4 pushes perplexity to 8×1078\times10^{7}, while one scale per 128 weights gives 22.41. What is the main reason?

  • Per-tensor quantization uses fewer bits
  • The maximum in a tensor is far larger than a typical weight, so the scale is inflated and most weights round to 0
  • Per-tensor quantization cannot be converted back to floating point
  • Grouping adds trainable parameters

Both use 4 bits. In Experiment 1 the median over layers of max⁡∣w∣/median∣w∣\max|w|/\mathrm{median}|w| is 27; a per-tensor scale turns 74.3% of the weights into 0, against 19.7% with groups of 128.

3. In Experiment 2, W8A8 with a per-tensor activation scale gives perplexity 111.78 and a per-token scale gives 16.75. What does this show?

  • INT8 does not have enough bits; activations must use 16 bits
  • A few activation values are very large, so a per-tensor scale is set by the maximum and the other elements get only a few quantization steps; a per-token scale confines the damage to each row
  • Quantizing activations is easier than quantizing weights
  • Perplexity is insensitive to activation quantization error

The per-tensor scale is set by the maximum, 39.2, so a typical element (0.454) spans only about 1.5 quantization steps; with a per-token scale it spans about 5.

4. On an 80 GB card serving Llama-3-8B with 8K contexts, concurrency is limited by the KV cache. By the budget at the start, which action raises concurrency the most?

  • Quantize the weights from BF16 to INT4 (52 sequences become 61)
  • With INT4 weights, also quantize the KV cache from BF16 to INT8 (61 sequences become 121)
  • Increase the prefill batch size
  • Switch to memory with higher bandwidth

The number of concurrent sequences is the usable memory minus the weights, divided by the KV cache per sequence. Of the 72 GB usable, BF16 weights take 16 GB and INT4 frees only about 10 GB; halving the KV cache per sequence doubles the number of sequences that fit in the remaining 66 GB. Bandwidth affects speed, not capacity.

5. In Experiment 4, quantizing only K to INT4 (per-token scales) gives perplexity 59.62, and quantizing only V to INT4 gives 16.51. What is the most reasonable next step?

  • Give up on KV cache quantization
  • Change how K is quantized: per-channel scales, with V still per token (the KIVI recipe)
  • Raise V to INT8 and leave K alone
  • Use a larger calibration set

Almost all of the error comes from K, so changing V does not help. With K per channel and V per token, both at INT4, perplexity falls to 18.00.

6. What is the fundamental difference between GPTQ and RTN?

  • GPTQ uses more bits
  • GPTQ quantizes column by column and compensates each column’s quantization error onto the not-yet-quantized columns using H−1H^{-1}, so the layer’s output error is smaller
  • GPTQ retrains the whole model
  • GPTQ quantizes only activations

In Experiment 3, with INT4 and group size 128, RTN has a relative output error of 0.0151 and GPTQ 0.0055; perplexity is 22.41 against 18.40.

Exercises:

  1. Quantize x=(−0.30, 0.05, 0.12, 0.90)x=(-0.30,\,0.05,\,0.12,\,0.90) with symmetric INT4 (integer range −7-7 to 77): find ss, the integers qq, the restored values x^\hat x and the maximum absolute error. Then replace 0.90 with 0.30: what is the maximum error now, and what does that tell you?
  2. The KV cache of Qwen2.5-0.5B takes 12,288 bytes per token. How much memory do 8 concurrent sequences with 32K contexts need? And with the KV cache in INT8 (effective bit-width 8.25)? Compare with the BF16 weights (988 MB).
  3. The GPTQ code on this page stores one d×dd\times d float32 matrix HH for each of the 168 linear layers (dd is the layer’s input dimension: 4864 for down_proj, 896 for all the others). Write the expression for the total number of bytes, evaluate it, and say which kind of layer takes most of it.
  4. In Experiment 1, RTN with group size 16 uses 5.0 bits and reaches perplexity 18.08. Shrink the group size further to 8: predict the effective bit-width first, then run it, see how much perplexity improves, and compare with GPTQ (4.125 bits, 18.40).
  5. Combine SmoothQuant (with α=0.5\alpha=0.5) with dynamic per-token activation quantization: in q4b_smooth, change the False in act_quant(args[0] / scales[i], False) to True. Predict whether perplexity will be better or worse than per-token scaling alone (16.75) and how far from W8A16 (16.29) it will be, then run it to check.
  6. Why can AWQ’s scale ss be folded into the previous layer without extra inference cost? Why must q/k/v share the same ss?
Reference answers
  1. s=0.90/7≈0.1286s=0.90/7\approx0.1286, q=(−2,0,1,7)q=(-2,0,1,7), x^≈(−0.257,0,0.129,0.900)\hat x\approx(-0.257,0,0.129,0.900), errors (0.043,0.050,0.009,0)(0.043,0.050,0.009,0), so the maximum error is 0.050: the 0.05 was rounded to 0. With 0.30 instead of 0.90, s=0.30/7≈0.0429s=0.30/7\approx0.0429, q=(−7,1,3,7)q=(-7,1,3,7) and the maximum error is only 0.0086. The outlier tripled ss, so the error bound s/2s/2 tripled; in this example the actual maximum error grew about 5.8 times, and the small numbers were squeezed until they lost their resolution.
  2. One sequence takes 12,288×32,768≈4.03×10812{,}288\times32{,}768\approx4.03\times10^{8} bytes, about 403 MB; eight take 3.22 GB, 3.3 times the BF16 weights (988 MB). With INT8 (8.25/16) it falls to 1.66 GB. With long contexts and high concurrency, the KV cache is larger than the weights.
  3. The number of elements is 24×(6×8962+48642)=683,409,40824\times(6\times896^{2}+4864^{2})=683{,}409{,}408; at 4 bytes each that is 2.73 GB. The HH of down_proj takes 24×48642/683,409,408≈83%24\times4864^{2}/683{,}409{,}408\approx83\% of it: the size of HH is d2d^{2}, so a layer with 4864 inputs needs (4864/896)2≈29.5(4864/896)^{2}\approx29.5 times as much as a layer with 896. Letting layers that share an input share one HH (one for q/k/v, one for gate/up) only gets down to 2.50 GB, about 8% less.
  4. With group size 8 the effective bit-width is 4+16/8=6.04+16/8=6.0 bits. The measured perplexity is 17.68, only 0.40 better than group size 16 (18.08) for one more bit; GPTQ gets 18.40 with 4.125 bits, close to RTN at 5 bits (18.08). The gain from smaller groups diminishes, and calibration is another way to save bits.
  5. Measured: 16.38, which is 0.37 lower than per-token alone (16.75) and only 0.09 above W8A16 (16.29). Experiment 2 showed two kinds of large values: smoothing handles the fixed channels, the per-token scale handles the differences in magnitude between tokens, and together they do better.
  6. 1/sj1/s_j is just a per-channel scaling of the input channels, so it can be folded into the operator that produces that input: the per-channel weight gg of the RMSNorm becomes g/sg/s, or the output channels of the previous linear layer are multiplied by 1/s1/s. Inference gets no extra operator. q/k/v read the same RMSNorm output, which has only one g/sg/s, so the three linear layers must share the same ss. The teaching version searches ss for each layer independently and has no such constraint, so it is slightly optimistic compared with a real implementation.

Further Reading

  • The KV cache and the memory-bound decode step are the main beneficiaries of quantization: see KV Cache and Inference Performance. Another way to speed up decoding beyond reading fewer bytes is speculative decoding, and Efficient Attention: MQA, GQA, MLA and FlashAttention explains why GQA makes the KV cache smaller. For PagedAttention see the vLLM paper explainer.

  • Sources: Dettmers et al., LLM.int8(); Xiao et al., SmoothQuant; Frantar et al., GPTQ; Lin et al., AWQ; Dettmers et al., QLoRA; Liu et al., KIVI; Sun et al., Massive Activations in Large Language Models.

  • Engineering documentation: the Quantization section of the vLLM documentation (weight formats, the hardware support matrix and the FP8 KV cache; the version consulted for this page is from November 2026).

  • Paper explainer: QLoRA: how NF4 and double quantization are built, INT4 against FP4 against NF4 in weight error and perplexity on Qwen2.5, and the memory arithmetic for fine-tuning a 65B model.

  • Quantizing a 7B robot policy: 4-bit brings memory down to about 7 GB with no change in success rate, while 8-bit loses points because it runs slower: the OpenVLA breakdown.

  • FP8 inference for the 405B: only the feed-forward layers are quantized, scaling factors are capped, and the effect of quantization is checked with the reward-model score distribution rather than benchmark scores: see the Llama 3 breakdown.

  • Lin et al., QuaRot (2024) and Liu et al., SpinQuant (2024): rotation matrices “flatten” activation outliers, so 4-bit weight quantization no longer needs per-layer hand-tuning, pushing post-training quantization close to QAT quality.

  • Shao et al., OmniQuant (2023): learnable quantization ranges and weight clipping, sitting between PTQ and QAT.

  • Kuzmin et al., FP8 versus INT8 for efficient deep learning inference (2025) and Kuzmin et al., Scaling Laws for Precision (2024): a systematic comparison of integer and floating-point low-precision formats, and an attempt to fold precision itself into scaling laws.

FAQ

What is model quantization and why do it?
Quantization represents weights, activations or the KV cache with fewer bits (such as INT8 or INT4) to cut memory use and memory traffic. It brings three benefits: the model fits on a smaller GPU; the decode phase reads fewer bytes per step and so runs faster; and a smaller KV cache supports longer contexts or more concurrent requests. The cost is some loss of accuracy, and the speed-up depends on whether the inference kernels and hardware really support low-bit computation.
What is the difference between PTQ and QAT?
Post-training quantization (PTQ) quantizes a model after training is finished. It is cheap and easy to deploy and is the most common route for open models; GPTQ and AWQ are both PTQ. Quantization-aware training (QAT) simulates the quantization error during training so that the model gradually adapts to low-bit representations. It can reach better accuracy, but it is more complex and more expensive to train.
How do I choose between GPTQ and AWQ?
Both are weight-only post-training methods, usually used around 4 bits. GPTQ quantizes column by column and uses second-order information (the Hessian) to compensate the error onto the columns not yet quantized; AWQ uses activation magnitudes to find the important input channels and scales them up before quantizing, with no backpropagation. Measured on Qwen2.5-0.5B on this page (4 bits, group size 128), RTN reaches perplexity 22.41, the teaching version of AWQ 20.16 and GPTQ 18.40, against a baseline of 16.25. In practice the choice depends on whether your model has mature support, whether your serving framework is compatible and how sensitive your task is to accuracy, and you should verify it on your own samples.
Is a quantized model always faster?
No. Weight quantization mainly speeds up the memory-bound decode phase: the fewer bytes read per step, the faster it runs. Prefill is compute-bound, and quantizing only the weights usually does not help there. Speed also depends on whether the inference kernels and hardware support low-bit computation; with a mismatched kernel the gain can be small. Before going live, check memory, tokens per second and task quality together, and keep a path back to the higher-precision model.
Why does 4-bit quantization need groups, and how do I choose the group size?
When a whole tensor or a whole row shares one scale, a single outlier inflates the scale and squeezes the remaining weights into a few integer levels. Grouping confines an outlier to its own group, at the price of storing one extra scale per group: with group size 128 the effective bit-width is 4.125 bits. On Qwen2.5-0.5B, INT4 perplexity collapses to 8×10⁷ with a per-tensor scale, is 36.35 with one scale per row, and is 22.41, 20.36, 19.50 and 18.08 for group sizes 128, 64, 32 and 16 (baseline 16.25). A common compromise is 128.
Can activations and the KV cache be quantized too?
Yes, but it is harder than for weights. A few activation channels are far larger than the rest: with one INT8 scale per tensor, perplexity rises from 16.25 to 111.78, and with one scale per token it is 16.75. The KV cache in INT8 is nearly lossless; at INT4, K is much more sensitive than V, and quantizing K per channel brings perplexity from 62.46 down to 18.00 (all measured on Qwen2.5-0.5B).