Simple Algorithm
Deep Learning · Representation · 22 min

Model Compression & Efficient Inference

Quantization, pruning and distillation: smaller, faster models with little loss.

A 70-billion-parameter model stored in 16 bits takes 140 GB, and to generate a single token for a single user the GPU must read every one of those bytes from memory. Store each weight in 4 bits and it reads a quarter as much: tokens come up to four times faster, from far fewer GPUs. Compression makes models cheap to run by giving them fewer bits per weight, fewer weights, or a smaller student that imitates them, and the craft is in losing almost nothing along the way.

What you’ll learn

  • Explain why generating text is limited by memory traffic, and estimate how the bits per weight set a model's memory footprint and its speed limit.
  • Define uniform affine quantization (scale, zero point, symmetric or asymmetric, per tensor, channel or group) and derive how an integer matrix product recovers the real one.
  • Contrast post-training quantization with quantization-aware training and the straight-through estimator, and describe how large language models are quantized in practice.
  • Compare unstructured, N:M and structured pruning by what hardware can accelerate, and write the knowledge-distillation loss with its temperature.

What inference costs

Training happens once; a deployed model runs for months. Its bill has four parts: memory (the weights, plus a KV cache for every active sequence), latency (the time per generated token), throughput (tokens per second across all users, and so the cost per token) and energy. On a phone or a laptop a fifth comes first: fitting at all.

For text generation the deciding fact comes from The Roofline Model & Compute Efficiency. Producing one token for one sequence multiplies every weight matrix by a single vector, an arithmetic intensity of about one FLOP per byte. The GPU spends its time streaming weights out of HBM, not multiplying them, so the time per token is at least the bytes of weights divided by the memory bandwidth β\beta.

ttoken ≥ N b/8β(N parameters at b bits each)t_{\text{token}}\ \ge\ \frac{N\,b/8}{\beta}\qquad(N\text{ parameters at }b\text{ bits each})
Batching many sequences reuses each loaded weight and raises the intensity, but every sequence needs its own KV cache, so memory caps the batch. Fewer bits per weight help at every batch size: the model fits on fewer GPUs and leaves more room for caches.
Predict before you look

An illustrative GPU streams 3×10123\times10^{12} bytes per second from HBM. Counting only the weights, at most how many tokens per second can it generate for one sequence of a 70-billion-parameter model stored at exactly 4 bits per weight?

Show the answer

86 tokens/s

The weights take 70×109×0.5=3.5×101070\times10^9\times0.5=3.5\times10^{10} bytes, so each token needs at least 3.5×1010/(3×1012)≈11.73.5\times10^{10}/(3\times10^{12})\approx11.7 ms: about 86 tokens per second. In 16 bits the same model takes 140 GB, more than one 80 GB GPU holds; at the same bandwidth the bound would be 21 tokens per second, and splitting the model over two GPUs doubles the bandwidth but also the hardware. Real kernels reach only part of the bound and must spend some arithmetic unpacking 4-bit weights, but the ratio between the two is what quantization buys.

TechniqueWhat it shrinksWhat it costsTaken further in
Quantizationbits per weight, and per activationminutes to hours after training, or a training runQuantization in Depth
Pruningthe number of nonzero weights, or whole channels, heads and layersusually some retrainingPruning, Sparsity & Lottery Tickets
Distillationthe model itself: a smaller student trained to imitate a teachera full training run of the studentKnowledge Distillation
Low-rank factorizationa matrix W∈Rm×nW\in\R^{m\times n} replaced by a product UVUV of rank rr: r(m+n)r(m+n) parameters instead of mnmnfine-tuningLow-Rank Adaptation in Depth, for low-rank updates
Efficient architecturesFLOPs and memory by design: depthwise separable convolutions, grouped-query attention, mixtures of expertschosen before trainingEfficient ConvNets, Anatomy of a Modern LLM, Mixture of Experts
Serving techniqueswasted memory and idle arithmetic: continuous batching, paged KV caches, speculative decodingno change to the modelServing Language Models, Speculative Decoding
The first three change the model and are the subject of this lesson. They combine: Han, Mao and Dally (2016) pruned AlexNet, quantized the surviving weights to a few bits each and entropy-coded them, shrinking it 35×, from 240 MB to 6.9 MB, without loss of accuracy.

Rounding to a grid

Two errors compete. Inside the range, rounding moves a value by at most s/2s/2. Outside it, clipping sets the value to the end of the range. Choosing the range trades one against the other: covering the largest value never clips, but one large value makes the step coarse for everything else.

The other choice is granularity: one scale for a whole tensor, one per channel (each output row of a weight matrix), or one per group of 32 to 128 consecutive weights. Finer scales follow the local range better but must be stored too: a 16-bit scale for every 32 weights adds 16/32=0.516/32=0.5 bits per weight.

Check your understanding

Activations after a ReLU lie in [0,6][0,6]. You quantize them to 8 bits symmetrically (z=0z=0, codes −127-127 to 127127, s=6/127s=6/127). What goes wrong?

  1. Nothing: at 8 bits symmetric and asymmetric quantization are equivalent
  2. The negative codes are never used, so the data get only 128 levels and a step about twice as coarse as an asymmetric grid's 6/2556/255
  3. The value 0 can no longer be represented exactly
  4. Values near 6 overflow the grid
Show the answer

B. The negative codes are never used, so the data get only 128 levels and a step about twice as coarse as an asymmetric grid's 6/2556/255

No activation is negative, so codes −127-127 to −1-1 are wasted. Asymmetric quantization with z=0z=0 and s=6/255s=6/255 uses all 256 codes and halves the rounding error. For roughly symmetric data such as weights the symmetric grid wastes little, which is why weights are usually quantized symmetrically and post-ReLU activations asymmetrically.

Integer matrix products

Quantization saves memory on its own. Its second payoff is arithmetic: 8-bit multiplies on recent accelerators typically have about twice the peak rate of 16-bit ones and move half the bytes. To use them, the scales have to come out of the dot products.

DerivationWhere the scales go
  1. Wik≈si qik,xk≈sx (uk−zx)W_{ik}\approx s_i\,q_{ik},\qquad x_k\approx s_x\,(u_k-z_x)

    Take a layer y=Wx\mathbf y=W\mathbf x with W∈Rm×nW\in\R^{m\times n}. Quantize row ii of WW symmetrically with its own scale sis_i (per output channel), and the input with one scale sxs_x and zero point zxz_x (per tensor, or per token in a batch):

  2. yi≈∑ksiqik sx(uk−zx)=sisx(∑kqikuk⏟int8 × int8 → int32−  zx∑kqik⏟precomputed)y_i\approx\sum_k s_iq_{ik}\,s_x(u_k-z_x)=s_is_x\Big(\underbrace{\sum_kq_{ik}u_k}_{\text{int8}\,\times\,\text{int8}\,\to\,\text{int32}}-\;z_x\underbrace{\sum_kq_{ik}}_{\text{precomputed}}\Big)

    Both scales are constant along the summed index kk, so they factor out of the dot product and leave integers inside:

  3. M=sisxsy=2−nM0,M0∈[12,1) stored as an integerM=\frac{s_is_x}{s_y}=2^{-n}M_0,\qquad M_0\in\big[\tfrac12,1\big)\ \text{stored as an integer}

    The core is an integer matrix product accumulated in 32 bits; the zero-point correction is one stored sum per row, and the rescaling is one multiply per output. Jacob et al. (2018) made even that multiply integer: to requantize the output with its own scale sys_y they write the combined factor as a fixed-point number and a bit shift, so the whole network runs on integer-only hardware.

  4. A scale that changed with kk, one per input channel, could not be factored out: every product would need its own multiplication before the sum, which integer matrix units do not do. Per-group weight scales along a row are handled by summing each group in integers and rescaling the partial sums, at some cost. So weights get scales per output channel or per group, activations per tensor or per token, and large values confined to particular input channels are a real problem, as Quantization in Depth shows.

Two regimes for large language models.

  • Weight-only, e.g. W4A16: weights stored in 4 bits with group scales and unpacked to 16 bits inside the matrix kernel, so the arithmetic stays 16-bit. It saves no FLOPs but shrinks the bytes that bound decoding, so it speeds up generation at small batch sizes.
  • Weights and activations, e.g. W8A8: both operands in 8 bits, so the products run on 8-bit units. It helps where arithmetic dominates, such as long prompts and large batches. Its obstacle is the activations: beyond a few billion parameters, transformers develop a handful of hidden dimensions with values far larger than the rest (Dettmers et al., 2022), outlier features whose origin Attention Sinks & Massive Activations explains, and one scale per tensor or token must stretch to cover them.

After training, or during it?

Post-training quantization (PTQ) takes a trained model, runs a few hundred calibration examples through it to choose activation ranges, and rounds the weights. It needs no labels and no retraining, and at 8 bits it is usually enough: with a scale per channel for the weights and 8-bit activations, a wide range of CNNs stayed within 2% of their floating-point accuracy (Krishnamoorthi, 2018). Below 8 bits plain rounding starts to hurt, and there are two remedies: post-training algorithms that adjust the weights to cancel the rounding error, and training with the quantizer in the loop.

Quantization-aware training (QAT) inserts fake quantization, quantize then immediately dequantize, into the forward pass, so the loss is computed on the rounded model. The obstacle is the backward pass: rounding is a staircase whose derivative is zero almost everywhere. The straight-through estimator (Bengio, Léonard & Courville, 2013) pretends the staircase is the identity inside the clipping range:

forward:  w^=s clamp⁡(round⁡(w/s),−qmax⁡,qmax⁡),backward:  ∂w^∂w:={1∣w/s∣≤qmax⁡0otherwise\text{forward: }\ \hat w=s\,\operatorname{clamp}\big(\operatorname{round}(w/s),-q_{\max},q_{\max}\big),\qquad\text{backward: }\ \frac{\partial\hat w}{\partial w}:=\begin{cases}1&\abs{w/s}\le q_{\max}\\0&\text{otherwise}\end{cases}
Full-precision weights are kept and updated; every forward pass uses their rounded copies. With QAT, Krishnamoorthi (2018) cut the 8-bit gap to about 1% and reached 4-bit weights at losses of 2% to 10%, largest for the smallest networks; learned step sizes, combined with distillation, have since brought 3-bit ResNets to full-precision accuracy (Quantization in Depth).
python
import torch

def fake_quant(w, bits=4):
    """Symmetric absmax quantization with one scale per output channel (row)."""
    qmax = 2 ** (bits - 1) - 1                               # 7 for 4 bits
    s = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / qmax
    q = torch.clamp(torch.round(w / s), -qmax, qmax)          # integer codes
    w_hat = q * s                                             # dequantized weights
    return w + (w_hat - w).detach()                           # straight-through estimator

w = torch.randn(256, 512, requires_grad=True)
x = torch.randn(512, 32)
loss = (fake_quant(w) @ x).square().mean()
loss.backward()     # the gradient reaches w as if rounding were the identity

The forward value of w + (w_hat - w).detach() is exactly w_hat, but the detached difference contributes no gradient, so the derivative with respect to w is the identity. Here the scales are recomputed from the weights at every step; learning them as parameters works better at low bit widths.

At the scale of large language models QAT means repeating a large share of pretraining, so PTQ dominates, and plain rounding to the nearest level fails for 8-bit activations of large models and degrades 4-bit weights. GPTQ (Frantar et al., 2023) quantizes one weight column at a time and nudges the weights not yet quantized to cancel each rounding error, using second-order information from 128 calibration sequences. On OPT-175B at 4 bits it raised WikiText-2 perplexity by only 0.03, where rounding to nearest added 2.2 and did worse than the full-precision 13-billion-parameter model; at 3 bits rounding to nearest collapsed while GPTQ held up. The 4-bit format of QLoRA is in Low-Rank Adaptation in Depth, and quantized KV caches are in Serving Language Models.

Pruning: fewer weights

Magnitude pruning removes the weights closest to zero. Han, Pool, Tran and Dally (2015) trained a network, pruned its smallest weights, retrained the survivors, and repeated: AlexNet went from 61 million weights to 6.7 million (9×) and VGG-16 from 138 million to 10.3 million (13×), with no loss of ImageNet accuracy. Retraining was essential, and iterating beat pruning once: 9× against 5× on AlexNet.

Removing weights is easy; making the network faster is not. It depends on where the zeros are:

PatternWhich weights may be zeroAccuracySpeed on GPUs
Unstructuredany individual weightthe best at a given sparsitylittle gain unless sparsity is very high: indices must be stored (for 8-bit values a compressed-row format can need twice as many bits for indices as for values) and memory access becomes irregular
N:M, e.g. 2:4at most 2 nonzeros in every 4 consecutive weightsmatched dense accuracy across many vision and language networks after one retraining run (Mishra et al., 2021)sparse tensor cores skip the zeros: up to twice the dense math rate, with a 2-bit index per kept weight
Structuredwhole channels, filters, attention heads or layersthe lowest at a given parameter counta smaller dense network, fast on any hardware
Michel, Levy and Neubig (2019) found that many attention heads of trained transformers can be removed at test time without much loss, some layers down to a single head. Whole layers can go too (Reading the Residual Stream).
Check your understanding

A row of weights reads [0.9, −0.1, 0.4, −0.6 ∣ 0.05, 0.3, −0.2, 0.01][0.9,\ -0.1,\ 0.4,\ -0.6\ \mid\ 0.05,\ 0.3,\ -0.2,\ 0.01], in two groups of four. Which weights does 2:4 magnitude pruning keep?

  1. 0.9, 0.4, −0.6, 0.30.9,\ 0.4,\ -0.6,\ 0.3: the four largest in the row
  2. 0.9, −0.60.9,\ -0.6 and 0.3, −0.20.3,\ -0.2: the two largest in each group of four
  3. 0.9, 0.40.9,\ 0.4 and 0.05, 0.30.05,\ 0.3: the first two positive weights in each group
  4. 0.90.9 and 0.30.3: one weight per group
Show the answer

B. 0.9, −0.60.9,\ -0.6 and 0.3, −0.20.3,\ -0.2: the two largest in each group of four

2:4 sparsity allows at most two nonzeros in each group of four, so each group keeps its own two largest magnitudes. The hardware then stores 2 values plus two 2-bit positions per group: for 16-bit weights, 36 bits instead of 64.

Large language models are pruned in one shot, without retraining. SparseGPT (Frantar & Alistarh, 2023) prunes each layer so as to preserve its outputs, using second-order information, and took OPT-175B and BLOOM-176B to 50–60% unstructured sparsity in under 4.5 hours, with a negligible rise in perplexity at 60%; on OPT-175B, magnitude pruning collapsed beyond 30%. Pruning, Sparsity & Lottery Tickets derives the second-order criteria and asks a deeper question: if a pruned network is as good as the dense one, could it have been trained sparse from the start?

Distillation: learning from a teacher

Knowledge distillation trains a small student to imitate a large teacher, an idea Buciluă, Caruana and Niculescu-Mizil (2006) used to compress whole ensembles into one model. Hinton, Vinyals and Dean (2015) gave it its standard form. The teacher's logits v\mathbf v become soft targets through a softmax at temperature TT, the student's logits z\mathbf z are softened the same way, and the student is trained on a mix of the soft targets and the true label yy:

pi(T)=evi/T∑jevj/T,L=α CE⁡(y,softmax⁡(z))+(1−α) T2 DKL(p(T) ∥ softmax⁡(z/T))p_i^{(T)}=\frac{e^{v_i/T}}{\sum_je^{v_j/T}},\qquad\loss=\alpha\,\operatorname{CE}\big(y,\softmax(\mathbf z)\big)+(1-\alpha)\,T^2\,\KL\big(\mathbf p^{(T)}\,\big\|\,\softmax(\mathbf z/T)\big)
At T=1T=1 a confident teacher puts nearly all its probability on one class. At T>1T>1 the small probabilities of the wrong classes grow and their ratios shrink, so the student learns which wrong answers are plausible. The factor T2T^2 keeps the soft term's gradients from shrinking as TT grows (Knowledge Distillation derives it). Hinton et al. got their best results with a much smaller weight on the hard-label term.

Dark knowledge, Hinton's name for those small probabilities, carries a surprising amount:

  • On MNIST, a network with two hidden layers of 800 units made 146 test errors when trained on labels, but 74 when matching the soft targets of a larger, heavily regularized teacher (67 errors) at T=20T=20 was added to its training.
  • In speech recognition, the gain of a 10-model ensemble over one model (frame accuracy from 58.9% to 61.1%) was almost entirely kept by a single distilled model (60.8%).
  • DistilBERT (Sanh et al., 2019) halved BERT's layers and kept 97% of its language-understanding score with 40% fewer parameters, running 60% faster. Gemma 2's 2- and 9-billion-parameter models were trained with distillation instead of plain next-token prediction (Gemma Team, 2024).
Think first Why not simply train the student on the teacher's predicted labels, its argmax, instead of its whole distribution?

The argmax records only which class won, at most log⁡2K\log_2K bits per example for KK classes. The full distribution also says how much probability the teacher gave the other classes, and which ones. With only 3% of their speech data, Hinton et al. trained a model on soft targets to 57.0% frame accuracy, against 44.5% with hard labels and 58.9% with hard labels on all the data. Hard teacher outputs still have a use: for sequences, training on the teacher's decoded outputs is sequence-level distillation, which Knowledge Distillation covers.

Key takeaways

  • At small batch sizes text generation is limited by memory bandwidth: the time per token is at least the bytes of weights divided by the bandwidth, so the bits per weight translate directly into speed, memory and cost.
  • Uniform affine quantization stores x≈s(q−z)x\approx s(q-z). Scales per output channel or per token factor out of integer dot products; per-group scales follow local ranges at the price of storing them; outliers force fine-grained scales or special handling.
  • Post-training quantization usually suffices at 8 bits. Below that, quantization-aware training with the straight-through estimator, or post-training methods that compensate rounding error such as GPTQ, keep accuracy; large language models are commonly run with 4-bit weights or with 8-bit weights and activations.
  • Pruning removes weights, but only structured and N:M (2:4) patterns speed up standard hardware; unstructured sparsity mainly saves storage unless it is extreme.
  • Distillation trains a student on a teacher's temperature-softened distribution, whose small probabilities (dark knowledge) carry far more information per example than a label.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A 4-bit weight-only quantized language model still does its matrix products in 16-bit arithmetic. Why does it generate text faster than the 16-bit model at batch size 1?

  1. It performs a quarter as many FLOPs
  2. 4-bit numbers are multiplied four times faster by tensor cores
  3. Decoding is limited by memory bandwidth, and the weights it must stream each step are a quarter the size
  4. It skips the attention computation
Show the answer

C. Decoding is limited by memory bandwidth, and the weights it must stream each step are a quarter the size

At batch size 1 each weight is used for one multiply-add per token, so the time is set by bytes moved, not FLOPs. Unpacking 4-bit weights to 16 bits costs a little arithmetic, which the GPU has to spare.

Question 2

You quantize values in [−1,3][-1,3] to 8 bits asymmetrically, with codes 00 to 255255. What are the scale and the zero point?

  1. s=4/255, z=0s=4/255,\ z=0
  2. s=3/127, z=0s=3/127,\ z=0
  3. s=1/64, z=64s=1/64,\ z=64
  4. s=4/255, z=64s=4/255,\ z=64
Show the answer

D. s=4/255, z=64s=4/255,\ z=64

s=(3−(−1))/255≈0.0157s=(3-(-1))/255\approx0.0157 and z=round⁡(1/s)=round⁡(63.75)=64z=\operatorname{round}(1/s)=\operatorname{round}(63.75)=64. Check the ends: −1-1 maps to round⁡(−63.75)+64=0\operatorname{round}(-63.75)+64=0, and 33 to round⁡(191.25)+64=255\operatorname{round}(191.25)+64=255. The real 0 is the code 64 exactly.

Question 3

In quantization-aware training, what does the straight-through estimator do?

  1. It uses the rounded weights in the forward pass and treats rounding as the identity in the backward pass
  2. It removes the rounding from both passes, so training is ordinary full-precision training
  3. It computes the exact derivative of the rounding function
  4. It rounds the gradients to the same grid as the weights
Show the answer

A. It uses the rounded weights in the forward pass and treats rounding as the identity in the backward pass

The loss is computed on the quantized model, so training adapts the weights to rounding, while the gradient passes through the staircase as if it were not there (and stops where values are clipped).

Question 4

Pruning 50% of a layer's weights at scattered positions and pruning 50% in a 2:4 pattern remove the same number of multiplications. Why can only the 2:4 version run about twice as fast on GPUs with sparse tensor cores?

  1. The 2:4 version removes more FLOPs, because it prunes whole groups
  2. Unstructured pruning loses more accuracy, so the layer must be made wider again
  3. The fixed pattern needs only a 2-bit position per kept weight and keeps memory access regular, so the hardware can skip the zeros; scattered zeros need stored indices and irregular access
  4. GPUs cannot store matrices that contain zeros
Show the answer

C. The fixed pattern needs only a 2-bit position per kept weight and keeps memory access regular, so the hardware can skip the zeros; scattered zeros need stored indices and irregular access

Speed comes from hardware built for a fixed pattern of zeros. Every group of four has exactly two kept values, so a matrix unit can fetch them with small fixed-size metadata. Arbitrary sparsity needs general indices and gather operations that cost more than the multiplications they save, until sparsity is very high.

Question 5

In distillation, what does raising the temperature TT do to the teacher's soft targets?

  1. It sharpens them toward a one-hot label
  2. It can change which class is most likely
  3. It changes only the gradients, not the probabilities
  4. It flattens them: the wrong classes get more probability and their ratios move toward 1, while the ranking stays the same
Show the answer

D. It flattens them: the wrong classes get more probability and their ratios move toward 1, while the ranking stays the same

Dividing all logits by T>1T>1 shrinks every gap vi−vjv_i-v_j by the same factor, so the probabilities become more even without reordering. The ratio of two probabilities is e(vi−vj)/Te^{(v_i-v_j)/T}, which tends to 1 as TT grows.

Go deeper

Further reading

  • B. Jacob et al., "Quantization and training of neural networks for efficient integer-arithmetic-only inference," CVPR (2018).
  • 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).
  • S. Han, J. Pool, J. Tran & W. J. Dally, "Learning both weights and connections for efficient neural networks," NeurIPS (2015).
  • G. Hinton, O. Vinyals & J. Dean, "Distilling the knowledge in a neural network," arXiv:1503.02531 (2015).