Skip to content
BIASED

Model compression

Pruning, structured sparsity, knowledge distillation, low-rank factorization and quantization; parameters, FLOPs and measured latency are different quantities.

Why compress

Adversarial examples made a network robust at the price of more training. At deployment the network meets a different budget. A phone shares a few gigabytes and a battery; a server pays for every multiply-add; a car needs an answer in milliseconds. A network trained for accuracy is usually larger than the function it computes requires.

Inference costs three things: memory for NN parameters (plus activations), compute (about one MAC per weight per input for a dense layer), and time and energy to move data and do arithmetic. Those three are not proportional. Fetching a number from off-chip DRAM dwarfs computing with it — 640640 pJ to read 3232 bits versus a few pJ for an fp32 MAC on a 4545 nm process. At batch size 11 a layer is usually memory-bound. Fewer and smaller weights help twice.

Magnitude pruning

Key idea. Many weights, units and directions contribute little. Compression removes the redundancy and usually fine-tunes briefly.

Magnitude pruning zeroes weights below a threshold chosen for sparsity ss:

W′=M⊙W,Mij=1[∣Wij∣>τ].W' = M \odot W, \qquad M_{ij} = \mathbf 1\big[|W_{ij}| > \tau\big].

Optimal Brain Damage ranks weight ii by saliency 12Hiiwi2\tfrac12 H_{ii} w_i^2 from a second-order expansion at a trained minimum (g≈0g \approx 0). Similar curvatures recover ranking by ∣wi∣|w_i|. Prune in rounds with retraining between them: without fine-tuning accuracy collapses; with it, AlexNet and VGG lost most parameters on ImageNet with no accuracy loss. On digits, 90%90\% sparsity after fine-tuning kept accuracy; past 95%95\% it fell quickly. Half the weights in a toy vector can carry only about 1.2%1.2\% of ∥w∥22\|w\|_2^2.

Structure and the lottery ticket

Unstructured zeros are scattered. CSR stores values and indices — about 8(1−s)8(1-s) bytes per original weight versus 44 dense — so s=0.5s = 0.5 saves nothing in memory and s=0.9s = 0.9 needs about 0.20.2 of the dense size. A dense matmul still multiplies the zeros; sparse kernels pay for irregular access and win only at very high sparsity on general hardware.

Structured pruning removes whole units, filters or attention heads. What remains is a smaller dense network that every library runs faster. Semi-structured 2:42{:}4 sparsity doubles throughput on Ampere sparse tensor cores.

The lottery ticket hypothesis: train dense, prune, reset survivors to their original initial values, repeat. Those subnetworks, at 1010–20%20\% size, match the full network; the same masks with fresh random init do not. Finding a ticket costs several full trainings — it explains pruning more than it saves time. For large ImageNet nets one resets to an early training point, not step zero.

Knowledge distillation

Knowledge distillation trains a different, smaller student to imitate a teacher. Labels say which class is correct; the teacher’s soft output says how much a 22 resembles a 33 or a 77. Temperature T>1T > 1 divides logits before the softmax and surfaces wrong-class structure:

L=α ℓCE(y,softmax⁡(z))+(1−α) T2 DKL(q∥p).\mathcal L = \alpha\, \ell_{\mathrm{CE}}(y, \operatorname{softmax}(z)) + (1-\alpha)\, T^2\, D_{\mathrm{KL}}(q \| p).

The T2T^2 factor offsets a soft gradient that shrinks like 1/T21/T^2. At inference the student uses T=1T = 1.

On digits a 24102410-parameter student matched the teacher when trained on labels alone — the task is easy. Without threes in the training set, label training recognized 0%0\% of test threes; soft targets alone recognized 92.7%92.7\%, reading similarity off the teacher’s distribution on other digits. A teacher trained with label smoothing transfers less: smoothing erases part of that structure. DistilBERT in the NLP course is BERT distilled to half depth; DeiT’s distillation token from Vision Transformers is a sibling idea.

Factorization and quantization

A layer WxWx with WW near rank rr becomes A(Bx)A(Bx) with A∈Rm×rA \in \mathbb R^{m \times r}, B∈Rr×nB \in \mathbb R^{r \times n}, costing r(m+n)r(m+n) MACs instead of mnmn when r<mn/(m+n)r < mn/(m+n). The Eckart–Young truncation of the SVD is optimal in Frobenius norm. The teacher’s 512×512512 \times 512 middle layer has break-even rank 256256; at r=8r = 8 (81928192 weights) digit accuracy stayed 0.9760.976 — training’s useful update was nearly low-rank, the observation behind LoRA. Depthwise-separable convolutions in MobileNet are a factorization built in from the start.

Quantization keeps every weight but stores fewer bits — int8 is 4×4\times smaller than fp32 and cheaper in arithmetic. Pruning plus quantization plus entropy coding made AlexNet 35×35\times and VGG-16 49×49\times smaller with no accuracy loss. The affine float↔int map and LLM methods belong to the NLP course; fp16/bf16 to computer architecture.

Measuring real speed-up

Parameters, MACs and wall-clock are three different quantities. A review of 8181 pruning papers found rare comparable measurements. On one CPU thread, the teacher’s dense 512×512512 \times 512 layer is the baseline; the same zeros left dense change nothing; CSR at 90%90\% sparsity was about 40×40\times slower; keeping 5151 of 512512 outputs structurally was about 5×5\times faster, not 10×10\times, because small products have fixed overheads.

Measure the deployment setting — hardware, batch, precision, library. Warm up, repeat, report the median; on GPU wait for the device. Report parameters or bytes, MACs, and latency, plus accuracy. Compare against a smaller dense model trained from scratch or distilled at the same size and speed.

Wrap-up and on to practice

Compression removes redundancy along four axes: which weights, which architecture, which rank, how many bits. Smaller is not automatically faster; fine-tuning is part of the method; easy digits overstate how far ratios can go.

The course’s catalogue of training and vision methods is complete. What remains is the process: silent failures, checks with a number to expect, and a recipe that catches bugs before they cost a week. The last topic is training networks in practice.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Magnitude pruning: density and erroroptional

    Zero out 90% of weights by |w|; density, Frobenius error, renormalization. Self-check in the notebook.

    ~15 min · easier on a computer · Model compression topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.