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 .
An illustrative GPU streams 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 bytes, so each token needs at least 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.
| Technique | What it shrinks | What it costs | Taken further in |
|---|---|---|---|
| Quantization | bits per weight, and per activation | minutes to hours after training, or a training run | Quantization in Depth |
| Pruning | the number of nonzero weights, or whole channels, heads and layers | usually some retraining | Pruning, Sparsity & Lottery Tickets |
| Distillation | the model itself: a smaller student trained to imitate a teacher | a full training run of the student | Knowledge Distillation |
| Low-rank factorization | a matrix replaced by a product of rank : parameters instead of | fine-tuning | Low-Rank Adaptation in Depth, for low-rank updates |
| Efficient architectures | FLOPs and memory by design: depthwise separable convolutions, grouped-query attention, mixtures of experts | chosen before training | Efficient ConvNets, Anatomy of a Modern LLM, Mixture of Experts |
| Serving techniques | wasted memory and idle arithmetic: continuous batching, paged KV caches, speculative decoding | no change to the model | Serving Language Models, Speculative Decoding |
Rounding to a grid
Two errors compete. Inside the range, rounding moves a value by at most . 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 bits per weight.
Activations after a ReLU lie in . You quantize them to 8 bits symmetrically (, codes to , ). What goes wrong?
- Nothing: at 8 bits symmetric and asymmetric quantization are equivalent
- 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
- The value 0 can no longer be represented exactly
- 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
No activation is negative, so codes to are wasted. Asymmetric quantization with and 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.
Take a layer with . Quantize row of symmetrically with its own scale (per output channel), and the input with one scale and zero point (per tensor, or per token in a batch):
Both scales are constant along the summed index , so they factor out of the dot product and leave integers inside:
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 they write the combined factor as a fixed-point number and a bit shift, so the whole network runs on integer-only hardware.
A scale that changed with , 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:
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 identityThe 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:
| Pattern | Which weights may be zero | Accuracy | Speed on GPUs |
|---|---|---|---|
| Unstructured | any individual weight | the best at a given sparsity | little 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:4 | at most 2 nonzeros in every 4 consecutive weights | matched 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 |
| Structured | whole channels, filters, attention heads or layers | the lowest at a given parameter count | a smaller dense network, fast on any hardware |
A row of weights reads , in two groups of four. Which weights does 2:4 magnitude pruning keep?
- : the four largest in the row
- and : the two largest in each group of four
- and : the first two positive weights in each group
- and : one weight per group
Show the answer
B. and : 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 become soft targets through a softmax at temperature , the student's logits are softened the same way, and the student is trained on a mix of the soft targets and the true label :
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 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 bits per example for 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 . 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.
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?
- It performs a quarter as many FLOPs
- 4-bit numbers are multiplied four times faster by tensor cores
- Decoding is limited by memory bandwidth, and the weights it must stream each step are a quarter the size
- 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.
You quantize values in to 8 bits asymmetrically, with codes to . What are the scale and the zero point?
Show the answer
D.
and . Check the ends: maps to , and to . The real 0 is the code 64 exactly.
In quantization-aware training, what does the straight-through estimator do?
- It uses the rounded weights in the forward pass and treats rounding as the identity in the backward pass
- It removes the rounding from both passes, so training is ordinary full-precision training
- It computes the exact derivative of the rounding function
- 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).
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?
- The 2:4 version removes more FLOPs, because it prunes whole groups
- Unstructured pruning loses more accuracy, so the layer must be made wider again
- 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
- 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.
In distillation, what does raising the temperature do to the teacher's soft targets?
- It sharpens them toward a one-hot label
- It can change which class is most likely
- It changes only the gradients, not the probabilities
- 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 shrinks every gap by the same factor, so the probabilities become more even without reordering. The ratio of two probabilities is , which tends to 1 as grows.
Go deeper
- Quantization in Depth · Low-bit formats, outlier features, GPTQ and quantization-aware training.
- Pruning, Sparsity & Lottery Tickets · Magnitude and second-order pruning, sparsity hardware can use, and subnetworks that train from the start.
- Knowledge Distillation · Soft targets, dark knowledge and training small models from large ones.
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).