TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Quantizing LLMs: int8, int4 and Outliers

Quantizing LLMs: int8, int4 and Outliers

A 7-billion-parameter model in 16-bit floats is 14 GB of weights before it has processed a single token. Generating text reads all of them for every new token (the next lesson shows why), so the size of the weights decides both which GPU the model fits on and how fast it runs. Quantization stores weights, and sometimes activations, in 8 or 4 bits instead of 16: half or a quarter of the memory and of the bytes moved per token.

QLoRA built the 4-bit NF4 code book and block-wise scaling from scratch for fine-tuning. This lesson is about quantization for inference: the integer formats themselves (absmax and zero-point), the granularity of the scales, the outlier features that break naive int8 in LLMs, error-aware rounding as in GPTQ, and what each choice does to the output of a matrix product, which is what the model actually computes. The float formats underneath (fp32, fp16, bf16) are in Floating Point.

Two integer maps

A bb-bit integer has 2b2^b levels. Quantization maps a real range onto them with a scale ss (and maybe an offset), rounds, and clips; dequantization maps back.

Absmax (symmetric) puts 0 at integer 0 and uses qmax⁡=2b−1−1q_{\max} = 2^{b-1} - 1 (127 for int8, 7 for int4):

s=max⁡j∣xj∣qmax⁡,qj=clip⁡ ⁣(round⁡ ⁣(xjs),−qmax⁡,qmax⁡),x^j=s qjs = \frac{\max_j \lvert x_j \rvert}{q_{\max}}, \qquad q_j = \operatorname{clip}\!\left(\operatorname{round}\!\left(\frac{x_j}{s}\right), -q_{\max}, q_{\max}\right), \qquad \hat{x}_j = s\, q_j

Zero-point (affine, asymmetric) maps [min⁡x,max⁡x][\min x, \max x] onto the unsigned range 0…2b−10 \dots 2^b - 1, with an integer zero-point zz that represents the real 0 exactly (so zero padding and ReLU zeros stay exact):

s=max⁡jxj−min⁡jxj2b−1,z=round⁡ ⁣(−min⁡jxjs),qj=clip⁡ ⁣(round⁡ ⁣(xjs)+z,0,2b−1),x^j=s (qj−z)s = \frac{\max_j x_j - \min_j x_j}{2^b - 1}, \qquad z = \operatorname{round}\!\left(\frac{-\min_j x_j}{s}\right), \qquad q_j = \operatorname{clip}\!\left(\operatorname{round}\!\left(\frac{x_j}{s}\right) + z, 0, 2^b - 1\right), \qquad \hat{x}_j = s\,(q_j - z)

The rounding error of each value is at most s2\frac{s}{2} (inside the range), so everything is about making ss small: the scale is set by the extreme values, and every other value pays for them.

python · try it yourself
import numpy as np

def absmax_quant(x, bits=8):
    qmax = 2 ** (bits - 1) - 1                    # 127 for int8
    s = np.abs(x).max() / qmax
    q = np.clip(np.round(x / s), -qmax, qmax)
    return q * s, s, 0

def affine_quant(x, bits=8):
    qmax = 2 ** bits - 1                          # 255 for uint8
    s = (x.max() - x.min()) / qmax
    z = int(np.round(-x.min() / s))               # the integer that represents 0.0
    q = np.clip(np.round(x / s) + z, 0, qmax)
    return (q - z) * s, s, z

rng = np.random.default_rng(0)
weights = rng.normal(0, 0.02, 10_000)                           # symmetric around 0
acts = np.maximum(rng.normal(0.5, 1.0, 10_000), 0) - 0.17      # GELU-like: mostly >= -0.17, long right tail

for name, x in [("weights", weights), ("activations", acts)]:
    print(f"{name}: range [{x.min():.3f}, {x.max():.3f}]")
    for bits in (8, 4):
        for qname, fn in [("absmax", absmax_quant), ("affine", affine_quant)]:
            xh, s, z = fn(x, bits)
            err = np.linalg.norm(x - xh) / np.linalg.norm(x)
            levels = len(np.unique(np.round(xh / s)))
            print(f"  int{bits} {qname:<6} scale {s:.5f} zero {z:>3}  levels used {levels:>3}  rel. error {err:.4f}")
weights: range [-0.078, 0.070]
  int8 absmax scale 0.00061 zero   0  levels used 207  rel. error 0.0089
  int8 affine scale 0.00058 zero 135  levels used 217  rel. error 0.0083
  int4 absmax scale 0.01114 zero   0  levels used  14  rel. error 0.1616
  int4 affine scale 0.00984 zero   8  levels used  16  rel. error 0.1431
activations: range [-0.170, 4.276]
  int8 absmax scale 0.03367 zero   0  levels used 114  rel. error 0.0088
  int8 affine scale 0.01743 zero  10  levels used 208  rel. error 0.0053
  int4 absmax scale 0.61079 zero   0  levels used   8  rel. error 0.1875
  int4 affine scale 0.29637 zero   1  levels used  16  rel. error 0.1101

For weights, which are roughly symmetric around 0, the two maps are close (int8 errors 0.0089 and 0.0083). For activations after a GELU-like nonlinearity, which range from −0.17-0.17 to 4.34.3, absmax wastes the whole negative half: it uses 114 levels of int8 against 208 for the affine map, and the int4 error drops from 0.1875 to 0.1101 with a zero-point. That is why weights are usually quantized symmetrically and activations often asymmetrically. Note also the cost of int4 itself: about 18 times the int8 error, because the step ss is 1277≈18\frac{127}{7} \approx 18 times larger.

Granularity: per tensor, per channel, per group

The scale does not have to be shared by the whole matrix. For a weight matrix W∈Rdout×dinW \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}} (one row per output channel, as in nn.Linear):

  • per tensor: one ss for all of WW;
  • per channel: one ss per output row; rows of different size no longer share a scale;
  • per group: one ss per block of gg consecutive inputs within a row (g=128g = 128 is the common choice for int4); an outlier spoils only its own group.

Each scale is stored in fp16, so the cost per weight is b+16gb + \frac{16}{g} bits for groups of gg. What matters is not the weight error but the error of the output Y=XW⊤Y = X W^\top. The example measures both on a synthetic matrix whose rows differ in size, with 20 large weights.

python · try it yourself
import numpy as np

def quantize(W, bits, group=None, axis_rows=False):
    """Symmetric absmax quantization with one scale per tensor, per row, or per group of `group` inputs."""
    qmax = 2 ** (bits - 1) - 1
    out_f, in_f = W.shape
    if group:                                            # (out, in/group, group): one scale per block
        blocks = W.reshape(out_f, in_f // group, group)
        s = np.abs(blocks).max(axis=2, keepdims=True) / qmax
        return (np.clip(np.round(blocks / s), -qmax, qmax) * s).reshape(out_f, in_f), s.size
    if axis_rows:                                        # per output channel
        s = np.abs(W).max(axis=1, keepdims=True) / qmax
    else:                                                # per tensor
        s = np.abs(W).max() / qmax
    return np.clip(np.round(W / s), -qmax, qmax) * s, np.size(s)

rng = np.random.default_rng(0)
out_f, in_f = 256, 512
row_scale = np.exp(rng.normal(0, 0.5, (out_f, 1)))       # output channels differ in size
W = rng.normal(0, 0.02, (out_f, in_f)) * row_scale
idx = rng.choice(W.size, 20, replace=False)              # a few large weights
W.flat[idx] = rng.choice([-1, 1], 20) * 0.4
X = rng.normal(0, 1, (64, in_f))                         # 64 tokens of activations
Y = X @ W.T

print(f"W {W.shape}, max |w| {np.abs(W).max():.2f}, typical |w| {np.median(np.abs(W)):.4f}")
print(f"{'scheme':<22} {'bits/weight':>11} {'W error':>8} {'Y error':>8}")
for bits in (8, 4):
    for name, kw in [("per-tensor", {}), ("per-channel", {"axis_rows": True}),
                     ("per-group 128", {"group": 128}), ("per-group 32", {"group": 32})]:
        Wq, n_scales = quantize(W, bits, **kw)
        bpw = bits + 16 * n_scales / W.size              # fp16 scales
        ew = np.linalg.norm(W - Wq) / np.linalg.norm(W)
        ey = np.linalg.norm(Y - X @ Wq.T) / np.linalg.norm(Y)
        print(f"int{bits} {name:<17} {bpw:>11.3f} {ew:>8.4f} {ey:>8.4f}")

print("\nweights of a 7e9-parameter model:")
for name, bpw in [("fp16", 16), ("int8 per-channel", 8.0), ("int4 group 128", 4.125), ("int4 group 32", 4.5)]:
    print(f"  {name:<17} {7e9 * bpw / 8 / 1e9:5.2f} GB")
W (256, 512), max |w| 0.40, typical |w| 0.0128
scheme                 bits/weight  W error  Y error
int8 per-tensor              8.000   0.0347   0.0343
int8 per-channel             8.031   0.0119   0.0118
int8 per-group 128           8.125   0.0079   0.0078
int8 per-group 32            8.500   0.0057   0.0057
int4 per-tensor              4.000   0.5586   0.5536
int4 per-channel             4.031   0.2007   0.1984
int4 per-group 128           4.125   0.1383   0.1367
int4 per-group 32            4.500   0.1027   0.1013

weights of a 7e9-parameter model:
  fp16              14.00 GB
  int8 per-channel   7.00 GB
  int4 group 128     3.61 GB
  int4 group 32      3.94 GB

At 8 bits every scheme is usable: per-channel cuts the per-tensor error from 0.0347 to 0.0119. At 4 bits the granularity decides everything: per tensor the output error is 0.5536 (useless), per channel 0.1984, groups of 128 give 0.1367 for an eighth of a bit more, groups of 32 give 0.1013 for half a bit more. With random inputs the output error tracks the weight error; with real, correlated activations it does not, which is what GPTQ exploits below.

The memory lines are the arithmetic behind the opening sentence: 7×1097 \times 10^9 weights take 7×109×27 \times 10^9 \times 2 bytes =14= 14 GB in fp16 (13.0 GiB), 7 GB in int8 and 7×109×4.1258=3.617 \times 10^9 \times \frac{4.125}{8} = 3.61 GB in int4 with groups of 128. Add the KV cache and activations on top (KV cache): a quantized 7B model fits a 6 GB consumer GPU only with a short context.

Outlier features: why int8 activations broke LLMs

Weight-only quantization keeps activations in 16 bits and dequantizes weights on the fly. To use fast int8 matrix units you have to quantize the activations too (W8A8). In large transformers this failed at first, and the reason was found by Dettmers et al. in LLM.int8() (2022): beyond a certain scale, a few feature dimensions of the hidden states carry values up to about 20 times larger than the rest, in most tokens (75% of the sequence positions at 6.7 billion parameters). With one scale per token, those few dimensions set ss, and the ordinary features fall on the few integer levels near 0.

The example plants 4 such columns (out of 512) at 40 times the normal size, then compares weight-only int8, W8A8 with per-token scales for XX and per-channel scales for WW, and the mixed-precision decomposition of LLM.int8(): columns containing any ∣x∣>6\lvert x \rvert > 6 are multiplied in 16-bit, all others in int8, and the two partial products are added.

XW⊤=X:,O W:,O⊤+X:,Oˉ W:,Oˉ⊤,O={j:max⁡t∣xtj∣>6}X W^\top = X_{:, O}\, W_{:, O}^\top + X_{:, \bar{O}}\, W_{:, \bar{O}}^\top, \qquad O = \{ j : \max_t \lvert x_{tj} \rvert > 6 \}
python · try it yourself
import numpy as np

def q8_rows(A):                    # int8 absmax, one scale per row (per token for X, per channel for W)
    s = np.abs(A).max(axis=1, keepdims=True) / 127
    return np.clip(np.round(A / s), -127, 127) * s

rng = np.random.default_rng(0)
tokens, d_in, d_out = 64, 512, 256
X = rng.normal(0, 1, (tokens, d_in))
outlier_cols = [17, 140, 301, 455]
X[:, outlier_cols] *= 40                     # a few feature dimensions are huge in every token
W = rng.normal(0, 0.02, (d_out, d_in))
Y = X @ W.T
rel = lambda Yh: np.linalg.norm(Y - Yh) / np.linalg.norm(Y)

print(f"|x| median {np.median(np.abs(X)):.2f}, max {np.abs(X).max():.1f}; "
      f"{len(outlier_cols)} of {d_in} columns hold {np.square(X[:, outlier_cols]).sum() / np.square(X).sum():.0%} of the energy")
print(f"weight-only int8 (W8, X in fp16):     error {rel(X @ q8_rows(W).T):.4f}")
print(f"weights + activations int8 (W8A8):    error {rel(q8_rows(X) @ q8_rows(W).T):.4f}")

# why: the per-token scale is set by the outliers, so the ordinary features lose their resolution
Xq = q8_rows(X)
normal = np.setdiff1d(np.arange(d_in), outlier_cols)
print(f"step size per token: {np.mean(np.abs(X).max(axis=1) / 127):.2f}; "
      f"ordinary activations rounded to 0: {np.mean(Xq[:, normal] == 0):.0%}")
Yn = X[:, normal] @ W[:, normal].T
print(f"error on the ordinary features' share of Y: {np.linalg.norm(Yn - Xq[:, normal] @ q8_rows(W)[:, normal].T) / np.linalg.norm(Yn):.4f}")

# LLM.int8()-style decomposition: columns with any |x| > 6 stay in 16-bit, the rest go through int8
big = np.abs(X).max(axis=0) > 6
Y_mixed = X[:, big] @ W[:, big].T + q8_rows(X[:, ~big]) @ q8_rows(W[:, ~big]).T
print(f"mixed: {big.sum()} outlier columns fp16, {(~big).sum()} int8: error {rel(Y_mixed):.4f}")

# without the outliers W8A8 is fine: the problem is the scale, not int8 itself
Xc = X.copy(); Xc[:, outlier_cols] /= 40
Yc = Xc @ W.T
print(f"W8A8 on the same X without outliers:  error {np.linalg.norm(Yc - q8_rows(Xc) @ q8_rows(W).T) / np.linalg.norm(Yc):.4f}")
|x| median 0.68, max 142.6; 4 of 512 columns hold 93% of the energy
weight-only int8 (W8, X in fp16):     error 0.0073
weights + activations int8 (W8A8):    error 0.0381
step size per token: 0.47; ordinary activations rounded to 0: 18%
error on the ordinary features' share of Y: 0.1455
mixed: 4 outlier columns fp16, 508 int8: error 0.0027
W8A8 on the same X without outliers:  error 0.0106

The 4 outlier columns hold 93% of the activation energy. W8A8 raises the error five-fold over weight-only int8 (0.0381 against 0.0073). The cause is visible in the next line: the per-token step is 0.47, close to the median ordinary activation of 0.68, so 18% of the ordinary activations round to 0 and their contribution to YY is off by 0.1455. Without the outliers, the same W8A8 gives 0.0106. Keeping just the 4 outlier columns in 16-bit (under 1% of the features) brings the error down to 0.0027.

Two other fixes are worth knowing by name. SmoothQuant (Xiao et al., 2022) divides each activation column by a factor and multiplies the matching weight column by it, an exact rewrite of XW⊤XW^\top that moves the difficulty from activations, which are hard to quantize, to weights, which are easy. Per-token dynamic scales with int8 or fp8 activations, now standard on recent GPUs, combine with either.

Error-aware rounding: the GPTQ idea

Rounding each weight to its nearest level (round-to-nearest, RTN) minimises the weight error. But the error that matters is ∥XW⊤−XW^⊤∥\lVert X W^\top - X \hat{W}^\top \rVert on real inputs, and when input features are correlated, an error in one weight can be compensated by adjusting the weights of correlated inputs that are not yet quantized. GPTQ (Frantar et al., 2022) does this one input column at a time, using the inverse of the Hessian H=X⊤XH = X^\top X of that squared output error (computed from a small calibration set: 128 sequences of 2,048 tokens from C4 in the paper), following the older Optimal Brain Quantization:

δi=wi−w^i[H−1]ii,wj←wj−δi [H−1]ijfor the columns j>i\delta_i = \frac{w_i - \hat{w}_i}{[H^{-1}]_{ii}}, \qquad w_{j} \leftarrow w_{j} - \delta_i\, [H^{-1}]_{ij} \quad \text{for the columns } j > i

after which input ii is removed from H−1H^{-1}. The example applies exactly this loop to a small layer with correlated inputs, at int4 with one scale per row, and measures the output error on new inputs, not the calibration ones.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
d_in, d_out = 64, 32
mix = rng.normal(0, 1, (d_in, d_in)) * np.exp(-np.arange(d_in) / 16)   # correlated input features
X_cal = rng.normal(0, 1, (512, d_in)) @ mix                            # calibration activations
X_test = rng.normal(0, 1, (512, d_in)) @ mix                           # new activations, same distribution
W = rng.normal(0, 0.1, (d_out, d_in))
qmax = 7                                                               # int4, symmetric
scale = np.abs(W).max(axis=1, keepdims=True) / qmax                    # one scale per output row

def rtn(W):                                    # round to nearest, each weight on its own
    return np.clip(np.round(W / scale), -qmax, qmax) * scale

def error_aware(W, X, damp=0.01):
    """GPTQ-style: quantize the inputs one by one and push each rounding error onto
    the not-yet-quantized weights, weighted by the inverse Hessian H = X^T X."""
    H = X.T @ X
    H += damp * np.mean(np.diag(H)) * np.eye(len(H))
    Hinv = np.linalg.inv(H)
    W = W.copy()
    Q = np.zeros_like(W)
    for i in range(W.shape[1]):
        Q[:, i] = np.clip(np.round(W[:, i] / scale[:, 0]), -qmax, qmax) * scale[:, 0]
        err = (W[:, i] - Q[:, i]) / Hinv[i, i]
        W[:, i + 1:] -= np.outer(err, Hinv[i, i + 1:])          # compensate in the remaining columns
        Hinv = Hinv - np.outer(Hinv[:, i], Hinv[i, :]) / Hinv[i, i]   # remove input i
    return Q

for name, Q in [("round to nearest", rtn(W)), ("error-aware (GPTQ idea)", error_aware(W, X_cal))]:
    w_err = np.linalg.norm(W - Q) / np.linalg.norm(W)
    y_err = np.linalg.norm(X_test @ W.T - X_test @ Q.T) / np.linalg.norm(X_test @ W.T)
    print(f"{name:<24} weight error {w_err:.4f}   output error on new inputs {y_err:.4f}")
round to nearest         weight error 0.1082   output error on new inputs 0.1032
error-aware (GPTQ idea)  weight error 0.3083   output error on new inputs 0.0669

The error-aware weights are three times further from the original weights (0.3083 against 0.1082) and still give a 35% smaller output error on new inputs (0.0669 against 0.1032). That is the whole idea: the weights are a means, the layer's output is the goal. The real GPTQ adds a Cholesky reformulation, lazy block updates and groups, and quantizes a 175-billion-parameter model in about four GPU hours on one A100.

AWQ (activation-aware weight quantization, Lin et al., 2023) starts from a related observation: about 1% of the weight channels matter most, those that multiply large activations. Instead of keeping them in fp16, it scales those input channels up before quantization (and the activations down by the same factor), so their relative rounding error shrinks. Both are post-training methods: a small calibration set (on the order of a hundred samples), no gradient steps. Quantization-aware training, which fine-tunes with simulated quantization in the forward pass, goes further but costs a training run.

A real model, quantized by hand (recorded)

The course's BERT (2 layers, hidden size 128) has 12 linear layers in its encoder (query, key, value, attention output and the two MLP layers in each of the 2 blocks). The example quantizes their weights by hand with torch tensors (the deprecated torch.ao.quantization API is not needed: dequantized "fake quantization" gives exactly the numbers an int kernel would) and compares the masked-language-model predictions with the fp32 model on 8 sentences: agreement of the top-1 word, the KL divergence of the predicted distributions at the masked position, and the smallest cosine similarity of the final hidden states over all tokens. Embeddings, layer norms and the output layer stay in fp32, as in most real schemes.

python · try it yourself
import copy
import torch
from transformers import AutoTokenizer, AutoModelForMaskedLM
from transformers.utils import logging
logging.set_verbosity_error()

torch.manual_seed(0)
name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
fp32 = AutoModelForMaskedLM.from_pretrained(name).eval()

def fake_quant(w, bits, group=None):
    """Symmetric absmax: one scale per output row, or per group of `group` inputs. Returns dequantized w."""
    qmax = 2 ** (bits - 1) - 1
    rows, cols = w.shape
    blocks = w.reshape(rows, cols // group, group) if group else w.reshape(rows, 1, cols)
    s = blocks.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8) / qmax
    return (torch.clamp(torch.round(blocks / s), -qmax, qmax) * s).reshape(rows, cols)

def quantized_copy(model, bits, group=None):
    m = copy.deepcopy(model)
    n = 0
    with torch.no_grad():
        for mod in m.bert.encoder.modules():                 # attention + MLP layers; embeddings stay fp32
            if isinstance(mod, torch.nn.Linear):
                mod.weight.copy_(fake_quant(mod.weight, bits, group))
                n += mod.weight.numel()
    return m, n

sentences = ["the capital of france is [MASK].", "she drank a cup of hot [MASK].",
             "he paid with his credit [MASK].", "the cat sat on the [MASK].",
             "i [MASK] this movie, it was wonderful.", "you need a [MASK] to open the door.",
             "the bike was returned to the [MASK].", "water boils at one hundred [MASK]."]
batch = tok(sentences, return_tensors="pt", padding=True)
mask_pos = batch["input_ids"] == tok.mask_token_id

with torch.no_grad():
    ref = fp32(**batch, output_hidden_states=True)
ref_logp = ref.logits[mask_pos].log_softmax(-1)
print("fp32 top-1:", tok.convert_ids_to_tokens(ref_logp.argmax(-1)))

for label, bits, group in [("int8 per-channel", 8, None), ("int4 per-channel", 4, None), ("int4 group 32", 4, 32)]:
    m, n = quantized_copy(fp32, bits, group)
    with torch.no_grad():
        out = m(**batch, output_hidden_states=True)
    logp = out.logits[mask_pos].log_softmax(-1)
    kl = (ref_logp.exp() * (ref_logp - logp)).sum(-1).mean().item()
    agree = (logp.argmax(-1) == ref_logp.argmax(-1)).float().mean().item()
    att = batch["attention_mask"].bool()
    cos = torch.nn.functional.cosine_similarity(out.hidden_states[-1][att], ref.hidden_states[-1][att], dim=-1)
    print(f"{label:<17} ({n:,} weights) top-1 agreement {agree:.3f}  KL {kl:.4f}  "
          f"hidden cos min {cos.min().item():.4f}")
    if bits == 4 and group is None:
        print("   int4 per-channel top-1:", tok.convert_ids_to_tokens(logp.argmax(-1)))
fp32 top-1: ['france', 'coffee', 'cards', 'table', 'felt', 'door', 'race', 'feet']
int8 per-channel  (393,216 weights) top-1 agreement 1.000  KL 0.0011  hidden cos min 0.9997
int4 per-channel  (393,216 weights) top-1 agreement 0.250  KL 0.5024  hidden cos min 0.8903
   int4 per-channel top-1: ['located', 'wine', 'again', 'floor', 'was', 'door', 'road', 'feet']
int4 group 32     (393,216 weights) top-1 agreement 0.500  KL 0.5293  hidden cos min 0.9066

Int8 per channel is practically lossless here: all 8 top-1 words agree, the KL divergence is 0.0011 nats and every token's hidden state keeps a cosine of at least 0.9997. Int4 round-to-nearest is a different story on this model: per channel only 2 of 8 top-1 words survive (KL 0.5024; "france" becomes "located"), and groups of 32 raise the agreement to 4 of 8 but leave the KL about the same (0.5293). A 2-layer, 128-wide BERT has little redundancy, so every rounding error lands somewhere visible; large LLMs tolerate 4-bit weights much better, and in practice int4 is always combined with groups and an error-aware method such as GPTQ or AWQ. The general rule holds at every size: int8 weights are safe, int4 must be measured.

The library version (needs a CUDA GPU, not run here)

In practice you load a model that someone has already quantized, or quantize on load:

python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, GPTQConfig

# LLM.int8(): weights int8, outlier columns of the activations in fp16
m8 = AutoModelForCausalLM.from_pretrained(name, quantization_config=BitsAndBytesConfig(load_in_8bit=True))
# GPTQ int4 with groups of 128, calibrated on a dataset (takes minutes to hours)
mq = AutoModelForCausalLM.from_pretrained(name, quantization_config=GPTQConfig(bits=4, group_size=128, dataset="c4", tokenizer=tok))

Serving engines read pre-quantized checkpoints (GPTQ, AWQ, fp8) directly, and llama.cpp uses its own GGUF formats (such as Q4_K_M: 4-bit weights in blocks with per-block scales, a few tensors in 6-bit, about 4.8 to 4.9 bits per weight over a whole model). Whichever you choose, the deciding test is your own evaluation set, as the first pitfall says.

Pitfalls

  • Judging by weight error. Measure the output of each layer, then the model on your own evaluation set (Evaluating LLMs); perplexity on a generic corpus can hide a drop on your task.
  • One scale per tensor at 4 bits. One outlier ruins it; use groups.
  • Quantizing activations naively. Outlier features need mixed precision, smoothing or fine-grained scales.
  • Calibrating on the wrong data. GPTQ and AWQ fit to their calibration set; calibrate on text like your traffic (and never on the test set).
  • Expecting speed from memory savings alone. Weight-only int4 speeds up memory-bound decoding (fewer bytes per token) but needs a kernel that dequantizes on the fly; without one, it can be slower than fp16. Compute-bound prefill gains only from int8 or fp8 matrix units.
  • Quantizing the sensitive parts. Embeddings, the output layer, norms and sometimes the first and last blocks are kept in 16 bits.

Practice

  1. In the first example, why does absmax int4 on the activations use only 8 levels?
  2. A layer has din=4096d_{\text{in}} = 4096. How many bits per weight do int4 groups of 64, 128 and 4096 cost with fp16 scales?
  3. Estimate the weight memory of a 70-billion-parameter model in fp16, int8 and int4 (groups of 128). Which fits on one 80 GB GPU?
  4. In the outlier example, what would happen to W8A8 with one scale per feature column of XX instead of per token? Why is that hard to use in a real int8 matrix product?
  5. Why does the GPTQ loop need calibration data, while RTN does not?
Answers
  1. The activations are almost all non-negative, and absmax maps [−4.28,4.28][-4.28, 4.28] onto −7…7-7 \dots 7. The negative half of the range is nearly empty (only values down to −0.17-0.17), and at a step of s=0.61s = 0.61 the most negative value, −0.17-0.17, still rounds to 0. Only the levels 0 to 7 are used: 8 levels.
  2. 4+1664=4.254 + \frac{16}{64} = 4.25, 4+16128=4.1254 + \frac{16}{128} = 4.125, and 4+164096≈4.0044 + \frac{16}{4096} \approx 4.004 bits (per channel).
  3. fp16: 70×109×2=14070 \times 10^9 \times 2 = 140 GB; int8: 70 GB; int4 with groups of 128: 70×109×4.1258≈3670 \times 10^9 \times \frac{4.125}{8} \approx 36 GB. Only int8 (tightly, leaving little room for the KV cache) and int4 fit on one 80 GB GPU.
  4. Per-column scales would isolate the outliers and fix the accuracy. But in XW⊤XW^\top the sum runs over the columns jj, and a scale per jj cannot be factored out of the sum: the int8 kernel would have to rescale each product before adding. Per-token (row of XX) and per-output-channel (row of WW) scales factor out, which is why those are used, and why SmoothQuant moves the per-column factor into the weights instead.
  5. RTN minimises the weight error, which needs only WW. GPTQ minimises the output error ∥X(W−W^)⊤∥\lVert X(W - \hat{W})^\top \rVert, which depends on the inputs through H=X⊤XH = X^\top X; calibration samples estimate it.

Test yourself

Why does the zero-point (affine) map beat absmax on post-GELU activations?

  1. It uses more bits
  2. Their range is mostly positive, and absmax wastes the negative half of the integer range
  3. It avoids rounding
  4. Absmax cannot represent 0

In the granularity example, what were the output errors of int4 per tensor and int4 with groups of 128?

  1. 0.5536 and 0.1367
  2. 0.0347 and 0.0079
  3. 0.1984 and 0.1013
  4. 0.2007 and 0.1383

What does LLM.int8() do with activation outlier features?

  1. Clips them to 6
  2. Multiplies the columns that contain them in 16-bit and everything else in int8
  3. Removes them from the model
  4. Quantizes them to int4

In the GPTQ example, the error-aware weights were further from the original weights than round-to-nearest. Why is that fine?

  1. Weight error is not measured correctly
  2. The goal is the layer's output on real inputs, and compensating rounding errors along correlated inputs lowers it
  3. GPTQ uses more bits
  4. The test inputs were the calibration inputs

Approximately how much memory do the weights of a 7-billion-parameter model take in int4 with fp16 scales per group of 128?

  1. 14 GB
  2. 7 GB
  3. 3.6 GB
  4. 0.9 GB