Quantization in Depth
Low-bit formats, outlier features, GPTQ and quantization-aware training.
Round every weight of OPT-175B to the nearest of sixteen levels and the model does worse than the full-precision OPT-13B, which is thirteen times smaller. Round the same weights one column at a time, letting the weights not yet rounded absorb each error, and the loss in perplexity shrinks to 0.03. Between those two outcomes lie the statistics of rounding error, the outlier features of large transformers, and a second-order idea first used in the early 1990s to prune networks.
What you’ll learn
- Derive the model of rounding error and the 6 dB-per-bit rule, and find the clipping range that balances rounding error against clipping error.
- Derive the gradients of quantization-aware training, including the step-size gradient of learned step size quantization.
- Explain why outlier features break 8-bit activation quantization in large transformers, and derive how LLM.int8(), SmoothQuant and random rotations avoid them.
- Derive GPTQ's error-compensating update from the layer-wise quadratic objective, and explain AWQ's activation-aware scaling.
- Weigh the evidence on how low weights can go: bit-level scaling laws, ternary models trained from scratch and precision-aware scaling laws.
The error of a uniform quantizer
The mean square of an error uniform on one cell:
With cells across a clipping range , . Each extra bit halves and quarters the error, so the signal-to-quantization-noise ratio rises by dB per bit:
Values beyond are clipped. For a Laplace density with scale each tail contributes , so the total trades a term that falls with against one that grows (Banner et al., 2019):
Clipping at the largest value, the natural default, is far from optimal. Among Laplace samples the largest is near ; at 4 bits that range gives an MSE of , against at , five times less. The same calculation for a Gaussian puts the optimum near , and at 2, 3 and 4 bits, and still only at 8 bits.
A 4-bit quantizer splits into 16 equal cells and maps each value to its cell's midpoint. For uniform on , what is the mean squared error? Answer in units of .
Show the answer
1.3 × 10⁻³
, and with uniform input the error is exactly uniform on each cell, so . Against the signal's variance of that is an SQNR of dB, the dB per bit of the formula. A symmetric integer grid with codes to has only 15 levels, a step of and an MSE of about .
Training through the rounding
Quantization-aware training, introduced in Model Compression & Efficient Inference, rounds in the forward pass and uses the straight-through estimator (Bengio, Léonard & Courville, 2013) in the backward pass. That handles the weights; the quantizer's own parameters, its step size and range, need gradients too. Esser et al. (2020) made the step size of every layer a trainable parameter, learned step size quantization (LSQ), and derived its gradient with the same estimator.
Write the quantizer with integer bounds and ; for signed -bit weights and :
Inside the range, differentiate the product. Keep the value of the rounding but give it unit slope, as the straight-through estimator does:
In the clipped regions or , so the derivative is or . The interior term is the signed distance from to its grid point, so values close to a rounding boundary push hardest on the step size. Approximations that cancel the rounding algebraically before differentiating get exactly zero there and ignore where sits between grid points.
Each step size sums gradient contributions from every value it scales, so LSQ multiplies its gradient by , chosen to keep the ratio of update size to parameter size comparable to the weights', and initializes it from the data. With every layer but the first and last (kept at 8 bits) at 3 bits for weights and activations, ResNets trained this way came within about a point of full precision on ImageNet (ResNet-18: 70.2% against 70.5%), and with distillation from a full-precision copy of the same network they matched it.
With step and , a weight is quantized to . What is under learned step size quantization?
Show the answer
A.
rounds to 3, inside the range, so the gradient is . Holding the rounded code fixed would give , the true slope of ; the straight-through term subtracts the part that the rounding would otherwise hide.
For large language models, full quantization-aware training is a training run, so it is used mainly for models designed to be low-precision from the start (step 5) or as a shorter phase after pretraining: LLM-QAT (Liu et al., 2023) trained LLaMA models of 7 to 30 billion parameters to 4-bit weights and KV caches with 8-bit activations, distilling each from its own full-precision version on text that model generated. Post-training methods carry the rest: they cannot adapt the network as a whole, but they can choose, weight by weight, how to round.
Outlier features
Weights of trained networks are well behaved: roughly bell-shaped, with few extreme values. Activations of large transformers are not. Dettmers, Lewis, Belkada and Zettlemoyer (2022) found outlier features in OPT-style models: hidden dimensions with magnitudes up to 20 times larger than the rest, which first appear in about a quarter of the layers and, between 6 and 6.7 billion parameters, spread to all layers and to about 75% of token positions. At 6.7 billion parameters they counted about 150,000 outlier values per sequence, all in just six feature dimensions of the whole network. Zeroing those dimensions, about 0.1% of the features, degraded perplexity by 600–1000%; zeroing as many random ones changed it by about 0.1%. Measured against perplexity instead of size, the emergence is smooth rather than sudden. Where such coordinates come from, and why they help softmax attention do nothing, is the subject of Attention Sinks & Massive Activations.
Per-tensor 8-bit quantization of such activations fails beyond about 6.7 billion parameters: one scale must reach the outliers, so the ordinary values occupy only a few levels near zero. LLM.int8() combines two fixes. Vector-wise quantization gives each token and each output channel its own scale, which still factors out of the dot product. Mixed-precision decomposition splits the product by input dimension: any dimension where some value exceeds a threshold of 6.0 is multiplied in 16 bits, and the rest, more than 99.9% of the values, in 8 bits. With at most seven such dimensions in models up to 13 billion parameters, this halved the memory of the weights with no measurable degradation up to 175 billion parameters.
SmoothQuant (Xiao et al., 2023) starts from two observations: outliers sit in a few fixed input channels in every token, and per-channel activation scales would fix them (simulated per-channel INT8 kept OPT-175B at 71.4% average accuracy against 71.6% in FP16, where per-tensor and per-token scales fell to about 32%), but a scale per input channel cannot be pulled out of an integer dot product. So it moves the difficulty into the weights, which tolerate it, with an exact change of variables.
For any positive vector indexed by input channel , the layer's output is unchanged (here holds one token per column):
Channel of the activations is divided by and column of the weights multiplied by it. With migration strength , measured on calibration data:
At both factors end with the same channel maximum, the geometric mean of the two, so neither side keeps the outlier alone. moves everything into the weights, everything into the activations; worked for OPT and BLOOM and for GLM-130B, whose outliers are more severe.
The division by is folded offline into the preceding normalization or linear layer, so inference pays nothing. Both operands are then quantized to INT8 with scales that factor out of the integer product; the paper used one scale per tensor for the weights and one per tensor or per token for the activations. The authors reported up to 1.56 times faster inference and half the memory, with negligible loss in accuracy.
Because is orthogonal, : the rotation can be folded into the neighboring weights without changing the function (in the residual stream this works because RMSNorm divides each vector by its root mean square, which a rotation leaves unchanged, once the norm's learned scale has been folded into the next weight matrix), yet every rotated vector loses its spikes. Take with one coordinate of 60 and the rest of size 1: before the rotation an INT8 step must be ; after it, the largest of the 4,096 coordinates is about 4 to 5 in a few random draws and the step about . QuaRot (Ashkboos et al., 2024) applies such rotations to the residual stream, inside the feed-forward blocks and to keys and values, and quantized every weight, activation and cached key and value of LLaMA2-70B to 4 bits while losing at most 0.47 WikiText-2 perplexity and keeping 99% of its zero-shot accuracy. The same random Hadamard idea appears in 4-bit training recipes (Number Formats & Mixed Precision).
GPTQ: rounding with error compensation
Round weight , fixing , and let the not-yet-quantized weights move. Split the quadratic into blocks:
Minimizing over is a least-squares problem, and the minimum is a Schur complement:
The block-inverse formulas and turn this into the update of Optimal Brain Quantization (Frantar, Singh & Alistarh, 2022), which GPTQ inherits; here is restricted to the weights not yet fixed:
Without compensation the cost would be , never smaller, since for positive definite ; the gain is largest when inputs are strongly correlated. After fixing , its row and column are removed from by one step of Gaussian elimination, , without inverting again. The same formulas with are Optimal Brain Surgeon's pruning rule, derived another way in Pruning, Sparsity & Lottery Tickets.
A row has two weights with and a grid of step . Weight 1 is rounded to . What should weight 2 become?
Show the answer
0.525
, so and becomes . The inputs are positively correlated, so weight 2 makes up for weight 1's loss. The output error drops from to , a quarter less; weight 2 is rounded next, from its new value.
OBQ picked the weight with the smallest next, separately for every row, which costs and limited it to models of up to about a hundred million parameters. GPTQ (Frantar, Ashkboos, Hoefler & Alistarh, 2023) made it scale with three changes:
- One order for all rows. Quantizing columns left to right in every row lost little against the greedy order on large layers. Since depends only on , every row then shares the same sequence of inverses, updated once per column: .
- Lazy batch updates. Rank-one updates of a large matrix are memory-bound. GPTQ processes 128 columns at a time, updating only inside the block, then applies the accumulated corrections to all later columns in one matrix product.
- Cholesky form. Repeated eliminations accumulate errors that can make indefinite in models of billions of parameters. The rows GPTQ needs are, up to scaling, the rows of the upper Cholesky factor of , computed once after adding 1% of the mean diagonal to (dampening).
Calibrated on 128 random sequences of 2,048 tokens, GPTQ quantized OPT-175B and BLOOM-176B in about four GPU hours. At 3 bits OPT-175B fits on one 80 GB GPU, and a kernel that unpacks weights on the fly generated tokens 3.24 times faster than the 16-bit model spread over five GPUs.
import torch
def gptq(W, X, bits=4, damp=0.01):
"""W: (d_out, d_in) weights, X: (d_in, n) calibration inputs. Returns quantized weights."""
W, d = W.clone(), W.shape[1]
H = 2 * X @ X.T
H += damp * H.diagonal().mean() * torch.eye(d) # dampening
U = torch.linalg.cholesky(torch.linalg.inv(H), upper=True) # H^-1 = U^T U
qmax = 2 ** (bits - 1) - 1
s = W.abs().amax(dim=1) / qmax # one scale per row
Q = torch.zeros_like(W)
for j in range(d): # columns in a fixed order
Q[:, j] = torch.clamp(torch.round(W[:, j] / s), -qmax, qmax) * s
err = (W[:, j] - Q[:, j]) / U[j, j]
W[:, j:] -= torch.outer(err, U[j, j:]) # compensate later columns
return QGPTQ without the blocking. Row of the upper Cholesky factor equals row of the inverse over the columns not yet quantized, divided by the square root of its diagonal entry, so each update matches the formula above. On random correlated inputs this gives exactly the result of applying the one-weight update column by column, and a smaller output error than rounding to nearest.
AWQ (Lin et al., 2024) takes the opposite approach: no reconstruction at all, only a better choice of what to protect. Keeping just 1% of weight channels in 16 bits, chosen by the size of their activations, brought OPT-6.7B under 3-bit quantization with groups of 128 from a perplexity of 23.54 (round to nearest) to 11.39, against 10.86 in FP16; choosing the 1% by weight magnitude barely helped. Since mixed precision is awkward for kernels, AWQ protects those channels by scaling instead. Multiply weight by and its input by : if the group's step barely changes, the rounding error of is about times that of . Too large an widens the step for the rest of the group, so AWQ searches , with the average activation magnitude per channel and , to minimize the layer's output error. With no backpropagation and little dependence on the calibration set it generalized well, including to instruction-tuned and multimodal models. QLoRA's 4-bit NormalFloat, whose 16 levels follow the quantiles of a normal distribution, is the third common 4-bit scheme (Low-Rank Adaptation in Depth).
How low can weights go?
Bits are a budget. A 30-billion-parameter model in 8 bits and a 60-billion-parameter model in 4 bits occupy the same memory. Dettmers and Zettlemoyer (2023) ran more than 35,000 zero-shot experiments on models from 19 million to 176 billion parameters in four families, quantizing weights to 3 to 8 bits, and found 4-bit precision almost universally optimal for accuracy at a fixed total number of model bits. Few changes improved that trade-off at 4 bits, and none at 6 to 8: only small quantization blocks (64 to 128 weights was usually best) and the data type, with floating-point or quantile levels scaling better than integers.
Below 4 bits after training, error compensation and small groups go a long way. With groups of 8 weights, GPTQ reached ternary weights times a scale on OPT-175B while losing less than one point of WikiText-2 perplexity.
Low precision from the start. BitNet b1.58 (Ma et al., 2024) trains the weights of every linear layer of a LLaMA-style model as ternary (the embeddings stay in high precision), quantization-aware from the first step, with 8-bit activations and the absmean quantizer below. Pretrained on 100 billion tokens, it trailed a 16-bit baseline slightly at 1.3 billion parameters and matched it at 3 billion in perplexity (9.91 against 10.04) and zero-shot accuracy, by the authors' report. Three levels carry bits, and matrix products become additions and subtractions. The paper is a preprint describing work in progress, and how the comparison holds up at larger scale and longer training is not yet settled.
Precision meets scaling laws. Kumar et al. (2025) fitted scaling laws with precision as a variable on more than 465 pretraining runs, up to 1.7 billion parameters and 26 billion tokens. Two findings bear on compression. The loss added by post-training quantization grows with the number of tokens a model was trained on, to the point where, for a fixed post-training precision, more pretraining data can make the quantized model worse. And training in low precision acts like reducing the effective parameter count. Since models meant for wide deployment are trained far beyond 20 tokens per parameter (Neural Scaling Laws), the models most worth quantizing may be the hardest to quantize. The fits come from small models and await confirmation at scale.
Key takeaways
- A uniform quantizer with step adds error of variance about , so each bit is worth about 6 dB; the clipping range trades rounding against clipping error, and its optimum lies well inside the largest value (about at 4 bits for Laplace data of scale ).
- Quantization-aware training uses the straight-through estimator for values and, in LSQ, the gradient for the step size, with which 3-bit ResNets, helped by distillation, matched full precision.
- Beyond about 6.7 billion parameters a few outlier dimensions break per-tensor 8-bit activations. LLM.int8() keeps them in 16 bits, SmoothQuant moves the difficulty into the weights with , and random Hadamard rotations spread any spike over all coordinates.
- GPTQ minimizes each layer's output error with : rounding and moving the remaining weights by costs only . One shared column order, lazy blocks and a Cholesky factor make it run on 175-billion-parameter models in hours; AWQ instead scales up the channels with large activations.
- At a fixed memory budget, 4-bit weights are almost always the best post-training trade-off. Ternary weights need tiny groups or training from scratch (BitNet b1.58), and models trained on more tokens lose more when quantized afterwards.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With the clipping range fixed, by what factor does the rounding MSE grow when a uniform quantizer goes from 6 bits to 4 bits, under the uniform-noise model?
- 2
- 4
- 16
- It is unchanged
Show the answer
C. 16
Two bits fewer quadruple the step , and the MSE grows by : 12 dB of SQNR, about 6 dB per bit.
In SmoothQuant with migration strength , input channel has activation maximum and weight maximum . After smoothing, what are the two maxima?
- and
- and
- and
- and , since smoothing is exact
Show the answer
B. and
. The activation maximum becomes and the weight maximum : both equal , so the two sides share the difficulty equally.
Why can GPTQ quantize every row of a weight matrix in the same column order, instead of choosing a greedy order per row as OBQ did?
- Because rows of a weight matrix are identical
- Because the layer-wise Hessian depends only on the inputs, so all rows share it and its inverse is updated once per column; on large layers the greedy order gained little
- Because the order of quantization never affects the final error
- Because GPTQ quantizes all weights at once, without any order
Show the answer
B. Because the layer-wise Hessian depends only on the inputs, so all rows share it and its inverse is updated once per column; on large layers the greedy order gained little
Each row's objective has the same Hessian. With a shared order, the inverse over the remaining columns is the same for every row, which cuts the cost by a factor of .
AWQ protects about 1% of the weight channels of a layer. How does it choose them, and how does it protect them without storing them in 16 bits?
- By the largest weight magnitudes; it clips them less
- At random; it gives them their own quantization groups
- By the largest gradients; it skips quantizing them
- By the largest average activation magnitudes; it multiplies those weight channels by and divides the matching activations by , which shrinks their relative rounding error
Show the answer
D. By the largest average activation magnitudes; it multiplies those weight channels by and divides the matching activations by , which shrinks their relative rounding error
A weight's error is multiplied by its input, so channels with large activations matter most. Scaling a channel's weights up by while its group's step barely changes cuts its relative error by about , and the factor is folded into the previous operation.
Further reading
- M. Nagel, M. Fournarakis, R. A. Amjad, Y. Bondarenko, M. van Baalen & T. Blankevoort, "A white paper on neural network quantization," arXiv:2106.08295 (2021).
- T. Dettmers, M. Lewis, Y. Belkada & L. Zettlemoyer, "LLM.int8(): 8-bit matrix multiplication for transformers at scale," NeurIPS (2022).
- G. Xiao, J. Lin, M. Seznec, H. Wu, J. Demouth & S. Han, "SmoothQuant: Accurate and efficient post-training quantization for large language models," ICML (2023).
- E. Frantar, S. Ashkboos, T. Hoefler & D. Alistarh, "GPTQ: Accurate post-training quantization for generative pre-trained transformers," ICLR (2023).
- J. Lin et al., "AWQ: Activation-aware weight quantization for on-device LLM compression and acceleration," MLSys (2024).