Pruning and Sparsity II

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.

Spend a pruning budget

70%

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

Why Pruning Needs Two More Answers

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.

The four decisions

Pruning sets weights to zero so the network stores and computes less. Every pruning method makes four decisions.

  1. Granularity. In what pattern do we cut: single weights, or whole rows and channels?
  2. Criterion. Which weights do we cut? The less important ones, so we need a measure of importance.
  3. Ratio. What fraction does each layer lose?
  4. Fine-tuning. How do we recover the accuracy we lost?

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.

The goal as one line of math

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.

Say it aloud

Arg min over W-P of L of x and W-P, subject to the zero-norm of W-P being at most N.

arg min
arg min over W-P search all the ways to prune and return the one that makes the loss smallest. It names a search, not a formula.
WP
W-P the pruned weights: the original weights W with some entries forced to zero.
L(x; WP)
L of x and W-P the loss: how wrong the network is on input x when it uses W-P.
∥WP∥0
the zero-norm of W-P the count of nonzero entries in W-P.
≤ N
at most N the budget: the number of nonzero weights we allow.
In plain words

Look at every pruned version W-P that keeps at most N weights nonzero. Pick the one with the smallest loss L.

With numbers

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.

Granularity: where the zeros may fall

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.

Cut the same weights two ways

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.

  1. One ratio per layer: sensitivity analysis and its blind spot.
  2. AMC: a learning agent that picks every ratio.
  3. NetAdapt: a greedy loop with real latency numbers.
  4. Fine-tune, iterate, regularize: getting accuracy back.
  5. Sparsity needs hardware: the three kinds of lazy work, and the EIE idea.
  6. EIE: storing and walking zeros: pointers, relative indices and parallel engines.
  7. EIE inside: the chip, the benchmark and the retrospective.
  8. 2:4 sparsity: the pattern GPUs support.
  9. Sparse convolution: TorchSparse, PointAcc and sparse inputs.
  10. The field guide: numbers, code and where to go next.
You prune a layer by cutting its 50% smallest weights anywhere (fine-grained). A plain dense matrix engine runs the layer. What happens to its work?

Chapter 1

Find Each Layer's Ratio by Testing How Much It Hurts

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 recipe

The lecture runs it on VGG-11 trained on CIFAR-10.

  1. Pick one layer Li. Leave every other layer untouched.
  2. Prune Li by each ratio r in 0, 0.1, 0.2, up to 0.9 (other steps work too). Measure the accuracy drop at each.
  3. Repeat for every layer. You now hold one curve per layer.
  4. Choose one degradation threshold. Give each layer the largest ratio whose drop stays under it.
  5. Tune the threshold until the overall pruning rate is the one you want.

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.

Say it aloud

r-i equals the largest r such that delta-Acc i at r is at most T.

ri
r-i the pruning ratio layer i receives, from 0 to 1.
max { r : … }
the largest r such that scan the tested ratios and keep the biggest one that passes the test after the colon.
ΔAccir
delta-Acc i at r the accuracy lost, in points, when only layer i is pruned by ratio r. It is zero at r = 0.
T
T the degradation threshold: one allowed drop, shared by every layer.
In plain words

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.

With numbers

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.

Read ratios off the curves

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.

8 points

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.

The failure: every layer passes, the network fails

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.

The cost of the test. Ten ratios times L layers means 10 × L passes over a validation set. No training is needed, so it is cheap. That is why people still use it as a first look.

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()}
You use one threshold T for every layer. One layer's curve stays flat until 80% pruned. Another falls at 20%. What does the method give them?

Chapter 2

Let an Agent Choose Every Ratio

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.

WordPlain meaningIn AMC
AgentThe learnerA DDPG agent (Deep Deterministic Policy Gradient). It outputs a continuous number, so it can choose 0.43, not only 25%, 50% or 75%.
EnvironmentThe world it acts onThe network under channel pruning: a ratio of 0.5 removes half of a layer's channels and leaves a smaller dense layer.
StateWhat the agent seesFacts about layer t, st = [N, C, H, W, i, …]: its index, channel counts, kernel size, FLOPs.
ActionWhat it doesOne pruning ratio a, from 0 up to but not including 1.
RewardThe scoreOne number, after the last layer is pruned.
PolicyThe rule it learnsState 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.

Say it aloud

R equals minus Error if the constraint holds, and minus infinity if it does not.

R
R the reward. The agent tries to make it as large as possible.
−Error
minus Error a lower error gives a higher reward. The lecture's figure also shows a smoother form, minus Error times log of FLOP, which favours cheaper networks a little.
if … holds
if the constraint holds the pruned network's FLOPs or latency is within the budget.
−∞
minus infinity the worst possible score, so the agent learns to stay inside the budget.
In plain words

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.

With numbers

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.

Run the agent

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.

50%

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.

What the real agent learned

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:

ModelMACsTop-1LatencySpeedupMemory
1.0 MobileNet569M70.6%119.0 ms1x20.1 MB
AMC (50% FLOPs)285M70.5%64.4 ms1.8x14.3 MB
AMC (50% time)272M70.2%59.7 ms2.0x13.2 MB
0.75 MobileNet325M68.4%69.5 ms1.7x14.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.

The failure: a good score, wrong target

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
AMC's action is a pruning ratio between 0 and 1. Why does the lecture pick a DDPG agent for it?

Chapter 3

Trim in Small Steps, Measured on the Real Device

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.

One round

  1. Choose a small latency cut ΔR by hand.
  2. For each layer, A to Z in the lecture's figure, prune only that layer by the amount that saves ΔR. A table gives the amount.
  3. Fine-tune each candidate briefly (10k iterations) and measure its accuracy.
  4. Keep the most accurate candidate. Drop the rest.
  5. Repeat until the total cut meets the constraint. Then run one long fine-tune.

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.

Say it aloud

n-k equals delta-R divided by c-k, rounded up.

nk
n-k the channels removed from layer k in its candidate this round.
⌈ ⌉
rounded up to the next whole channel, so the cut saves at least delta-R.
ΔR
delta-R the latency to remove this round, in ms, set by hand. Small means many careful rounds.
ck
c-k the milliseconds one channel of layer k costs, read from the table.
In plain words

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 numbers

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.

Run the greedy loop

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.

Why it works, and how it differs from AMC

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.

AMCNetAdapt
SearchA learned policy proposes all ratios togetherOne greedy choice per round, no look-ahead
Main costMany episodes to train the agentMany short fine-tunes
ResourceFLOPs, or latency if you add a tableMeasured latency from the start

The failure: a table that does not match the device

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
In one NetAdapt round, what is the lookup table used for?

Chapter 4

Get the Accuracy Back: Fine-Tune, Iterate, Regularize

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.

Cut one-shot, fine-tune, or iterate

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: shrink before you cut

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′.

Say it aloud

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.

L′
L-prime the new loss that training minimizes.
L(x; W)
L of x and W the old loss on input x with weights W.
λ
lambda the penalty strength. Zero means no penalty. A larger value pushes harder toward small weights.
|W|
the absolute value of W L1: the sum of the weights' absolute values. Every unit of size costs the same.
∥W∥2
the squared norm of W L2: the sum of squares. Large weights pay much more than small ones.
In plain words

Add up the weights' sizes: absolute values for L1, squares for L2. Multiply by lambda. Add that to the old loss L.

With numbers

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.

Watch weights shrink

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.

0.040

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.

The failure: cut too much at once

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
You must reach a very high sparsity. Why does iterative pruning usually beat one big cut followed by fine-tuning?

Chapter 5

A Model Full of Zeros Still Needs a Machine That Skips Them

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.

Three kinds of lazy

SavingRuleKind of zerosSlide's figure
Sparse weights0 × A = 0Static: fixed after pruning, known before any input90% sparse: 10x less computation, 5x less memory
Sparse activationsW × 0 = 0Dynamic: ReLU zeroes negative outputs, and which ones changes with every input70% sparse: 3x less computation
Weight sharing2.09 and 1.92 both become 2A 16-entry codebook: each weight becomes a 4-bit index, not a 32-bit float8x 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.

Say it aloud

Useful MACs is about w times a times dense MACs.

useful MACs
useful MACs the multiply-adds where both inputs are nonzero.
≈
is about exact only if the two kinds of zeros fall independently.
w
w the weight density: 0.1 means 90% sparse.
a
a the activation density: the fraction of activations that are nonzero.
dense MACs
dense MACs rows times columns of the weight matrix: the work of a dense engine.
In plain words

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.

With numbers

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.

Count the multiply-adds

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.

9%
35%

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.

Why a plain GPU does not collect this

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))
A layer has 10% nonzero weights and 30% nonzero activations. An engine skips every multiply with a zero input. About what fraction of the dense multiply-adds does it still do?

Chapter 6

EIE Stores Only the Nonzeros and Walks Them in Parallel

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.

Split the rows, store by column

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:

  1. Virtual weights: W0,0, W0,1, W4,2, W0,3, W4,3. "Virtual" means the full matrix exists on paper, but only these five are stored.
  2. Relative index: 0, 0, 1, 0, 0. Each counts the zero rows, in this PE's share, since the previous stored weight in the same column. The 1 belongs to W4,2, because row 0 of column 2 is zero.
  3. Column pointer: 0, 1, 2, 3, 5. Column j runs from pointer j up to, but not including, pointer j + 1. So column 3 holds two weights.

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.

The dataflow

  1. Scan the activations. A zero aj is skipped and no PE works. In the example, a0 and a2 are zero.
  2. Broadcast a nonzero aj and its index j to every PE.
  3. Each PE finds column j with its pointers, multiplies each stored weight there by aj, and adds the product into the row that the relative index names.
  4. After the last activation, apply ReLU. The sums are the output b.

Step through the walk

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).

The failure: one PE does all the work

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)
In EIE's dataflow, an activation a3 is nonzero. What happens next?

Chapter 7

Inside One EIE Processing Element, and What It Bought

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.

  1. Activation queue and leading nonzero detect. The queue holds incoming activations. The detector skips the zeros and picks the next nonzero one. This collects activation sparsity.
  2. Pointer read. The pointers pj and pj+1 sit side by side, so the chip keeps them in an even and an odd memory bank and reads both in one cycle.
  3. Sparse matrix access. The sparse matrix SRAM, a fast on-chip memory, gives every stored entry from pj up to pj+1.
  4. Weight decoder. Each entry is a 4-bit code. A 16-entry table turns it into a 16-bit weight. This undoes weight sharing.
  5. Address accumulate and arithmetic. The relative index becomes an absolute row address. The multiplier forms weight × activation, and the adder adds it to that row's sum. A bypass path feeds a fresh sum straight back when two products hit the same row back to back.
  6. Write back. The outputs get ReLU. A nonzero detector marks the survivors, so the next layer's queue gets only nonzero activations.

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.

Keep the PEs fed

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.

Fill the idle gaps

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.

20%

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 benchmark

The lecture benchmarks nine layers from three networks. The last column is ours: 1 / (weight density × activation density).

LayerSizeWeights nonzeroActivations nonzeroListed FLOP reductionOur product estimate
AlexNet layer 64096 × 92169%35%33x32x
AlexNet layer 74096 × 40969%35%33x32x
AlexNet layer 81000 × 409625%38%10x11x
VGG layer 64096 × 250884%18%100x139x
VGG layer 74096 × 40964%37%50x68x
VGG layer 81000 × 409623%41%10x11x
NeuralTalk We600 × 409610%100%10x10x
NeuralTalk Wd8791 × 60011%100%10x9x
NeuralTalk LSTM2400 × 120110%100%10x10x

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.

The lecturer's retrospective

SidePoint
ProSpecial hardware makes sparse operations pay for matrices up to 50% dense.
ProIt skips zero weights and zero activations, so it saves energy and cycles.
ProIt supports fine-grained sparsity, so pruning can go further.
Pro4-bit weights decoded to 16-bit arithmetic. That W4A16 recipe is back in LLMs: GPTQ, AWQ, llama.cpp, MLC LLM.
ConIt does not map easily onto arrays of vector processors. The fix: structured sparsity such as N:M (Chapter 8).
ConControl flow and storage cost overhead. The fix: coarser-grained sparsity.
ConIt supports only fully connected layers, which LLMs now revive.
ConEverything fits in on-chip SRAM: practical for TinyML, not for an LLM.
The first principle: be lazy. The lecture's closing slide for this part says efficient AI computing means avoiding redundant computation, rejecting work early, or delaying it. It lists examples: spatial sparsity in image generation (SIGE), token sparsity in Transformers (SpAtten), temporal sparsity in video (TSM) and spatial sparsity in point clouds (TorchSparse and PointAcc). It expects future models to be sparse at several granularities, built together with accelerators.

The failure: skipping that costs more than it saves

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
Which piece of an EIE processing element undoes weight sharing, and what does it do?

Chapter 8

2:4 Sparsity: A Pattern Simple Enough for a GPU

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.

The format

  1. Values: R rows by C/2 columns. Each row keeps 2 of every 4 weights, pushed to the left in memory.
  2. Metadata: also R by C/2, with 2 bits per entry. Each entry says which of the four slots its value came from, since 2 bits count 0 to 3. A free pattern in a row of 16 would need 4 bits.

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.

Say it aloud

S equals C over 2 times b plus 2, divided by C times b, which equals b plus 2 over 2 b.

S
S the compressed size as a fraction of the dense row.
C/2
C over 2 the values kept: half the row.
b
b bits per value: 16 for FP16, 8 for INT8.
+ 2
plus 2 the 2-bit slot index stored with each kept value.
C × b
C times b the dense row: C values of b bits each.
In plain words

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 numbers

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.

The tensor core picks the matching half

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.

Keep half, two ways

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.

What it bought

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:

NetworkDense FP16Sparse FP16Sparse INT8
ResNet-3473.773.973.7
ResNet-5076.176.276.2
ResNet-10177.778.077.9
DenseNet-12175.575.375.3
VGG-1674.074.174.1
ResNeXt-101-32x16 (WSL)84.284.084.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.

The failure: a group with three big weights

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
Why does each stored value in a 2:4 matrix need only a 2-bit index?

Chapter 9

Sparse Convolution: Skip the Empty Space Itself

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.

A convolution as a list of maps

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.

Say it aloud

f-Out becomes f-Out plus f-In times W-Wgt, once for every map In, Out, Wgt.

fOut
f-Out the running sum for output point Out: C-out numbers.
← … +
becomes f-Out plus add the product into the sum already there.
fIn
f-In the feature row of input point In: C-in numbers.
WWgt
W-Wgt the kernel weight for one offset, such as (−1, −1): a C-in by C-out matrix.
(In, Out, Wgt)
for every map one line of the map list: which input, through which weight, into which output.
In plain words

For each map in the list, multiply f-In by W-Wgt and add the product into f-Out.

With numbers

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.

Find the maps for a weight

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.

Running the maps on a GPU, one weight at a time

  1. Gather the input rows named by the nk maps of kernel weight Wk into a buffer, nk × Cin.
  2. Multiply by Wk, Cin × Cout, to get nk × Cout.
  3. Scatter-accumulate each result row into its output row.

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: trade a little work for regularity

TorchSparse (Tang et al., MLSys 2022) reorders gather and scatter for locality, then chooses how to run the multiplies:

Group the maps

Bars are the 27 map sizes, largest first; warm is padding.

4

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.

PointAcc: find the maps with a merge sort

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).

The failure: every offset is its own tiny job

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
TorchSparse bundles kernel weights with similar map sizes into groups and pads inside each group. What is the trade it makes?

Chapter 10

The Field Guide: Numbers, Checklist and Code

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.

Which hardware, which pattern?

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.

Match the pattern to the machine

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).

Numbers to remember

ItemNumberWhat it shows
AMC on MobileNet, 50% FLOPs569M to 285M MACs; 70.6% to 70.5%; 119.0 to 64.4 msPer-layer ratios halve the work for 0.1 points, a 1.8x speedup
AMC, 50% time budget272M MACs; 70.2%; 59.7 msA latency table gives 2.0x for 0.4 points
Uniform 0.75 MobileNet325M MACs; 68.4%; 69.5 ms1.7x but 2.2 points lost
AMC on ResNet-5020% density against 29% by a humanThe agent learned to prune 3×3 layers more than 1×1
Fine-tuning rate1/100 to 1/10 of the originalSmall steps keep the surviving weights
Iterative pruning, AlexNet5x to 9xSmall cuts plus retraining reach a higher ratio
NetAdapt short fine-tune10k iterations per candidateMeasured accuracy picks the layer; #models = #iterations
EIE90% static, 70% dynamic sparsity; 4-bit weights10x and 3x less computation; 5x and 8x less memory
EIE benchmark layers33x (AlexNet 6 and 7), 100x (VGG 6)Listed FLOP reduction from both zero kinds
A100 with 2:42x peak; 1.5x measured on BERTRegular zeros turn into real speed
2:4 storageR × C/2 values + 2 bits eachHalf the values and a thin index
Point cloudsabout 0.01% nonzero; 9 against 2 multiplies in the exampleSkip the empty space, not just the zeros
Grouping in TorchSparseextra computation 2/28 in the toy exampleA little padding buys regular multiplies
TorchSparse++ (MICRO 2023)redundant computation 12, then 10, then 8 in the toy figureRow reordering and column splitting, with memory and compute overlapped
PointAcc2.4x to 269x speedup; up to 1,319x energy savingOver an RTX 2080Ti, a Xeon Skylake with a TPU V3, and a Xeon Gold 6130, across point-cloud networks
Pruning papers per yearunder 500 until about 2013, over 3,000 by about 2021The field took off with Deep Compression and EIE; Optimal Brain Damage dates from 1989

Terms in plain words

TermPlain meaning
Sensitivity analysisPrune one layer at a time, record the accuracy drop, and pick a ratio from each curve with one threshold.
AMCA DDPG agent that outputs a continuous pruning ratio per layer, scored by accuracy under a budget.
NetAdaptA greedy loop that cuts a fixed latency each round, using a lookup table, and keeps the best candidate.
Iterative pruningAlternate small cuts with fine-tuning, so each cut is easy to recover from.
L1 and L2 penaltyTraining adds a cost for large weights. L1 can drive weights to exact zero.
Static and dynamic sparsityWeight zeros are fixed after pruning. Activation zeros change with every input.
Relative index, column pointerEIE's two lists that say where each stored nonzero sits and where each column starts.
Load imbalanceSome PEs get more nonzeros than others, so the pass waits for the busiest one.
2:4 sparsityExactly two nonzeros in every group of four weights, with 2-bit position codes.
Submanifold sparse convolutionCompute outputs only where the input was nonzero, so sparsity does not spread.
MapA triple (input point, output point, kernel weight) that names one small matrix multiply.

A checklist for compressing a model

The whole recipe as code

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

Keep going

The takeaway. A sparse model is only as fast as the machine that can skip its zeros. Choose each layer's ratio with search, not by hand. Retrain gently after each cut. Then shape the zeros to fit the hardware you will ship on.
You must ship one pruned model on an Ampere GPU. Which plan follows the lecture?

Credit and sources

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.

MIT 6.5940 Lecture 4: Pruning and Sparsity II
The course site and slides · Back to Lecture 3 · On to Lecture 5 · Back to Gleams