Practical Deep Learning/Model Compression and Distillation

Lesson 10.63,410 words

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.

The accuracy--cost frontier. Each method pushes the achievable curve down and left; the dashed line is the dense baseline.
ResourceScales withDominant costCompression lever
Parameter memory bytesDRAM capacityquantization (cut ), pruning (cut )
Compute FLOPs / tokenmatrix multiplydistillation, structured pruning, low-rank
Activation memorybatch width depthon-chip SRAMquantization, smaller student
Energyweight reads FLOPsDRAM bandwidthquantization, 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.

Temperature flattens the teacher softmax, lifting wrong-class probabilities (dark knowledge) into a learnable signal for the student.

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.

Distillation: a frozen teacher's softened logits and the true label both supervise the student through the combined KD loss.
Algorithm:Distill(ft,fs,D,T,α)\textsc{Distill}(f_t, f_s, \mathcal{D}, T, \alpha) — train a student to match a frozen teacher
  1. 1
    freeze teacher ftf_t
    teacher weights never updated
  2. 2
    for each minibatch (x,y)D(x, y) \in \mathcal{D} do
  3. 3
    ztft(x)z_t \gets f_t(x)
    teacher logits (no gradient)
  4. 4
    zsfs(x)z_s \gets f_s(x)
    student logits
  5. 5
    LsoftT2KL(p(zt;T)p(zs;T))L_{\text{soft}} \gets T^2 \cdot \mathrm{KL}\parens{p(z_t; T) \,\|\, p(z_s; T)}
    dark knowledge
  6. 6
    LhardCE(y,p(zs;1))L_{\text{hard}} \gets \mathrm{CE}\parens{y,\, p(z_s; 1)}
    ground truth
  7. 7
    LαLsoft+(1α)LhardL \gets \alpha\, L_{\text{soft}} + (1 - \alpha)\, L_{\text{hard}}
  8. 8
    θsθsηθsL\theta_s \gets \theta_s - \eta\, \nabla_{\theta_s} L
    student step only
  9. 9
    return fsf_s

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.

Algorithm:IterativePrune(fθ,s,k)\textsc{IterativePrune}(f_\theta, s, k) — reach sparsity ss over kk prune--retrain rounds
  1. 1
    train fθf_\theta to convergence
    dense model first
  2. 2
    for round r=1r = 1 to kk do
  3. 3
    srsr/ks_r \gets s \cdot r / k
    ramp sparsity gradually
  4. 4
    τ\tau \gets the srs_r-th percentile of {θj}\braces{\abs{\theta_j}}
  5. 5
    for each weight θj\theta_j do
  6. 6
    if θj<τ\abs{\theta_j} < \tau then
  7. 7
    θj0\theta_j \gets 0 and freeze it
    mask out, never updated again
  8. 8
    retrain unmasked weights for a few epochs
    recover accuracy
  9. 9
    return the sparse fθf_\theta

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.

Iterative prune--retrain. Each round tightens the sparsity target, masks the smallest survivors, and retrains the rest to recover accuracy.

Structured versus unstructured

Where the zeros land decides whether the chip can exploit them.

GranularityWhat is removedSparsity patternSpeedup on dense hardware
Unstructuredindividual weightsscatterednone (needs sparse kernels)
Structured: channelwhole conv filters / channelsdense sub-tensoryes, shrinks the matrix
Structured: headwhole attention headsdense sub-tensoryes
Structured: block blocks (e.g. 2:4)semi-structuredyes (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.

Unstructured pruning scatters zeros (left); structured pruning deletes whole rows/columns, leaving a smaller dense matrix (right).

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.

The affine map: a continuous range is rounded onto evenly spaced integer levels; each real value snaps to its nearest grid point.

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.

The straight-through estimator. The forward pass rounds; the backward pass replaces the flat rounding gradient with the identity so a signal reaches .
AspectPTQQAT
Retrainingnone (calibrate only)full fine-tune with simulated quant
Costminuteshours to days
Accuracy at int8good for robust modelsbetter, near-lossless
Accuracy at int4often poorrecovers much of the gap
Gradient tricknot neededstraight-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.

MethodBitsIdeaHandles outliers by
LLM.int8()8mixed-precision decompositionkeeping outlier columns in fp16, rest in int8
GPTQ3–4second-order weight roundinglayer-wise error compensation via the Hessian
AWQ4activation-aware scalingprotecting salient weight channels by activation scale
QLoRA / NF44normal-float storage + LoRAa quantile-optimal 4-bit grid for normal weights
  • LLM.int8() splits each matrix multiply: the few outlier feature columns run in fp16, the rest in int8, recombined exactly. It is lossless at int8 for 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.

A fat matrix factored into two thin matrices of inner dimension , cutting parameters from to .

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:

MethodMemory cutLatency winAccuracy hitHardware need
Distillationlarge (small student)largesmall–moderatenone (trains a normal net)
Unstructured pruningmoderatenone on dense HWsmall at moderate sparsitysparse kernels for speedup
Structured pruningmoderateyesmoderate (coarser deletions)none
Quantization (int8)yesminimalinteger tensor units
Quantization (int4)yessmall with GPTQ/AWQ/QAT4-bit kernels
Low-rank / LoRAmatrix-dependentyes if rank lowsmall if spectrum decaysnone

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 fp32 to int8 for a cut; QAT uses the straight-through estimator to train through rounding, and per-channel scales are essential below int8. 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

  1. 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
  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.
  3. 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
  4. 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 ╌╌