Han et al. cut AlexNet from 61 M to 6.7 M weights, 9× fewer. Yet a GPU only runs faster when the zeros follow a pattern it can skip.
Learn how to remove most of a trained network, which pieces to cut, and which cuts a real chip can turn into speed.
Pick a way to prune, then drag the sparsity slider. Compare how much the output changes with how much faster a dense GPU runs. Then we build, piece by piece, the problem, the pruning loop, the granularities and the criteria that choose what to cut.
You need matrix multiplication (a layer is a table of weights times a vector) and a little Python. We build the rest from zero.
Based on Lecture 3 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 2, NN Building Blocks and leads into Lecture 4, Pruning II.
Illustrative: one made-up 8 by 8 weight matrix and 48 random inputs. The output error is measured live: how far the pruned layer's output moves, as a share of the dense output's size. The 2× for 2:4 is the peak figure in the lecture; the measured BERT speedup it quotes is 1.5×. The row-pruning speedup assumes the work shrinks with the matrix.
Chapter 0
See what one weight costs to fetch, and why that makes a smaller network the cheapest speedup there is
Your phone runs a camera model that names a plant. For every frame, it reads the whole model out of memory once. A model is a long list of numbers called weights, like the dials on a huge mixing desk. Each read of a weight costs energy.
The lecture prices that read with a table from Mark Horowitz's 2014 talk: the energy of basic operations on a 45 nm chip at 0.9 V, in picojoules (pJ), trillionths of a joule.
| Operation | Energy | What it is |
|---|---|---|
| 32 bit int ADD | 0.1 pJ | Add two whole numbers |
| 32 bit float ADD | 0.9 pJ | Add two decimal numbers |
| 32 bit register file | 1 pJ | Read a number held right beside the arithmetic unit |
| 32 bit int MULT | 3.1 pJ | Multiply two whole numbers |
| 32 bit float MULT | 3.7 pJ | Multiply two decimal numbers |
| 32 bit SRAM cache | 5 pJ | Read a number from small, fast memory on the chip |
| 32 bit DRAM memory | 640 pJ | Read a number from the large, slow memory off the chip |
SRAM is small, fast memory on the chip, like a notepad on your desk. DRAM is big memory on a separate chip, like a library across the road. A trained network does not fit on the notepad, so its weights live in the library.
The slide's headline: more data movement means more memory reads, and more energy. A DRAM read is about 200 times a cheap operation, and 640 / 3.7 = 173 times a float multiply.
A layer does multiply-accumulates (MACs): multiply a weight by an input and add it to a running total. One float MAC costs 3.7 + 0.9 = 4.6 pJ. Take a fully connected layer of 1,000,000 weights at batch size 1: it uses each weight once.
AlexNet, an image network from 2012, has 61 million weights. One pass reads 61,000,000 × 640 pJ = 39 mJ from DRAM. At 30 frames a second that is about 1.2 W, for fetching weights alone.
The slide then asks: how should we make deep learning more efficient? If most of the cost is fetching weights, fetch fewer. That is pruning: remove the weights that matter least, so the chip never fetches them and never multiplies by them.
Top: the lecture's seven operations on a log scale, where a bar one quarter longer means ten times more energy. Bottom: one layer of 1,000,000 weights. Drag the share you keep.
Energies: the lecture's Horowitz table (45 nm, 0.9 V). The layer is illustrative: 32 bit weights at batch size 1, each fetched once, pruned weights fully skipped. Real sparse formats also store indices, which adds some cost back.
Keep 10% and the fetch bill drops from 640 µJ to 64 µJ. Each kept weight costs one fetch, so the bill scales straight with the count.
Part 1 of MIT 6.5940 is efficient inference, with four tools: pruning, quantization, neural architecture search and knowledge distillation. Of the five pruning questions (what, which pattern, which weights, how much, how to retrain), this lecture answers the first three.
Chapter 1
Write the problem as one formula, then see why you cannot solve it by trying every answer
You pack a suitcase with a 10 kg limit and a 25 kg pile. For each item you ask: if it stays home, how much does the trip suffer? Pruning asks that of each weight, and the trip is the accuracy.
A neural network is a stack of layers of neurons. Each neuron multiplies its inputs by weights, adds them, and passes the sum through a simple function. A weight joins two neurons, so the lecture also calls it a synapse. Pruning synapses deletes single connections. Pruning neurons deletes a whole unit with every connection into and out of it.
LeCun et al. named the idea Optimal Brain Damage in 1989, and Han et al. revived it in 2015. The brain does it too: about 2,500 synapses per neuron at birth, 15,000 at age two to four, 7,000 in an adult.
Call the input x and the trained weights W. Call the pruned weights WP: the same table with some entries set to exactly zero. The loss L says how badly the network does. The budget N is the most non-zero weights you may keep.
Arg min over W-P of L of x and W-P, subject to the L-zero norm of W-P being at most N.
List every way to zero out weights so that at most N stay. Compute the loss L for each W-P. Keep the one with the lowest loss.
With made-up numbers: six weights and N = 3 give 20 masks. Compute L for all 20 and keep the lowest.
With M weights and room for N, there are "M choose N" masks. Drag M and read the count.
Blue dots stay, hollow dots go. Drag M, then press the button for another random half.
The counts are exact. The time assumes an illustrative machine that tests one billion masks a second; a real loss evaluation takes far longer.
At 20 weights there are 184,756 masks. At 64 there are about 1.8 × 1018, some 58 years at a billion tests a second. A real layer has millions. So nobody solves the formula exactly, and every practical method is an approximation.
The choices combine. You can score by size and cut whole channels, or score by curvature and cut single weights.
Symptom: the report says 90% sparse, and the model file is the same size. Measure: the vector (0.0001, 0, 2, 0.0003) has L0 norm 3, because only an exact zero is not counted. Fix: set pruned weights to exactly zero, and keep a mask so they stay zero.
pythonimport torch
w = torch.tensor([0.0001, 0.0, 2.0, 0.0003])
print((w != 0).sum().item()) # L0 norm: 3 non-zeros
mask = (w.abs() > 0.001).float() # 1 = keep, 0 = prune
print((w * mask).count_nonzero().item()) # after pruning: 1 non-zero
Chapter 2
Watch accuracy fall as you cut, and see how retraining and repeating push the cliff further away
Cut a third of a wild hedge in one afternoon, and it looks thin for weeks. Trim a little each week, and it fills in around every cut. A network behaves the same way.
The lecture's chart (Han et al., 2015) plots accuracy loss against the pruning ratio, the share of weights removed. It adds one curve per step. The values are read off the slide.
Weights train together, so each one sits where it is because of the others. Take two nearly equal inputs x1 and x2, and y = 2x1 + 2x2, about 4x. Prune the second weight: y = 2x1, about 2x. The output halves, and the loss rises.
Finetuning reruns training on the survivors. The output is too small, so the gradient pushes the first weight from 2 toward 4. Then y = 4x1: one weight does the job of two. Small cuts work better, because each leaves a small error to repair before the next.
Each curve is test error over the full model's error, on a log scale. Lower is better. Drag the ratio, and switch curves on and off.
Toy run live in your browser: a linear model with 40 correlated inputs, 150 training and 500 test examples, all made up. Pruning drops the smallest weights. Finetune refits the survivors exactly. Iterative drops one weight at a time and refits.
At 50% the plain cut more than doubles the error. The finetuned model sits at about 1.3 times the full model, and the iterative one matches the full model. Near 90% all three suffer, and iterative is still lowest.
In a deep network, finetuning is normal training plus one rule: multiply the mask back in after every update, so pruned weights stay at exactly zero.
pythondef finetune(model, masks, loader, opt, epochs):
for _ in range(epochs):
for x, y in loader: # x: (B, ...), y: (B,)
loss = loss_fn(model(x), y)
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
for p, m in zip(model.parameters(), masks):
p.mul_(m) # pruned weights back to exactly 0
def iterative_prune(model, steps=(0.2, 0.4, 0.6, 0.8)):
for s in steps: # a little more each round
masks = [magnitude_mask(p, s) for p in model.parameters()]
finetune(model, masks, loader, opt, epochs=2)
Symptom: the model is 80% sparse before finetuning and 12% after. Measure: count the zeros in each weight tensor after training. Fix: apply the mask after every optimizer step. The optimizer does not know which weights you pruned, so it moves them.
Chapter 3
Compare weights saved with work saved on five real networks, and meet the hardware that turns zeros into speed
A publisher cuts a book's appendix. The book is cheaper to print, but no faster to read. Pruning has the same split between what you store and what you compute.
The parameter reduction counts the weights left: file size and fetches. The MACs reduction counts the multiply-accumulates left: arithmetic. A fully connected layer uses each weight once per input, so its MACs equal its weights. A convolution reuses each weight at every output position, so its MACs are its weights times the positions.
AlexNet's three fully connected layers hold 9,216 × 4,096 + 4,096 × 4,096 + 4,096 × 1,000 = 58.6 million of its 61 million weights. They do only 58.6 million MACs. The convolutions hold few weights and do most of the arithmetic. Most of the cut falls in the fully connected layers, so weights fall 9 times and MACs only 3 times.
Top pair: parameters before and after pruning. Bottom: the share of MACs left. A shorter bar is a bigger saving.
Numbers: the lecture's table (Han et al. 2015, and S. Han's Stanford talk). The share of MACs left is one over the table's MACs reduction.
VGG-16 matches AlexNet: 12 times fewer weights, 5 times fewer MACs. GoogleNet and ResNet50 flip it: MACs fall 5 and 6.3 times, weights only 3.5 and 3.4 times. Their pruned weights sat in layers that reuse each weight many times. So count what you must save: parameters for storage, MACs for arithmetic.
The lecture shows captions from NeuralTalk, an LSTM (a network that writes one word at a time). Pruned 90%, it says "a basketball player in a white uniform is playing with a basketball". The baseline said "with a ball". The hardware the lecture lists:
| Hardware | What the slide says |
|---|---|
| EIE (Han et al., ISCA 2016), ESE (FPGA 2017) | Custom accelerators for sparse networks |
| SpArch (HPCA 2020), SpAtten (HPCA 2021) | Later sparse accelerators |
| NVIDIA A100 | 2:4 sparsity (Chapter 6): 2× peak, 1.5× measured on BERT |
| AMD Xilinx Vitis AI Optimizer | Prune and finetune: 5× to 50× less model complexity with minimal accuracy impact |
The A100 gap from 2 to 1.5 is normal. Only some layers are sparse, and memory steps do not speed up.
Symptom: a team reports "90% sparse" and sees no change in GPU latency. Measure: time the same input through both models on the same card. Fix: check the pattern of the zeros. A chip saves only the zeros it can skip.
Chapter 4
Compare cutting single weights with cutting whole rows, and see which one a plain chip can use
A bookcase holds eight shelves of eight books, and half must go. Remove the 32 you like least, and every shelf has gaps. Remove four whole shelves, and the bookcase is half as tall with every shelf full. This choice is pruning granularity: the size of the piece you remove.
A fully connected layer multiplies an input vector x by a weight matrix W. Each row of W makes one output, so a row is one neuron. The lecture prunes an 8 by 8 matrix two ways:
| Property | Fine-grained (unstructured) | Coarse-grained (structured) |
|---|---|---|
| What goes | Any single weight | Whole rows |
| Choice of indices | More flexible | Less flexible: a subset of the fine-grained masks |
| Speed | Hard to accelerate (irregular) | Easy: just a smaller matrix |
A chip multiplies in blocks of neighbouring numbers. A 4 by 8 matrix is a smaller dense matrix: same code, half the work. Scattered zeros leave the matrix 8 by 8. To skip them, the chip needs an index per weight, extra reads and irregular jumps. A plain GPU multiplies by the zeros instead, and saves nothing.
Row pruning must take a whole row, big weights too. Score the damage by squared weight, a rough stand-in for harm, on four rows:
The total is 3.30. Remove 6 of 12 weights. Scattered, keep the six biggest (0.9, 0.9, 0.8, 0.7, 0.6, 0.3): their squares sum to 3.20, so you drop 3%. By rows, keep A and C: 2.31, so you drop 30%. Same budget, ten times the damage.
Left: keep the biggest weights anywhere. Right: keep the heaviest whole rows. Filled cells stay, hollow cells go.
Illustrative: the hero's made-up 8 by 8 matrix and 48 random inputs. The device measures output error live, as a share of the dense output, and scores rows by the sum of absolute weights. MACs count every stored weight a dense chip runs.
At 4 rows kept, both masks keep 32 weights. The scattered one moves the output by 26%, the row mask by 62%. But on a dense chip the scattered matrix still runs all 64 MACs, and the packed rows run 32. A removed row also lets the next layer drop its matching column, which Chapter 7 uses.
Symptom: the model is 50% sparse, the profiler shows 64 MACs per input, and latency has not moved. Measure: count the MACs the kernel runs, not the non-zeros stored. Fix: use hardware that skips zeros (Chapter 6), or prune in a pattern that gives a smaller dense matrix.
Chapter 5
Open a convolution layer, name its four dimensions, and slide from the most scattered cut to the most regular one
A sharpening filter is a 3 by 3 grid of numbers that slides over a photo. A vision network runs thousands of such filters. A convolution layer turns an input of several channels (like the red, green and blue planes) into an output of several channels. Its weights have four dimensions, [co, ci, kh, kw]:
Each output channel has one filter of ci kernels. The lecture's toy layer has co = 3, ci = 2 and 3 by 3 kernels: 3 × 2 × 9 = 54 weights. Four dimensions give more ways to cut. The lecture lists five, from irregular to regular (Mao et al., CVPR workshop):
The slide jokes that the shapes look like Tetris. The cleaner the blocks, the easier a chip finds them.
Each small grid is one 3 by 3 kernel. Rows are output channels, columns are input channels. Filled cells stay, hollow cells go.
Illustrative: co = 3, ci = 2, masks from a fixed seed, not by importance. We made up the four 2 by 2 pattern shapes. Decisions counts the separate keep or prune facts the mask stores.
Fine keeps 27 of 54 weights with 54 separate decisions. Channel keeps the same 27 with one decision: keep input channel 1, drop channel 2. The chip must read the mask before it can use it. Fifty-four bits are a table to fetch and decode; one bit is read once. Each step to the right gives up some freedom for a cheaper mask.
Only channel pruning changes the shape. Drop one input channel, and [3, 2, 3, 3] becomes [3, 1, 3, 3], a smaller dense tensor that any routine can run. On a 14 by 14 output map, the MACs go from 54 × 196 = 10,584 to 27 × 196 = 5,292. The other four keep holes in the old shape. Pattern-based is the clever middle: with few shapes, a chip can have a fast path for each.
Symptom: you drop input channel 2 of layer B, and the network crashes ("expected 3 channels, got 2") or wastes work. Measure: print the shapes of neighbouring layers. Layer A's output channels must equal layer B's input channels. Fix: also drop output filter 2 of layer A, which fed only that channel.
Chapter 6
Give up a little freedom to get a pattern that hardware can read, and see exactly how the compressed matrix is stored
One library lets a book go on any free spot: flexible, and hard to search. Another puts exactly two books on every shelf of four slots: a little wasteful, and anyone finds a book fast.
Fine-grained pruning is the first library. Its indices are free, so it usually reaches the largest compression (AlexNet 9 times, VGG-16 12 times). It can speed up custom hardware such as EIE, but not a GPU, at least not easily.
N:M sparsity is the second library, a form of pattern-based pruning. Cut each row into groups of M neighbouring weights, and let N survive in each group. The slide words it as "N of them is pruned"; for 2:4 both readings give half. We count N as kept, as NVIDIA does.
2:4 sparsity is exactly 50% sparse. NVIDIA's Ampere GPUs, such as the A100, run it up to 2 times faster, and it usually keeps accuracy across many tasks. The trick: every group has exactly two survivors, so no group has more work than its neighbours.
The chip stores the non-zero values packed together, plus a 2-bit index for each value. Take the group 0.9, −0.1, 0.4, −0.7. Keep 0.9 at position 0 and −0.7 at position 3. Store values (0.9, −0.7) and indices 00 and 11. To multiply by inputs a0 to a3, the chip reads the indices and computes 0.9a0 − 0.7a3: 2 MACs instead of 4.
With 16-bit weights, a dense group takes 64 bits. A compressed group takes 2 × 16 + 2 × 2 = 36 bits, 56% of dense. The indices are why storage falls only to 56%.
Top: a 4 by 8 weight slice, kept weights filled. Bottom: packed values in blue, one index per kept weight in purple.
Illustrative: the first four rows of the hero's matrix and 48 random inputs. Weights take 16 bits; an index takes the fewest bits that name a position in a group of M (2 bits for M = 4). Real hardware formats are the vendor's.
At 2:4 the slice takes 288 bits against 512, or 56%. At 1:4 only a quarter stays, the compressed matrix shrinks more, and the error climbs. 2:4 is the sweet spot.
Symptom: the model is 50% sparse, and the sparse tensor cores give no speedup. Measure: count the non-zeros in each group of four. Three zeros in one group and one in the next average 50% but break 2:4. Fix: keep the two largest weights in every group, as the code does.
pythonimport torch
def nm_mask(w, n=2, m=4):
g = w.abs().reshape(-1, m) # (rows * cols / m, m)
idx = g.topk(n, dim=1).indices # the n biggest in each group
mask = torch.zeros_like(g).scatter_(1, idx, 1.0)
return mask.reshape(w.shape) # same shape as w, exactly n of every m kept
Chapter 7
Count exactly how many MACs a channel cut saves, and see why each layer needs its own ratio
Trim every station of a kitchen line by the same share, and the busiest one becomes the bottleneck. Trim each by what it can spare instead. That is channel pruning and its question: how much can each layer lose?
Pro: a direct speedup, because the result is an ordinary network with fewer channels. Con: a smaller compression ratio. One filter of a [256, 128, 3, 3] layer holds 128 × 9 = 1,152 weights, and channel pruning removes all of them, big ones too.
How many MACs does a convolution layer do for one image? Name its output channels co and input channels ci. Name the kernel size kh by kw and the output map size H by W.
MACs equals c-o times c-i times k-h times k-w times H times W.
One output value needs c-i times k-h times k-w MACs. There are c-o times H times W output values. Multiply the two.
Layer 1 turns 3 channels into 64 on a 56 by 56 map: 64 × 3 × 9 × 3,136 = 5,419,008 MACs. Halve c-o to 32 and it falls to 2,709,504.
A cut of layer l's output channels also shrinks ci of layer l + 1. Add layer 2, from 64 to 128 channels on a 28 by 28 map:
Cut every layer by the same ratio s, and each middle layer loses on both sides. Its MACs fall to about (1 − s)2: with s = 0.3, 0.7 × 0.7 = 49% remains.
The slide gives five layers their own sparsity (0.5, 0.3, 0.7, 0.2, 0.3), next to uniform shrink at 0.3 everywhere. AMC (He et al., ECCV 2018) shows that per-layer ratios beat uniform scaling on mobile: more ImageNet accuracy at the same latency. How AMC finds them is Lecture 4. Tune five toy layers by hand:
Toy network: channels 64, 128, 256, 256, 512 on maps 56, 28, 14, 14, 7; exact MAC counts. The loss proxy is ours: 100 times the sum of sensitivity (0.4, 0.7, 0.2, 1.0, 0.7) times ratio squared. Uniform spends your MACs.
The slide's ratios keep about 32% of the MACs. Uniform needs s = 0.43 everywhere for the same MACs, and costs 56 proxy points against 36. The tuned ratios spare the sensitive layer 3.
Symptom: a 40% shrink on every layer drops accuracy far more than expected. Measure: prune each layer alone and record the accuracy. A few layers cause most of the loss. Fix: lower their ratio and raise it on tolerant layers, until you meet the MACs target.
Chapter 8
Score each weight, row or filter by how big it is, and learn where the big number hides in a channel
The less important the removed weights, the better the pruned network. Take the slide's neuron y = ReLU(10x0 − 8x1 + 0.1x2), where a ReLU turns negative numbers into zero. If one weight must go, the 0.1 goes: it barely moves y.
That is magnitude-based pruning: importance is the absolute value |W|. To score a row or filter, call the group the structural set S, each weight in it wi, and pick a power p, 1 or 2.
The L-p norm of W-S equals the sum over i in S of the size of w-i to the p, all to the power one over p.
Take the size of each weight w-i in S. Raise it to the power p and add. Take the p-th root. That is the score of S.
The slide's matrix [[3, −2], [1, −5]], half cut. Row L1 scores are 5 and 6, so row 0 goes. Row L2 scores are √13 = 3.61 and √26 = 5.10: the same. Element-wise, 1 and 2 go, leaving [[3, 0], [0, −5]].
The norms can disagree, because squaring rewards a few big weights.
Numbers are the weights. Filled cells stay, hollow cells go. Row scores sit at the right of each row.
Illustrative rows, built so L1 and L2 disagree at 50%.
At 50% by rows, L1 keeps A and B; L2 keeps B and D. Row A of four equal weights scores 16 by L1 and 8 by L2.
Give each filter a trainable scaling factor on its output channel, and prune the small ones (Liu et al., ICCV 2017). The batch normalization after most convolutions already has one. Call a channel's input zi, the batch mean μB, the batch variance σB2, the scale γ and the shift β.
z-o equals gamma times z-i minus mu-B, over the square root of sigma-B squared plus epsilon, plus beta.
Subtract mu-B from z-i, divide by the spread, multiply by gamma, add beta. With gamma near 0, z-o is about beta for every input.
Inputs 2, 4, 6 standardize to −1.22, 0, 1.22. With gamma 1.17 and beta 0.5, z-o is −0.93, 0.5, 1.93. With gamma 0.10 it is 0.38, 0.5, 0.62: nearly flat, so a constant can replace it.
Five filters with the lecture's scaling factors. Each wave is one channel's output for the same input. Drag to prune the smallest factors.
Factors from the slide. The waves are illustrative: one shared signal, scaled by each factor, resting at 0.5.
pythonimport torch
def magnitude_mask(w, sparsity):
"""1 = keep, 0 = prune. Drops the smallest |w| in this one tensor."""
k = int(sparsity * w.numel())
thresh = w.abs().flatten().kthvalue(k).values # k-th smallest size
return (w.abs() > thresh).float()
def filter_l1_mask(conv_w, sparsity): # conv_w: (c_o, c_i, kh, kw)
score = conv_w.abs().sum(dim=(1, 2, 3)) # one L1 score per filter, (c_o,)
keep = score.argsort(descending=True)[: int(len(score) * (1 - sparsity))]
mask = torch.zeros(len(score)); mask[keep] = 1
return mask.view(-1, 1, 1, 1).expand_as(conv_w)
Symptom: one threshold for the whole network leaves a layer 99% pruned, and the network collapses. Measure: print each layer's sparsity. Fix: give each layer its own ratio (Lecture 4).
Chapter 9
Derive Optimal Brain Damage in three assumptions, and see a tiny weight that is more costly to lose than a big one
One metre east crosses a plateau; one metre north drops off a cliff. A step's cost depends on how the ground bends, not on its length.
Training ends at a valley floor of the loss. Pruning weight i moves it by δwi. Call the slope of the loss along weight i the gradient gi. Call the bend of the loss along weights i and j hij, the Hessian; hii is the curvature. A Taylor series adds them up:
Delta L equals the sum of g-i delta w-i, plus half the sum of h-i-i delta w-i squared, plus half the sum over i not j of h-i-j delta w-i delta w-j, plus order delta W cubed.
For each weight, add slope g-i times the move and half of h-i-i times the move squared. Add the cross terms. The total predicts delta L.
With made-up numbers: a weight of 0.1 with g = 0 and h = 100, moved to 0. The first term is 0; the second is (1/2) × 100 × 0.12 = 0.5. The loss rises about 0.5.
Optimal Brain Damage (LeCun et al., 1989) makes three assumptions:
One term per weight is left. Zeroing weight i is a move of wi:
Importance of w-i equals the size of delta L-i, which equals one half h-i-i times w-i squared.
Square the weight w-i, multiply by its curvature h-i-i, and halve. If every h-i-i were equal, this would rank weights like magnitude does.
With made-up numbers: w1 = 0.1 with h11 = 100 scores 0.5. w2 = 3 with h22 = 0.01 scores (1/2) × 0.01 × 9 = 0.045. OBD prunes the big weight 2: 11 times less damage.
The cross is your trained network. Pruning weight 1 moves you left; weight 2, down. A narrow ellipse is a steep direction.
Illustrative loss with no cross terms, L = (1/2)(h1d12 + h2d22), d the move. Curvatures run 0.01 to 100.
On the first preset, weight 1's dot is close to the cross but on a high contour. Weight 2's dot is far away, on a low one.
The slide's warning: the Hessian is difficult to compute. For 61 million weights it has about 3.7 × 1015 entries, some 15 petabytes. OBD needs only the diagonal, 244 MB, but each entry costs a second derivative.
pythonimport torch
w_star = torch.tensor([0.1, 3.0]) # trained weights (the loss minimum)
h = torch.tensor([100.0, 0.01])
L = lambda w: 0.5 * (h * (w - w_star) ** 2).sum()
H = torch.autograd.functional.hessian(L, w_star) # (2, 2), here diag(100, 0.01)
saliency = 0.5 * H.diag() * w_star ** 2 # tensor([0.5000, 0.0450])
print(saliency.argsort()) # tensor([1, 0]): prune weight 1 first, by index
The argsort lists index 1, the weight 3.0, first: the cheaper one to prune.
Symptom: OBD ranks well at the end of training and badly in the middle. Measure: check the gradient. If it is not near zero, the first-order term matters. Fix: train to convergence first, or use a first-order score (Molchanov et al.).
Chapter 10
Choose which channels to cut by watching what they output, and fit what is left so the layer's answer barely moves
Now score neurons by what they output. Neuron pruning is coarse-grained weight pruning: a neuron is one row of W in a linear layer, and a channel in a convolution.
ReLU outputs many exact zeros. A channel that is nearly always zero adds almost nothing. The Average Percentage of Zeros (APoZ, Hu et al., 2017) counts channel c's zeros n0 over a batch of B inputs on an H by W output map.
APoZ of c equals n-zero over B times H times W.
Run a batch. Divide channel c's zero count n-zero by its number of values, B times H times W. A larger APoZ means a less important channel.
From the slide: B = 2 on a 4 by 4 map gives 32 values. Zeros 11, 12 and 14 give 0.34, 0.375 and 0.44. Channel 2 goes.
Each grid is one channel's output for the first input; hollow cells are zeros. The bar is APoZ over all inputs.
Illustrative: pre-ReLU means 0.6, 0.1, −0.5, 0.3 with spread 1, so long-run APoZ is 0.27, 0.46, 0.69, 0.38.
With 2 inputs the ranking wobbles. With 64 inputs, channel 2 wins every time.
Ask an easier question: after the cut, does the layer give nearly the same output? Call the input X (b rows), its columns for channel c Xc, their weights Wc, and the output Z = XWT. Channel c gets a switch βc; at most Nc stay on.
Arg min over W and beta of the Frobenius norm of Z minus Z-hat, squared, where Z-hat is the sum over c of beta-c X-c W-c transpose, with at most N-c non-zero betas.
Fix W and choose the non-zero beta-c, to pick channels. Then fix beta and refit W. Repeat. The weights change too.
In the device below, 3 of 6 channels stay. Picking by weight size misses Z by 27%, refitting gives 24%, and regression gives 7%.
A layer with 6 input channels and 3 outputs. Pick how many stay.
Illustrative: 80 random inputs; channel 3 copies channel 0, channel 4 mixes 1 and 2, channel 5 is weak. Regression tries every set and refits by least squares; He et al. (ICCV 2017) alternate instead.
Regression picks channels 0, 1 and 2, which can rebuild 3 and 4. A channel with small weights can be the one nothing replaces.
pythondef apoz(act): # act: (B, C, H, W), after ReLU
return (act == 0).float().mean(dim=(0, 2, 3)) # (C,) the share of zeros per channel
def regression_refit(X, Z, keep): # X: (b, c_i), Z: (b, c_o), keep: indices
Xp = X[:, keep] # (b, k)
Wp = torch.linalg.lstsq(Xp, Z).solution # (k, c_o) minimises ||Z - Xp Wp||_F
return Wp
Symptom: you prune by APoZ, and a channel that mattered disappears. Measure: compute APoZ again on another batch. If the ranking changes, the first was noise. Fix: measure on a large, varied set of inputs.
Chapter 11
Keep the numbers, the terms, the checklist and the code, and know where Part II picks up
Pruning is four choices: a granularity, a criterion, a ratio, and a finetune. Scattered zeros compress best but need special hardware. Regular patterns, like 2:4 and whole channels, give up some accuracy to run fast on common chips.
| Fact | Value | Where it came from |
|---|---|---|
| DRAM fetch against float MULT | 640 pJ against 3.7 pJ, about 173× | Horowitz table, Chapter 0 |
| Papers on pruning | about 3,000 a year by 2022 | Publication chart, Chapter 1 |
| Synapses per neuron in a human | 2,500 at birth, 15,000 at 2 to 4 years, 7,000 as an adult | Brain slide, Chapter 1 |
| AlexNet | 61 M to 6.7 M parameters (9×), MACs 3× | Han et al. 2015, Chapter 3 |
| VGG-16 | 138 M to 10.3 M (12×), MACs 5× | Chapter 3 |
| GoogleNet | 7 M to 2.0 M (3.5×), MACs 5× | Chapter 3 |
| ResNet50 | 26 M to 7.47 M (3.4×), MACs 6.3× | Chapter 3 |
| SqueezeNet | 1 M to 0.38 M (3.2×), MACs 3.5× | Chapter 3 |
| 2:4 sparsity | 50% sparse, up to 2× faster, 1.5× measured on BERT | A100 slide, Chapters 3 and 6 |
| Compressed 2:4 group, 16-bit weights | 36 bits against 64 (56%) | Our arithmetic, Chapter 6 |
| Channel cut on every layer by s | MACs about (1 − s)2 | Our derivation, Chapter 7 |
| OBD importance | (1/2) hii wi2 | LeCun et al. 1989, Chapter 9 |
| APoZ of one channel | zeros / (batch × height × width) | Hu et al. 2017, Chapter 10 |
| Term | Plain meaning |
|---|---|
| Synapse, neuron | A weight is a connection. A neuron is a unit that holds many. |
| Sparsity, L0 norm | The share of zeros. The L0 norm counts the non-zeros. |
| Granularity | The size and shape of the piece you remove. |
| Structured, unstructured | Whole groups removed, or single weights removed. |
| N:M sparsity | N weights kept in every group of M. 2:4 is the case with hardware support. |
| Criterion | The score that ranks what to remove. |
| Pruning ratio | The share removed, for the network or one layer. |
| Finetune | Train the survivors while the mask holds the zeros. |
pythonimport torch
def mask_fine(w, sparsity): # any shape; 0 < sparsity < 1
k = max(1, int(sparsity * w.numel()))
t = w.abs().flatten().kthvalue(k).values # k-th smallest size
return (w.abs() > t).float()
def mask_nm(w, n=2, m=4): # w: (rows, cols), cols divisible by m
g = w.abs().reshape(-1, m)
idx = g.topk(n, dim=1).indices # n biggest in each group
return torch.zeros_like(g).scatter_(1, idx, 1.0).reshape(w.shape)
def mask_filter(w, sparsity, p=1): # w: (c_o, c_i, kh, kw)
score = w.abs().pow(p).sum(dim=(1, 2, 3)) # one L_p score per filter, (c_o,)
keep = score.argsort(descending=True)[: round(len(score) * (1 - sparsity))]
m = torch.zeros(len(score)); m[keep] = 1
return m.view(-1, 1, 1, 1).expand_as(w)
def apoz(act): # act: (B, C, H, W), after ReLU
return (act == 0).float().mean(dim=(0, 2, 3)) # (C,) share of zeros per channel
def obd_saliency(w, h_diag): # h_diag: curvature of each weight
return 0.5 * h_diag * w ** 2 # smallest values are pruned first
# Then: apply the mask, finetune with p.mul_(mask) after every step (Chapter 2),
# and repeat with a slightly higher sparsity.
Check them on the lesson's examples. On [[3, −2], [1, −5]] at 50%, mask_fine keeps 3 and −5. On the group (0.9, −0.1, 0.4, −0.7), mask_nm keeps 0.9 and −0.7. On weights (0.1, 3.0) with curvatures (100, 0.01), obd_saliency gives (0.5, 0.045).
This lecture answers three of the five questions: what pruning is, in what pattern, and which weights. Lecture 4 covers the ratio for each layer, how to finetune the pruned network, automated ways to find the ratios, and system support for each granularity. Quantization comes next, in Lecture 5.
This lesson follows Lecture 3 of MIT 6.5940, TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Find the lecture and its slides on the course site. Every idea is re-taught here in our own words and devices. We label toy numbers illustrative. Papers the lecture cites:
Now press Teach and explain, from memory, why a 90% sparse model may not run any faster, and what pattern fixes that. Then go back to the layer at the top and try all three patterns once more.