Prune each layer by its own amount, found by search, and MobileNet does half the work for 0.1 points of accuracy. Then store the zeros so hardware skips them.
Learn how to choose how much to prune in every layer, how to recover accuracy afterwards, and why the hardware decides whether a sparse model is actually fast.
Pick a method, then drag the slider to remove more weights. Watch which layers each method spares, and what it costs in accuracy. Then we build, piece by piece, sensitivity curves, a learning agent, a greedy loop, a zero-skipping chip, the 2:4 pattern and sparse convolution.
You need the idea of pruning (set small weights to zero, then retrain) from the last lecture, and a little Python. We build the rest from zero.
Based on Lecture 4 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides (PDF) are linked on the course page. Every idea is re-taught here in our own words and devices; it follows Lecture 3, Pruning and Sparsity I and leads into Lecture 5, Quantization I.
Illustrative: a made-up six layer network. The sensitivity curves, layer sizes and accuracies are invented for this lesson so every number can be checked on the page. The real result is in the AMC row of the MobileNet table in chapter 2: 569M to 285M multiply-adds, 70.6% to 70.5% top-1 accuracy (He et al., ECCV 2018, as shown in the lecture).
Chapter 0
How much to cut from each layer, and whether the cut model runs any faster
You must cut 5 kg from a 20 kg backpack. Taking a quarter off every item sounds fair, and it is a poor plan. The map cannot lose anything. The spare clothes can lose a lot.
A network is the same. Lecture 3 showed which weights to remove. This lecture asks how much to remove from each layer, how to win the accuracy back, and why a model full of zeros is not automatically fast.
Pruning sets weights to zero so the network stores and computes less. Every pruning method makes four decisions.
Lecture 3 answered the first two. This lecture answers the last two, then adds hardware support. The criterion stays magnitude: a weight with a larger absolute value matters more. Of the weights 3, −2, 1 and −5, a 50% cut keeps 3 and −5.
Call the weights after pruning WP. Call the training loss on an input x L: how wrong the network is. Call the number of nonzero weights we agree to keep N.
Arg min over W-P of L of x and W-P, subject to the zero-norm of W-P being at most N.
Look at every pruned version W-P that keeps at most N weights nonzero. Pick the one with the smallest loss L.
The toy matrix below has 36 weights. A 50% cut sets N = 18. The search wants the 18 weights that keep L lowest. Magnitude pruning guesses they are the 18 largest.
Chapters 1 to 3 split N across the layers. Chapter 4 trains WP. Chapters 5 to 9 make the zeros pay off on a chip.
Fine-grained pruning lets any single weight go, so the zeros fall anywhere. Channel-level pruning removes whole channels. Pattern, vector and kernel pruning sit between them; the lecture jokes that they look like Tetris. Irregular zeros keep more accuracy. Regular zeros are easier for hardware.
Pick fine-grained or channel-level, then a ratio. Left: the pruned matrix. Right: the matrix a dense engine multiplies after the cut.
Toy matrix: 36 made-up weights, one row per output channel. "Magnitude lost" is the removed share of the summed absolute values: a rough stand-in for accuracy loss, not a measurement of one.
Fine-grained wins on magnitude. But its right grid stays six by six with zeros inside, and a dense engine multiplies every cell. Channel pruning gives up some magnitude and leaves a smaller matrix that any engine runs faster.
Chapter 1
Prune one layer at a time, plot the damage, and read every ratio off one shared threshold
The lecture's plot of ImageNet accuracy against latency settles one thing first. Channel pruning with per-layer ratios (AMC, Chapter 2) beats uniform shrinking at every latency. So how do we find each layer's ratio?
Some layers are sensitive: the first layer reads raw pixels with few filters, so each filter carries a lot. Others are redundant: they hold many overlapping weights. Sensitivity analysis tells them apart by testing.
The lecture runs it on VGG-11 trained on CIFAR-10.
Step 4 is one line of math. Call the accuracy lost when only layer i is pruned by ratio r ΔAccir. Call the threshold T, and the ratio that layer i receives ri.
r-i equals the largest r such that delta-Acc i at r is at most T.
Walk along layer i's curve from r = 0. Stop at the last ratio whose drop is still at most T. That ratio is r-i. Use the same T for every layer.
In the toy below, layer L0 loses 70 × r4 points. With T = 8, r4 = 8 / 70 = 0.114, so r0 = 0.58. Layer L3 loses 16 × r4, so r3 = 0.51/4 = 0.84. The robust layer gets the deeper cut.
Top: accuracy when one layer alone is pruned. The dashed line is the threshold. Bottom: the ratio each layer gets, with its share of all weights.
Illustrative: six invented layers from a base of 91%. Layer i alone loses SENi × r4 points, with SEN = 70, 45, 28, 16, 9, 5. Layer sizes are 2, 8, 14, 20, 28 and 28% of all weights. Pruned together, the layers multiply their survival factors. The lecture's real curves are VGG-11 on CIFAR-10.
At T = 8, layers L4 and L5 reach the 95% cap. Weight each ratio by its layer's share of all weights, and 86.6% of the weights go. At T = 3, about 72% go.
Each layer, tested alone, lost at most 8 points. Prune all six at once and the toy falls from 91% to 55.3%. The test never prunes two layers together, so it cannot see errors compound. The lecture says so: sensitivity analysis ignores the interaction between layers, so its answer may not be optimal.
Measure the whole pruned network, never the table alone. The fix is a method that scores whole networks: Chapters 2 and 3.
In: a trained model and a validation set. Out: a table of drops, shape L × 10, then one ratio per layer.
pythonimport copy RATIOS = [i / 10 for i in range(10)] # 0.0, 0.1, ..., 0.9 def sensitivity(model, layer_names, evaluate, prune_layer): base = evaluate(model) # accuracy of the unpruned model drops = {} for name in layer_names: drops[name] = [] for r in RATIOS: m = copy.deepcopy(model) # leave every other layer untouched prune_layer(m, name, r) # magnitude pruning of ONE layer drops[name].append(base - evaluate(m)) return drops # L curves of 10 points def ratios_for(drops, T): # the largest ratio under threshold T return {n: max(r for r, d in zip(RATIOS, c) if d <= T) for n, c in drops.items()}
Chapter 2
Turn pruning into a game that a learning agent plays layer by layer, scored by accuracy under a budget
Hand-tuning every layer's ratio for thousands of customers' phones is slow guesswork. The lecture asks for a push-the-button tool that a non-expert with a hardware target can run.
AMC, AutoML for Model Compression (He et al., ECCV 2018), is that tool. AutoML means a program, not a person, tunes the design choices. AMC casts pruning as reinforcement learning: an agent learns from scores, not from answers.
| Word | Plain meaning | In AMC |
|---|---|---|
| Agent | The learner | A DDPG agent (Deep Deterministic Policy Gradient). It outputs a continuous number, so it can choose 0.43, not only 25%, 50% or 75%. |
| Environment | The world it acts on | The network under channel pruning: a ratio of 0.5 removes half of a layer's channels and leaves a smaller dense layer. |
| State | What the agent sees | Facts about layer t, st = [N, C, H, W, i, …]: its index, channel counts, kernel size, FLOPs. |
| Action | What it does | One pruning ratio a, from 0 up to but not including 1. |
| Reward | The score | One number, after the last layer is pruned. |
| Policy | The rule it learns | State in, ratio out. |
The score needs two names. Call the agent's reward R. Call the pruned network's top-1 error, in percent, Error. The constraint is a budget on FLOPs or on latency.
R equals minus Error if the constraint holds, and minus infinity if it does not.
Prune every layer with the agent's ratios. Check the budget. If it is broken, R is minus infinity. If not, R is minus the Error, so a lower Error scores higher.
From the AMC row of the table below: top-1 accuracy 70.5% means Error = 29.5, so R = −29.5. A proposal that keeps 60% of the FLOPs under a 50% budget scores minus infinity, no matter how accurate it is.
Pick a FLOP budget and press Run. Top: the best ratios found so far. Bottom: the reward of every episode. Red ticks are proposals that broke the budget.
Illustrative: the Chapter 1 toy, with compute shares 20, 24, 20, 16, 12 and 8% of 500 toy megaflops. Error is 100 minus toy accuracy. Eight random episodes, then the agent perturbs its best proposal with shrinking noise. This stand-in is not DDPG, which learns a neural policy.
Press Run at 50%, then compare the read-out with uniform pruning at the same budget.
On ResNet-50, a human expert kept 29% of the weights and AMC kept 20%. AMC learned to prune 1×1 convolutions less, because they have less redundancy, and 3×3 convolutions more. No one told the agent this. The score taught it.
The MobileNet results, measured with TF-Lite on a Samsung Galaxy S7 Edge, single core, batch size 1:
| Model | MACs | Top-1 | Latency | Speedup | Memory |
|---|---|---|---|---|---|
| 1.0 MobileNet | 569M | 70.6% | 119.0 ms | 1x | 20.1 MB |
| AMC (50% FLOPs) | 285M | 70.5% | 64.4 ms | 1.8x | 14.3 MB |
| AMC (50% time) | 272M | 70.2% | 59.7 ms | 2.0x | 13.2 MB |
| 0.75 MobileNet | 325M | 68.4% | 69.5 ms | 1.7x | 14.8 MB |
Latency falls from 119.0 to 64.4 ms: 119.0 / 64.4 = 1.85, under 2x because memory traffic stays. Uniform 0.75 width runs at 1.7x and loses 2.2 points. AMC runs at 1.8x and loses 0.1.
Symptom, for example: the agent hits 50% of the FLOPs, but the phone runs only 1.3x faster. Measure by timing the model on the phone, because FLOPs ignore memory and fit. Fix: put latency in the loop with a lookup table. The "50% time" row does this and reaches 2.0x for 0.4 points.
pythonimport math def amc_episode(agent, env, flop_budget): s = env.reset() # state of layer 0: a vector like [N, C, H, W, i, ...] transitions = [] for t in range(env.num_layers): a = agent.act(s) + agent.noise() # one continuous ratio in [0, 1) a = min(max(a, 0.0), 0.99) s_next = env.channel_prune(t, a) # prune layer t, return layer t+1's state transitions.append((s, a, s_next)) s = s_next err, flops = env.evaluate() # error of the finished network and its FLOPs reward = -err * math.log(flops) if flops <= flop_budget else -math.inf agent.update(transitions, reward) # DDPG: a critic scores actions, the actor follows the critic return reward
Chapter 3
Shave a fixed number of milliseconds per round, let a short fine-tune pick the layer, and keep every model on the way
A sculptor takes off a little stone, steps back and looks, then cuts again. NetAdapt (Yang et al., ECCV 2018) prunes the same way, rule-based and step by step, toward a global limit such as latency or energy. The lecture uses latency.
Step 2 must not run the phone for every candidate. So NetAdapt times each layer on the target device once, at many channel counts, and stores the times in a latency lookup table (LUT).
Call the latency to remove in one round ΔR, in milliseconds. Call layer k's cost per channel, read from the table, ck. Call the channels to remove from layer k nk.
n-k equals delta-R divided by c-k, rounded up.
Read layer k's cost per channel c-k from the table. Divide the round's cut delta-R by it. Round up. That many channels leave layer k.
With the toy table below and delta-R = 4 ms: layer A costs 0.20 ms per channel, so n-A = 4 / 0.20 = 20 of its 32. Layer B: 4 / 0.15 = 26.7, so 27. Layer D: 80 of 256, a much smaller bite.
Blue bars are channels kept, and warm is this round's cut. The number on top is the accuracy after a short fine-tune; green marks the winner.
Illustrative: five invented layers of 32, 64, 128, 256 and 256 channels, costing 0.20, 0.15, 0.10, 0.05 and 0.04 ms per channel. Accuracy after the short fine-tune is a made-up formula that punishes cuts to early layers more.
After the short fine-tune, the five candidates score 86.31, 89.72, 90.61, 90.77 and 90.76%. Layer D wins by a hair, and latency drops from 51.8 to 47.8 ms. Four rounds reach 35.8 ms, with winners D, E, C, D.
Each round leaves a complete network, so the number of models equals the number of iterations. That series serves devices of different speeds.
Each round changes the network a little, and the short fine-tune measures the true effect, interactions included. That closes the blind spot of Chapter 1.
| AMC | NetAdapt | |
|---|---|---|
| Search | A learned policy proposes all ratios together | One greedy choice per round, no look-ahead |
| Main cost | Many episodes to train the agent | Many short fine-tunes |
| Resource | FLOPs, or latency if you add a table | Measured latency from the start |
Symptom: the loop stops at a predicted 36 ms, yet the phone runs the model in 44 ms. Measure by timing the final model and comparing it with the table's sum. Fix: build the table on the same device, batch size, thread count and number type that you ship.
In: a trained network, the table, ΔR and a target. Out: one network per round, and a final long fine-tuned model.
pythondef netadapt(model, lut, delta_r, target_ms, short_ft, long_ft, evaluate): series = [] while lut.latency(model) > target_ms: goal = lut.latency(model) - delta_r # this round must reach this latency best, best_acc = None, -1.0 for layer in model.layers: m = model.copy() n_out = lut.channels_for(layer, goal, m) # a table read, not a device run if n_out is None: continue # this layer cannot save delta_r m.prune_channels(layer, n_out) short_ft(m, steps=10_000) # brief recovery, then a real accuracy acc = evaluate(m) if acc > best_acc: best, best_acc = m, acc model = best # commit the winner only series.append(model.copy()) return series, long_ft(model) # one long fine-tune at the end
Chapter 4
Cut gently, retrain after every cut, and teach the weights to shrink before you remove them
Pruning lowers accuracy, most at high ratios. Fine-tuning retrains the survivors with the zeros held fixed. It wins accuracy back and pushes the usable ratio higher. Its learning rate is usually 1/100 or 1/10 of the original: the survivors are already good.
One prune plus one fine-tune is one iteration. Iterative pruning raises the target each iteration: 30%, then 50%, then 70%. On AlexNet it lifts the ratio from 5x to 9x over one aggressive cut; 9x means one ninth of the weights remain.
Pick a sparsity and press Prune. Panels: dense, one-shot, one-shot plus fine-tune, and iterative with a fine-tune each round.
Real, not a mock-up: a 2-32-32-1 tanh network, trained on 240 spiral points and scored on 400 others. Pruning cuts the smallest weights across layers. Fine-tune: 300 epochs. Iterative: 50, 70, 85, 95, 97%, 100 epochs each. 50% is chance.
At 80% or 90%, fine-tuning alone is enough. The rounds matter only near the edge: try 97%.
Regularization adds a penalty for large weights to the loss, so training prefers small weights, which are cheap to cut. Call the old loss L(x; W), the penalty strength λ (lambda), and the new loss L′.
L-prime equals L of x and W, plus lambda times the absolute value of W for L1, or plus lambda times the squared norm of W for L2.
Add up the weights' sizes: absolute values for L1, squares for L2. Multiply by lambda. Add that to the old loss L.
With made-up numbers (w = 0.05, step size 0.1, lambda 0.1, loss ignored): L1 subtracts 0.1 × 0.1 = 0.01 a step and hits 0 after 5 steps. L2 multiplies w by 1 − 2 × 0.1 × 0.1 = 0.98 a step and leaves 0.0452.
Magnitude-based fine-grained pruning uses L2 on the weights. Network Slimming (Liu et al., ICCV 2017) puts a smooth L1 penalty on channel scaling factors, one per channel; a zero factor deletes its channel.
Ten weights matter little and six matter a lot. Pick a penalty, set λ and press Train. Ticks mark where the loss alone would put each weight.
Toy: each weight has a loss k(w − t)2/2, with k = 0.06 for the ten and k = 1 for the six. Step size 0.5. L1 uses the soft-threshold update, which lands on exact zeros. Zero means below 0.01.
With L1 at λ = 0.04, the ten minor weights reach zero and the six big ones barely move. With L2, all sixteen shrink; none reaches zero.
Symptom: one 97% cut stays at chance even after fine-tuning. Measure it with the first device: 50.0% for one-shot plus fine-tune, 87.0% for iterative. Fix: cut in rounds, and fine-tune gently after each.
pythondef iterative_prune(model, data, schedule, ft_epochs, base_lr): masks = {n: torch.ones_like(p) for n, p in model.named_parameters() if p.dim() > 1} opt = torch.optim.SGD(model.parameters(), lr=base_lr * 0.01) # fine-tune at 1/100 of the original rate for target in schedule: # e.g. [0.3, 0.5, 0.7, 0.9] all_w = torch.cat([p.abs().flatten() for n, p in model.named_parameters() if n in masks]) thr = torch.kthvalue(all_w, int(target * all_w.numel())).values # magnitude criterion for n, p in model.named_parameters(): if n in masks: masks[n] = (p.abs() > thr).float() # 1 = keep, 0 = cut for _ in range(ft_epochs): for x, y in data: loss = F.cross_entropy(model(x), y) opt.zero_grad(); loss.backward(); opt.step() with torch.no_grad(): # keep the zeros at zero after every update for n, p in model.named_parameters(): if n in masks: p.mul_(masks[n]) return model, masks
Chapter 5
Count the work a zero-skipping engine saves, and meet the three kinds of lazy that EIE builds into silicon
You prune a layer to 90% zeros and time it on a GPU. It runs at the old speed. The machine does not know the zeros are zeros.
The lecture now turns to system support for sparsity, in three systems:
The lecture's paradigm puts model compression between training and deployment, then runs the compressed model on an accelerator built for it. Compression alone does not give speed; the chip does. That chip is EIE, the Efficient Inference Engine (Han et al., ISCA 2016), the first accelerator for a sparse, compressed network.
| Saving | Rule | Kind of zeros | Slide's figure |
|---|---|---|---|
| Sparse weights | 0 × A = 0 | Static: fixed after pruning, known before any input | 90% sparse: 10x less computation, 5x less memory |
| Sparse activations | W × 0 = 0 | Dynamic: ReLU zeroes negative outputs, and which ones changes with every input | 70% sparse: 3x less computation |
| Weight sharing | 2.09 and 1.92 both become 2 | A 16-entry codebook: each weight becomes a 4-bit index, not a 32-bit float | 8x less memory |
An activation is a layer's output, the next layer's input. A multiply-add, or MAC, is useful only if both its weight and its activation are nonzero. Call the fraction of nonzero weights w and the fraction of nonzero activations a.
Useful MACs is about w times a times dense MACs.
Take the dense count, rows times columns. Multiply by w. Multiply by a. The result is the work left for an engine that skips both kinds of zeros.
AlexNet layer 7, from the lecture's benchmark: 4096 × 4096 = 16.8 million dense MACs, w = 0.09, a = 0.35. Useful MACs = 0.09 × 0.35 × 16.8 M = 0.53 million, about 32x fewer. The lecture lists 33x.
Memory counts the same way. Store each nonzero as a value plus an index: at 10% density that is 2 numbers per 10 weights, 5x fewer. That count is ours, and it matches the slide.
Set how many weights and activations are nonzero. Bars show the multiply-adds each engine must do. The yellow part is work done; the rest is skipped.
The presets use the weight and activation densities in the lecture's EIE benchmark table (AlexNet layer 7: 9% and 35%; VGG layer 6: 4% and 18%). The count assumes the two densities are independent, so the real saving can differ; the table lists 33x and 100x. The storage figure counts one value and one index per nonzero weight.
Push the weights to 100% and the saving vanishes. Skipping needs zeros.
A GPU runs regular dense blocks, and a zero in a block still takes a lane. To skip it, the hardware must know where the zeros are and reshuffle the work. EIE spends its design on that bookkeeping.
The code counts the work that is not wasted. In: a weight matrix and an activation vector. Out: two counts.
pythonimport numpy as np def count_macs(W, a): # W: (rows, cols) weights after pruning; a: (cols,) activations after ReLU dense = W.size # a dense engine does rows * cols multiply-adds useful = np.count_nonzero((W != 0) & (a != 0)[None, :]) # both inputs nonzero return dense, useful rng = np.random.default_rng(0) W = rng.normal(size=(4096, 4096)) * (rng.random((4096, 4096)) < 0.09) # 9% nonzero a = np.maximum(rng.normal(size=4096) - 0.4, 0) # ReLU leaves about a third nonzero print(count_macs(W, a))
Chapter 6
Follow one tiny matrix-vector product through four processing elements, from the compressed layout to the last sum
A post office gets 32 letters, and 21 are blank. Nobody opens the blanks. The sorting room keeps a list of the 11 real letters, and each clerk gets only the letters for his own shelves.
That is EIE's plan for one fully connected layer. The layer multiplies a weight matrix W by an input vector a, then applies ReLU to get the output b. In the lecture's example, W has 8 rows and 4 columns, and four processing elements (PEs) share the work. A PE is a small compute unit with its own memory and multiplier.
The rows are dealt out like cards: PE0 gets rows 0 and 4, PE1 gets rows 1 and 5, and so on. Each PE stores only the nonzeros in its rows and sums only its own outputs, so no PE waits on another.
The input arrives one entry at a time, and a nonzero aj meets exactly one column of W. So each PE stores its weights column by column, in three short lists. For PE0:
To find a weight's row, start at −1 and add each relative index plus 1. In column 2 of PE0, −1 + 1 + 1 = 1: the PE's second row, which is row 4.
Top: the four activations. Each box below is one PE with its compressed lists. Yellow entries are being multiplied now, blue were done, warm were skipped.
The nonzero pattern is the 8 by 4 example in the lecture, with 11 nonzero weights out of 32; the weight values and activation values are made up so the arithmetic can be checked. Entries are named (row, column). A switched-off activation is zero. A dense engine would give each PE 2 rows times 4 columns, or 8 multiply-adds.
With the default a1 = 2 and a3 = 3, step to the end. The output is b = (1, 0, 9, 0, 6, 0, 6, −4), and after ReLU (1, 0, 9, 0, 6, 0, 6, 0).
PE0 did 3 multiplies, PE1 0, PE2 3 and PE3 1: 7 in all, against 32 dense. But the layer ends when the busiest PE ends, after 3 cycles. In 3 cycles four PEs could do 12 multiplies. They did 7, so 58% of the PE time was used.
That gap is load imbalance. Symptom: a speedup below the skipped-work count. Measure the busiest PE's count against the average. Fix: a queue in front of each PE (Chapter 7).
pythondef encode_pe(W, pe, n_pe=4): rows = list(range(pe, W.shape[0], n_pe)) # rows dealt out like cards: pe, pe+4, ... vals, rel, ptr = [], [], [0] for j in range(W.shape[1]): # column by column prev = -1 for l, r in enumerate(rows): if W[r, j] != 0: vals.append(W[r, j]); rel.append(l - prev - 1); prev = l ptr.append(len(vals)) # where the next column starts return vals, rel, ptr # PE0 of the example: [..5 weights..], [0,0,1,0,0], [0,1,2,3,5] def pe_matvec(vals, rel, ptr, a, n_local): acc = [0] * n_local # one accumulator per owned row for j, aj in enumerate(a): if aj == 0: continue # 0 * A = 0: no PE does anything for this column l = -1 for k in range(ptr[j], ptr[j + 1]): # only the stored nonzeros of column j l += rel[k] + 1 # relative index gives the local row acc[l] += vals[k] * aj return acc # then ReLU: max(acc, 0)
Chapter 7
Follow one activation through the chip, keep the PEs fed with a queue, then read the benchmark and the retrospective
Chapter 6 showed what a PE does. The lecture's microarchitecture slide shows how, as a pipeline of six stations.
The pieces that exist only for sparsity are the queue and detector (activation zeros), the sparse access and address accumulation (weight zeros), and the decoder (sharing). A dense chip has none of them.
Weight sharing in numbers: 1 million weights as 32-bit floats take 4 MB. As 4-bit codes into a 16-entry table, they take 0.5 MB plus 64 bytes. That is 8x less memory.
The lecture's load-balance fix is an activation queue in front of each PE. A PE that finishes early takes the next queued activation and runs ahead.
Pick a mode and a weight density. Top: when each PE works (yellow) and waits (empty). Bottom: total cycles for each way of running the same layer.
A simplified simulation, not EIE's real timing: 16 rows split over 4 PEs (4 rows each), 24 columns, random nonzeros with the density you choose, and one activation broadcast per cycle at most. A PE does one multiply-add per cycle. The dense engine count is 24 columns times 4 rows per PE. Ideal means perfect balance: total multiplies divided by 4.
At 20% density the barrier needs 23 cycles for 44 multiplies, where perfect balance needs 11. A queue of 4 brings it to 15, and a dense engine needs 96. At 10%, the queue stops helping: the chip waits on the broadcast of 14 nonzero activations, one per cycle.
The lecture benchmarks nine layers from three networks. The last column is ours: 1 / (weight density × activation density).
| Layer | Size | Weights nonzero | Activations nonzero | Listed FLOP reduction | Our product estimate |
|---|---|---|---|---|---|
| AlexNet layer 6 | 4096 × 9216 | 9% | 35% | 33x | 32x |
| AlexNet layer 7 | 4096 × 4096 | 9% | 35% | 33x | 32x |
| AlexNet layer 8 | 1000 × 4096 | 25% | 38% | 10x | 11x |
| VGG layer 6 | 4096 × 25088 | 4% | 18% | 100x | 139x |
| VGG layer 7 | 4096 × 4096 | 4% | 37% | 50x | 68x |
| VGG layer 8 | 1000 × 4096 | 23% | 41% | 10x | 11x |
| NeuralTalk We | 600 × 4096 | 10% | 100% | 10x | 10x |
| NeuralTalk Wd | 8791 × 600 | 11% | 100% | 10x | 9x |
| NeuralTalk LSTM | 2400 × 1201 | 10% | 100% | 10x | 10x |
The estimate matches when the product is not extreme. For VGG it overshoots; our guess is that the two kinds of zeros are not fully independent. Against an Intel Core i7 5930k, an NVIDIA TitanX, a Jetson TK1 mobile GPU, an FPGA design and other chips, EIE leads in layers per second and in layers per joule. Its paper ranks fifth among the most cited in 50 years of ISCA, with 2,690 citations.
| Side | Point |
|---|---|
| Pro | Special hardware makes sparse operations pay for matrices up to 50% dense. |
| Pro | It skips zero weights and zero activations, so it saves energy and cycles. |
| Pro | It supports fine-grained sparsity, so pruning can go further. |
| Pro | 4-bit weights decoded to 16-bit arithmetic. That W4A16 recipe is back in LLMs: GPTQ, AWQ, llama.cpp, MLC LLM. |
| Con | It does not map easily onto arrays of vector processors. The fix: structured sparsity such as N:M (Chapter 8). |
| Con | Control flow and storage cost overhead. The fix: coarser-grained sparsity. |
| Con | It supports only fully connected layers, which LLMs now revive. |
| Con | Everything fits in on-chip SRAM: practical for TinyML, not for an LLM. |
Symptom: a layer at 60% weight density runs no faster on a zero-skipping chip. Measure w × a: near 0.5, at most 2x of the work can be skipped, and every skip costs pointer reads and decoding. Fix: prune further, or use a regular pattern that needs no indices (Chapter 8).
pythonimport numpy as np def share_weights(w, k=16, iters=10): # w: (n,) float weights -> 4-bit codes (n,) and a 16-entry codebook cb = np.quantile(w, np.linspace(0, 1, k)) # start the 16 centroids spread over the weights for _ in range(iters): idx = np.abs(w[:, None] - cb[None, :]).argmin(1) # nearest centroid for every weight for c in range(k): if (idx == c).any(): cb[c] = w[idx == c].mean() return idx.astype(np.uint8), cb # store idx (4 bits each) + cb (16 numbers) def decode(idx, cb): return cb[idx] # what EIE's weight decoder does: 4-bit code -> 16-bit weight
Chapter 8
Keep exactly two weights in every group of four, store them compactly, and let the tensor core pick the matching inputs
EIE allows zeros anywhere, so it needs pointers and a custom chip. NVIDIA's Ampere GPUs restrict where zeros may be. In M:N sparsity, every group of N consecutive weights has exactly M nonzeros; the A100 runs 2:4 sparsity.
How big is the compressed row? Call the number of weights in a row C and the bits per stored value b. Call the compressed size, as a fraction of the dense row, S.
S equals C over 2 times b plus 2, divided by C times b, which equals b plus 2 over 2 b.
Keep half the values. Give each one 2 more bits for its slot. Divide by the dense size. C cancels, so S depends only on b.
With FP16, S = (16 + 2) / 32 = 0.5625: a row of 16 takes 8 × 16 + 8 × 2 = 144 bits, not 256. With INT8, S = 10 / 16 = 0.625. This arithmetic is ours.
A GEMM is a general matrix multiply, the core of every layer, and a tensor core runs it fast. The sparse tensor core stores matrix A compressed and B dense. Its 2-bit indices mask B: of K entries, it picks the K/2 that meet A's values. Only 2 of every 4 multiplies run, so peak math doubles.
Top: the pruned rows, groups of four marked. Middle: the stored values and indices. Bottom: the 16 inputs, with the ones row 1 multiplies lit.
Illustrative: random weights, three rows of 16, new on each press. "Magnitude kept" is the kept share of the summed absolute values. The selector sizes are our reasoning: a 2:4 value comes from 1 of 4 slots, a free one from 1 of 16.
Free zeros always keep at least as much magnitude. 2:4 loses a few percent and buys regular groups and 2-bit indices. Press New weights until a group holds three big weights.
On an A100, sparse INT8 GEMMs (cuSPARSELt) near 2x over dense ones (cuBLAS) as K grows from 1,280 to 20,480 at M = N = 10,240. Larger GEMMs have higher arithmetic intensity.
The accuracy recipe: train dense, prune to 2:4, then repeat the original training schedule, same hyper-parameters, from the pruned weights. ImageNet top-1:
| Network | Dense FP16 | Sparse FP16 | Sparse INT8 |
|---|---|---|---|
| ResNet-34 | 73.7 | 73.9 | 73.7 |
| ResNet-50 | 76.1 | 76.2 | 76.2 |
| ResNet-101 | 77.7 | 78.0 | 77.9 |
| DenseNet-121 | 75.5 | 75.3 | 75.3 |
| VGG-16 | 74.0 | 74.1 | 74.1 |
| ResNeXt-101-32x16 (WSL) | 84.2 | 84.0 | 84.2 |
ResNet-50 moves from 76.1 to 76.2; DenseNet-121 loses 0.2. The slide's verdict: a large GEMM speedup and no accuracy drop for these models.
Symptom: accuracy falls after you impose 2:4. Measure, per group, the magnitude dropped against the magnitude kept: (0.9, 0.8, 0.7, 0.1) must lose 0.7. Fix: retrain after pruning, so the weights move into two slots of every four.
pythonimport numpy as np def prune_2_4(W): # W: (rows, cols) with cols divisible by 4 -> values (rows, cols/2), 2-bit indices (rows, cols/2) R, C = W.shape G = W.reshape(R, C // 4, 4) # groups of four keep = np.argsort(-np.abs(G), axis=2)[:, :, :2] # the two largest by magnitude keep = np.sort(keep, axis=2) # keep slot order inside the group vals = np.take_along_axis(G, keep, axis=2).reshape(R, C // 2) idx = keep.reshape(R, C // 2).astype(np.uint8) # each entry is 0..3, so 2 bits return vals, idx def sparse_matvec(vals, idx, x): R, half = vals.shape base = (np.arange(half) // 2) * 4 # which group each stored value came from picked = x[base + idx] # the mask: pick the matching inputs, shape (rows, cols/2) return (vals * picked).sum(axis=1) # half the multiplies of a dense matvec
Chapter 9
Turn a convolution over empty 3D space into a short list of small matrix multiplies
A self-driving car's laser returns a point cloud: a few thousand 3D points. Cut the space into tiny cubes and about 0.01% hold a point. TorchSparse (a library) and PointAcc (a chip) exploit this sparsity of the world itself.
An ordinary convolution turns every output next to a point nonzero, so a thin ring swells into a band; the lecture calls this dilation. Submanifold sparse convolution (Graham, BMVC 2015) computes outputs only where the input was nonzero.
The lecture's central idea: a sparse convolution is a set of small dense matrix multiplies. A map (In, Out, Wgt) links input point In, through kernel weight Wgt, to output point Out. Call In's feature row fIn, Out's row fOut, and the weight's matrix WWgt.
f-Out becomes f-Out plus f-In times W-Wgt, once for every map In, Out, Wgt.
For each map in the list, multiply f-In by W-Wgt and add the product into f-Out.
Point P0 has 2 maps in the lecture's example. With made-up C-in = 4 and C-out = 8, each map costs 32 multiply-adds: 64 in all. A dense 3 by 3 convolution runs all 9 offsets: 288.
Pick an offset. Each input shifts by the opposite offset (purple). Where it lands on a blue point, there is a map.
The five points are the lecture's PointAcc figure. Stride 1, so outputs sit at the input positions.
All nine offsets give 11 maps, against 45 dense products.
This is weight-stationary code. The centre weight maps every point; corner weights map few. With 27 weights in a 3D kernel, many small multiplies leave the GPU idle.
TorchSparse (Tang et al., MLSys 2022) reorders gather and scatter for locality, then chooses how to run the multiplies:
Bars are the 27 map sizes, largest first; warm is padding.
Illustrative: sizes follow 80,000 × 0.78k, a big centre with a long tail. Toy latency = 300 per launch + padded work / 60.
One group pads everything to almost 6 times the real work; 27 groups launch 27 times. The best count differs between SemanticKITTI and nuScenes, so TorchSparse searches it. On nuScenes, fixed grouping posts the best TFLOP/s but loses to adaptive grouping, because it wastes work.
A chip cannot afford a big hash table. PointAcc (Lin et al., MICRO 2021) finds maps with a merge sort: sort the shifted inputs and the outputs into one list, and equal neighbours are maps. For offset (−1, −1) this finds (P0, Q1) and (P3, Q4).
Symptom: a sparse convolution runs slower than dense on a GPU, despite 10 times fewer multiplies. Measure launches and time per launch. Fix: group the maps, accepting some padding.
pythonimport numpy as np def build_maps(coords_in, coords_out, offsets): table = {tuple(c): j for j, c in enumerate(coords_out)} # output coordinate -> row index maps = {} for k, (a, b) in enumerate(offsets): pairs = [(i, table[(x - a, y - b)]) for i, (x, y) in enumerate(coords_in) if (x - a, y - b) in table] maps[k] = (np.array([p[0] for p in pairs], dtype=int), np.array([p[1] for p in pairs], dtype=int)) return maps # per weight: which inputs feed which outputs def sparse_conv(feats, maps, weights, n_out): # feats (N_in, C_in); weights[k] (C_in, C_out) out = np.zeros((n_out, weights[0].shape[1])) for k, (i, o) in maps.items(): if len(i) == 0: continue g = feats[i] # gather: (n_k, C_in) p = g @ weights[k] # matmul: (n_k, C_out) np.add.at(out, o, p) # scatter-accumulate into the output rows return out
Chapter 10
Keep one page of numbers, one checklist, and the whole recipe as code, then follow the links onward
The lecture kept two promises: automated ways to find pruning ratios (sensitivity analysis, AMC, NetAdapt), and hardware support for each granularity (EIE, the A100's 2:4 pattern, TorchSparse and PointAcc). The next lecture covers number formats and quantization.
One trade runs through it all. Free zeros keep more accuracy and need special hardware. Regular zeros give up a little accuracy and run on ordinary hardware.
Pick the machine you will ship on. The device shows where its best-fit pattern sits on the ladder from free zeros to regular ones.
The ladder runs from irregular zeros (left) to regular zeros (right). The lit step is the pattern this machine can turn into real speed.
The pairings follow the lecture. Dense engines need channels removed (Chapter 0) and the A100 runs 2:4 (Chapter 8). EIE handles fine-grained zeros (Chapters 6 and 7), and point clouds use sparse convolution (Chapter 9).
| Item | Number | What it shows |
|---|---|---|
| AMC on MobileNet, 50% FLOPs | 569M to 285M MACs; 70.6% to 70.5%; 119.0 to 64.4 ms | Per-layer ratios halve the work for 0.1 points, a 1.8x speedup |
| AMC, 50% time budget | 272M MACs; 70.2%; 59.7 ms | A latency table gives 2.0x for 0.4 points |
| Uniform 0.75 MobileNet | 325M MACs; 68.4%; 69.5 ms | 1.7x but 2.2 points lost |
| AMC on ResNet-50 | 20% density against 29% by a human | The agent learned to prune 3×3 layers more than 1×1 |
| Fine-tuning rate | 1/100 to 1/10 of the original | Small steps keep the surviving weights |
| Iterative pruning, AlexNet | 5x to 9x | Small cuts plus retraining reach a higher ratio |
| NetAdapt short fine-tune | 10k iterations per candidate | Measured accuracy picks the layer; #models = #iterations |
| EIE | 90% static, 70% dynamic sparsity; 4-bit weights | 10x and 3x less computation; 5x and 8x less memory |
| EIE benchmark layers | 33x (AlexNet 6 and 7), 100x (VGG 6) | Listed FLOP reduction from both zero kinds |
| A100 with 2:4 | 2x peak; 1.5x measured on BERT | Regular zeros turn into real speed |
| 2:4 storage | R × C/2 values + 2 bits each | Half the values and a thin index |
| Point clouds | about 0.01% nonzero; 9 against 2 multiplies in the example | Skip the empty space, not just the zeros |
| Grouping in TorchSparse | extra computation 2/28 in the toy example | A little padding buys regular multiplies |
| TorchSparse++ (MICRO 2023) | redundant computation 12, then 10, then 8 in the toy figure | Row reordering and column splitting, with memory and compute overlapped |
| PointAcc | 2.4x to 269x speedup; up to 1,319x energy saving | Over an RTX 2080Ti, a Xeon Skylake with a TPU V3, and a Xeon Gold 6130, across point-cloud networks |
| Pruning papers per year | under 500 until about 2013, over 3,000 by about 2021 | The field took off with Deep Compression and EIE; Optimal Brain Damage dates from 1989 |
| Term | Plain meaning |
|---|---|
| Sensitivity analysis | Prune one layer at a time, record the accuracy drop, and pick a ratio from each curve with one threshold. |
| AMC | A DDPG agent that outputs a continuous pruning ratio per layer, scored by accuracy under a budget. |
| NetAdapt | A greedy loop that cuts a fixed latency each round, using a lookup table, and keeps the best candidate. |
| Iterative pruning | Alternate small cuts with fine-tuning, so each cut is easy to recover from. |
| L1 and L2 penalty | Training adds a cost for large weights. L1 can drive weights to exact zero. |
| Static and dynamic sparsity | Weight zeros are fixed after pruning. Activation zeros change with every input. |
| Relative index, column pointer | EIE's two lists that say where each stored nonzero sits and where each column starts. |
| Load imbalance | Some PEs get more nonzeros than others, so the pass waits for the busiest one. |
| 2:4 sparsity | Exactly two nonzeros in every group of four weights, with 2-bit position codes. |
| Submanifold sparse convolution | Compute outputs only where the input was nonzero, so sparsity does not spread. |
| Map | A triple (input point, output point, kernel weight) that names one small matrix multiply. |
pythondef compress(model, data, target, hardware): drops = sensitivity(model, layers_of(model), evaluate, prune_layer) # Chapter 1: L x 10 table ratios = ratios_for(drops, T=3.0) # or an AMC agent, or NetAdapt (Chapters 2, 3) for f in (0.3, 0.6, 1.0): # prune in rounds (Chapter 4) step = {n: r * f for n, r in ratios.items()} # a growing share of each layer's ratio if hardware == "ampere": masks = mask_2_4(model) # Chapter 8: two of every four elif hardware == "dense": masks = channel_masks(model, step) # Chapter 0: real smaller matrices else: masks = magnitude_masks(model, step) # fine-grained, for a sparse engine (Chapters 6, 7) fine_tune(model, data, masks, lr_scale=0.01) # keep zeros at zero after each update return model, measure_latency(model, target) # the number that counts
This lesson follows Lecture 4 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course page, which links the slides PDF. The papers the lecture cites include:
All explanations, devices and toy numbers here are our own, and every toy number is labelled where it appears.
Now press Teach and explain, from memory, why a 90% sparse network can run no faster, and which pattern you would pick for a phone, an A100 and a sparse chip. Then go back to the budget at the top and compare the three methods once more.