Model Compression and Distillation
A trained network and a deployable one are rarely the same object. This lesson is the toolkit for closing that gap: knowledge distillation transfers a large teacher's soft, information-rich logits into a small student; pruning deletes the weights that contribute least; quantization swaps 32-bit floats for 8- or 4-bit integers; and low-rank factorization replaces a fat matrix with two thin ones.
╌╌╌╌
A model that scores well on a held-out set has met only the first requirement. The
second is deployment, where the binding constraints are memory, latency, and
energy, not validation loss. A network with a billion parameters in fp32
occupies four gigabytes before a single activation is allocated, and that footprint
decides whether it runs on a phone, fits a GPU's memory, or meets a millisecond
service-level target. Model compression is the set of techniques that shrink a
trained network while giving back as little accuracy as possible. This lesson treats
the four that matter in practice and the order in which to combine them. It assumes
the practical methodology loop and
the regularization view from the regularization overview;
the largest payoffs land on the large language models
where the fp32 checkpoint will not even load.
Why compress: the accuracy–cost frontier
Three resources bind at inference, and they scale differently. Memory scales with the parameter count times bytes-per-weight . Compute scales with the multiply-accumulate count, roughly FLOPs per token for a dense layer. Energy is dominated not by arithmetic but by data movement: reading a weight from DRAM costs orders of magnitude more than the multiply it feeds.1
The methods do not move a model along a fixed curve; each defines its own accuracy-versus-cost frontier, and the practitioner picks the point. The goal is the Pareto frontier: for a target accuracy, the cheapest model; for a cost budget, the most accurate.
Compression works at all because a trained network is not a tight fit to its task. It carries far more capacity than the task's information content requires, and that slack is what every method removes.2 Removing it trades a small increase in bias for a large reduction in the effective parameter count; the frontier collects the points where that trade is favorable. A method that pushed past the frontier would raise bias faster than it cut cost, which is the over-compressed regime marked in red below.
| Resource | Scales with | Dominant cost | Compression lever |
|---|---|---|---|
| Parameter memory | bytes | DRAM capacity | quantization (cut ), pruning (cut ) |
| Compute | FLOPs / token | matrix multiply | distillation, structured pruning, low-rank |
| Activation memory | batch width depth | on-chip SRAM | quantization, smaller student |
| Energy | weight reads FLOPs | DRAM bandwidth | quantization, pruning (sparse skips) |
Knowledge distillation
The cheapest way to get a small, accurate model is often not to train a small model from scratch but to train it to imitate a large one. The large model is the teacher; the small one is the student. The student learns from the teacher's full output distribution, not just the hard label.3
Soft targets and dark knowledge
A network's final logits become a distribution through the softmax. Introduce a temperature that flattens it:
At this is the ordinary softmax. As grows the distribution spreads toward uniform, amplifying the small probabilities the teacher assigns to the wrong classes. Those small probabilities are the signal.
Temperature is what exposes dark knowledge. A confident teacher puts on the true class and on the rest, so at the soft target is indistinguishable from one-hot. Raising rescales the logit gaps and lifts those tiny probabilities into a usable gradient.
The distillation loss
The student is trained on a convex combination of two terms: a soft term that matches the teacher at temperature , and a hard term that matches the true label at . With teacher logits , student logits , true label , and mixing weight ,
Each term has a role.
- The KL term measures how far the student's softened distribution sits from the teacher's. Minimizing it over (the teacher is fixed) pulls the student's whole logit vector toward the teacher's, dark knowledge included.
- The factor rescales the soft loss. The gradient of the softened cross-entropy with respect to a logit carries a from the softmax argument and another from the target probabilities, so the soft gradient shrinks like . Multiplying by restores it to the same scale as the hard gradient, keeping meaningful as changes.
- The CE term anchors the student to the ground truth, so it does not inherit the teacher's mistakes wholesale. Setting trains purely on the teacher; ignores it.
The picture is a teacher feeding two channels into the student loss: a softened distribution and the hard label.
- 1freeze teacherteacher weights never updated
- 2for each minibatch do
- 3teacher logits (no gradient)
- 4student logits
- 5dark knowledge
- 6ground truth
- 7
- 8student step only
- 9return
Pruning
Distillation builds a small model; pruning carves one out of a large model by deleting weights. The premise is that trained networks are heavily over-parameterized and most weights contribute little.
Magnitude pruning
The simplest and strongest baseline ranks weights by absolute value and zeros the smallest. A weight near zero contributes little to any activation, so removing it perturbs the function least. That such weights exist in bulk is the same over-parameterization that lets large networks fit and still generalize.4
where is the target sparsity. Pruning in one shot to high sparsity destroys accuracy; to address this, alternate pruning with retraining so the surviving weights absorb the slack.
- 1train to convergencedense model first
- 2for round to do
- 3ramp sparsity gradually
- 4the -th percentile of
- 5for each weight do
- 6if then
- 7and freeze itmask out, never updated again
- 8retrain unmasked weights for a few epochsrecover accuracy
- 9return the sparse
The loop matters more than the pruning rule. One-shot pruning to sparsity moves the weights far off the trained optimum in a single jump; the surviving weights never had a chance to compensate. Ramping from to over rounds, each followed by a short retrain, keeps the model near a good basin the whole way down.
Structured versus unstructured
Where the zeros land decides whether the chip can exploit them.
| Granularity | What is removed | Sparsity pattern | Speedup on dense hardware |
|---|---|---|---|
| Unstructured | individual weights | scattered | none (needs sparse kernels) |
| Structured: channel | whole conv filters / channels | dense sub-tensor | yes, shrinks the matrix |
| Structured: head | whole attention heads | dense sub-tensor | yes |
| Structured: block | blocks (e.g. 2:4) | semi-structured | yes (tensor-core support) |
Unstructured pruning reaches the highest sparsity at a given accuracy because it can remove any weight, but the leftover dense tensor with scattered zeros runs no faster on a GPU that schedules every multiply regardless. Structured pruning removes entire rows, columns, channels, or heads, leaving a smaller dense matrix that standard kernels run faster.
The Lottery Ticket Hypothesis
Iterative magnitude pruning raises a question: could the pruned subnetwork have been trained alone from the start? The answer is yes, but only with the original initialization.
The practical procedure to find the ticket is iterative: train, prune the smallest magnitudes, rewind the survivors to their original initial values, and retrain. The lesson is that sparsity is a property of the trainable subnetwork, not a post-hoc cleanup. It reframes pruning as discovering structure the dense network already contained.
Quantization
Quantization attacks the bytes-per-weight factor directly: store and compute in
low-precision integers instead of 32-bit floats. The standard first step is fp32 int8, a memory cut, with integer matrix-multiply units that are faster
and far more energy-efficient than their floating-point counterparts.1
The affine quantization map
Map a real value in a range to an 8-bit integer through a scale and a zero-point :
where is the dequantized value and the round-trip error is bounded by half a quantization step, . The scale and zero-point are fixed by the range:
The zero-point ensures the real value maps to an exact integer, which keeps zero-padding and ReLU outputs exact. A symmetric variant fixes and uses a range , trading one representable level for simpler integer arithmetic.
For example, take a weight tensor whose observed range is
quantized to unsigned int8, so
and . The scale and zero-point are
The weight then quantizes to , and dequantizes to , an error of , safely under the half-step bound .
The reason integer inference is fast is that the multiply itself never leaves the integer domain. For a matrix product with weight scale , zero-point , and activation scale , zero-point , substitute the affine maps and the real product factors into an integer accumulation times a single float rescale:
The inner sum runs entirely in int8-times-int8-accumulated-in-int32, which is
what the integer tensor units execute; the scalar multiplies the accumulated
result once at the end. All the arithmetic that scales with the matrix size is integer;
the lone floating-point operation is per output.
PTQ versus QAT
Two regimes set the scales. Post-training quantization (PTQ) quantizes a finished model and calibrates ranges on a small unlabeled set, with no retraining. It is fast and free of the training loop, but at low bit-widths the rounding error can reduce accuracy. Quantization-aware training (QAT) simulates quantization during training so the weights adapt to the rounding.
The obstacle in QAT is that the rounding function has zero gradient almost everywhere. The solution is the straight-through estimator (STE): in the forward pass apply real rounding; in the backward pass pretend rounding was the identity, passing the gradient through unchanged.
| Aspect | PTQ | QAT |
|---|---|---|
| Retraining | none (calibrate only) | full fine-tune with simulated quant |
| Cost | minutes | hours to days |
Accuracy at int8 | good for robust models | better, near-lossless |
Accuracy at int4 | often poor | recovers much of the gap |
| Gradient trick | not needed | straight-through estimator |
Quantizing large language models
LLMs break naive int8 quantization for one reason: a small number of
outlier features in the activations carry magnitudes orders larger than the
rest, and a single tensor-wide scale stretched to cover them quantizes everything
else to near-zero.
The main LLM quantization methods each handle this differently.
| Method | Bits | Idea | Handles outliers by |
|---|---|---|---|
LLM.int8() | 8 | mixed-precision decomposition | keeping outlier columns in fp16, rest in int8 |
| GPTQ | 3–4 | second-order weight rounding | layer-wise error compensation via the Hessian |
| AWQ | 4 | activation-aware scaling | protecting salient weight channels by activation scale |
| QLoRA / NF4 | 4 | normal-float storage + LoRA | a quantile-optimal 4-bit grid for normal weights |
LLM.int8()splits each matrix multiply: the few outlier feature columns run infp16, the rest inint8, recombined exactly. It is lossless atint8for models past the scale where outliers emerge.- GPTQ quantizes weights one layer at a time, after each rounding step adjusting the still-unquantized weights to compensate for the error introduced, using curvature from the layer's Hessian. It reaches 3–4 bits with small loss.
- AWQ observes that not all weights matter equally; the salient ones are those multiplying large-activation channels. It scales those channels up before quantizing so they keep precision, then folds the scale back.
- QLoRA stores the frozen base model in NF4, a 4-bit floating format whose levels are the quantiles of a normal distribution (matching the empirical weight histogram), and fine-tunes only small LoRA adapters on top. This makes 4-bit fine-tuning of very large models fit on a single GPU.
Low-rank factorization
A linear layer's weight matrix holds parameters. If is approximately low-rank, replacing it with a product of two thin matrices is a direct compression.
The parameter count drops from to , a win whenever . The best rank- approximation in Frobenius norm is the truncated SVD: keep the top singular values.
The tie to LoRA
Low-rank structure also drives the most common parameter-efficient fine-tuning method. LoRA freezes the pretrained weight and learns only a low-rank update, so the adapted weight is
Only and are trained, a tiny fraction of the parameters, and at inference folds into at no added latency. The premise is that the fine-tuning update is intrinsically low-rank even when is not. Combined with a 4-bit frozen base, this recovers the QLoRA method above: quantize to NF4, train in higher precision.
Combining methods
The four levers are largely orthogonal and routinely stacked. Distillation produces
a small dense student; pruning sparsifies it; quantization shrinks each surviving
weight to int8 or int4; low-rank factorization or LoRA handles the fine-tuning.
What trades off against what:
| Method | Memory cut | Latency win | Accuracy hit | Hardware need |
|---|---|---|---|---|
| Distillation | large (small student) | large | small–moderate | none (trains a normal net) |
| Unstructured pruning | moderate | none on dense HW | small at moderate sparsity | sparse kernels for speedup |
| Structured pruning | moderate | yes | moderate (coarser deletions) | none |
Quantization (int8) | yes | minimal | integer tensor units | |
Quantization (int4) | yes | small with GPTQ/AWQ/QAT | 4-bit kernels | |
| Low-rank / LoRA | matrix-dependent | yes if rank low | small if spectrum decays | none |
Compression in the large-model era
The four levers above predate large language models; scaling to billions of parameters sharpened each into a specialized method that Goodfellow does not cover.
Post-training quantization grew precise. Naively rounding an LLM's weights to int4
sharply degrades accuracy, but GPTQ (Frantar et al., 2023, ICLR) quantizes one weight column
at a time and adjusts the not-yet-quantized weights to compensate for the error each
rounding introduces, using second-order (Hessian) information. AWQ (Lin et al., 2024,
MLSys) observes that a small fraction of salient
weight channels — identifiable from
the activation magnitudes — carry most of the model's quality, and protects those while
aggressively quantizing the rest. Both recover near-full-precision accuracy at 4 bits with
no retraining, exactly the int4-with-GPTQ/AWQ row in the table above.
QLoRA (Dettmers et al., 2023, NeurIPS) fuses quantization with the parameter-efficient fine-tuning from the transfer-learning lesson: freeze the base model at 4-bit precision and train only the LoRA adapters in higher precision on top, which lets a single consumer GPU fine-tune a 65-billion-parameter model that would not otherwise fit in memory. Compression and adaptation, treated separately in this lesson, become one step.
Pruning got a theory and a one-shot method. The lottery ticket hypothesis (Frankle
& Carbin, 2019, ICLR) argues that a dense network contains a sparse subnetwork — a
winning ticket
— that, trained in isolation from the original initialization, matches the
full model, which reframes pruning as finding that subnetwork rather than degrading the
dense one. SparseGPT (Frantar & Alistarh, 2023, ICML) then made pruning practical at
LLM scale, removing half the weights of a 175-billion-parameter model in one pass with
negligible accuracy loss, using the same error-compensation idea as GPTQ. The principle
is unchanged from this lesson — trade capacity for cost, measure the hit on the deployment
metric — but the methods now assume a frozen, pretrained giant rather than a model trained
from scratch.
Takeaways
- Compression is a deployment problem, not a training one. The binding constraints are memory, latency, and energy on the target device, and energy is dominated by weight movement, not arithmetic. Each method defines its own accuracy–cost frontier; pick the operating point.
- Distillation transfers dark knowledge. A student trained on a teacher's temperature-softened logits learns the teacher's relative confidence over wrong classes, a richer signal than one-hot labels. The KD loss mixes a -scaled KL term with a hard cross-entropy; the keeps the soft gradient on scale.
- Pruning deletes weights; structure decides the speedup. Magnitude pruning with iterative retraining reaches high sparsity, but only structured pruning (channels, heads, blocks) speeds up dense hardware. The Lottery Ticket Hypothesis says the winning subnetwork was already present at initialization.
- Quantization cuts bytes-per-weight. The affine map
takes
fp32toint8for a cut; QAT uses the straight-through estimator to train through rounding, and per-channel scales are essential belowint8. LLMs need outlier-aware methods (LLM.int8(), GPTQ, AWQ, NF4/QLoRA). - Low-rank factorization replaces a fat matrix with two thin ones when the spectrum decays (Eckart–Young), and the same structure powers LoRA's low-rank fine-tuning update.
- Stack the methods in order: distill, then prune, then quantize, measuring wall-clock latency on the real hardware at each step.
Footnotes
- Stevens, Deep Learning with PyTorch, Part III — deployment: model size, latency, and the memory and bandwidth costs that bind at inference, with reduced-precision (
int8) storage and compute as the first lever. ↩ ↩2 - Goodfellow, Deep Learning, §5.4–5.5 — the bias--variance view of generalization: a compressed model trades a small increase in bias for a large cut in the effective number of parameters. ↩
- Goodfellow, Deep Learning, §7.11 — ensemble methods average many models to reduce variance; the distillation setup trains one fast model to reproduce that averaged output distribution. ↩ ↩2
- Goodfellow, Deep Learning, §5.2 — capacity, over-parameterization, and why a large model can fit its task while most of its representational budget is redundant, leaving weights that can be removed. ↩
╌╌ END ╌╌