Pruning and Sparsity

Han et al. cut AlexNet from 61 M to 6.7 M weights, 9× fewer. Yet a GPU only runs faster when the zeros follow a pattern it can skip.

Learn how to remove most of a trained network, which pieces to cut, and which cuts a real chip can turn into speed.

Pick a way to prune, then drag the sparsity slider. Compare how much the output changes with how much faster a dense GPU runs. Then we build, piece by piece, the problem, the pruning loop, the granularities and the criteria that choose what to cut.

You need matrix multiplication (a layer is a table of weights times a vector) and a little Python. We build the rest from zero.

Based on Lecture 3 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 2, NN Building Blocks and leads into Lecture 4, Pruning II.

Prune the same layer

50%

Illustrative: one made-up 8 by 8 weight matrix and 48 random inputs. The output error is measured live: how far the pruned layer's output moves, as a share of the dense output's size. The 2× for 2:4 is the peak figure in the lecture; the measured BERT speedup it quotes is 1.5×. The row-pruning speedup assumes the work shrinks with the matrix.

Chapter 0

Why Memory, Not Math, Is the Bill

See what one weight costs to fetch, and why that makes a smaller network the cheapest speedup there is

Your phone runs a camera model that names a plant. For every frame, it reads the whole model out of memory once. A model is a long list of numbers called weights, like the dials on a huge mixing desk. Each read of a weight costs energy.

The lecture prices that read with a table from Mark Horowitz's 2014 talk: the energy of basic operations on a 45 nm chip at 0.9 V, in picojoules (pJ), trillionths of a joule.

OperationEnergyWhat it is
32 bit int ADD0.1 pJAdd two whole numbers
32 bit float ADD0.9 pJAdd two decimal numbers
32 bit register file1 pJRead a number held right beside the arithmetic unit
32 bit int MULT3.1 pJMultiply two whole numbers
32 bit float MULT3.7 pJMultiply two decimal numbers
32 bit SRAM cache5 pJRead a number from small, fast memory on the chip
32 bit DRAM memory640 pJRead a number from the large, slow memory off the chip

SRAM is small, fast memory on the chip, like a notepad on your desk. DRAM is big memory on a separate chip, like a library across the road. A trained network does not fit on the notepad, so its weights live in the library.

The slide's headline: more data movement means more memory reads, and more energy. A DRAM read is about 200 times a cheap operation, and 640 / 3.7 = 173 times a float multiply.

One layer, one bill

A layer does multiply-accumulates (MACs): multiply a weight by an input and add it to a running total. One float MAC costs 3.7 + 0.9 = 4.6 pJ. Take a fully connected layer of 1,000,000 weights at batch size 1: it uses each weight once.

  1. Arithmetic: 1,000,000 MACs × 4.6 pJ = 4.6 µJ.
  2. Fetching: 1,000,000 weights × 640 pJ = 640 µJ.
  3. The fetch costs 640 / 4.6, about 139 times the arithmetic.

AlexNet, an image network from 2012, has 61 million weights. One pass reads 61,000,000 × 640 pJ = 39 mJ from DRAM. At 30 frames a second that is about 1.2 W, for fetching weights alone.

The cheapest cut

The slide then asks: how should we make deep learning more efficient? If most of the cost is fetching weights, fetch fewer. That is pruning: remove the weights that matter least, so the chip never fetches them and never multiplies by them.

Pay the memory bill

Top: the lecture's seven operations on a log scale, where a bar one quarter longer means ten times more energy. Bottom: one layer of 1,000,000 weights. Drag the share you keep.

100%

Energies: the lecture's Horowitz table (45 nm, 0.9 V). The layer is illustrative: 32 bit weights at batch size 1, each fetched once, pruned weights fully skipped. Real sparse formats also store indices, which adds some cost back.

Keep 10% and the fetch bill drops from 640 µJ to 64 µJ. Each kept weight costs one fetch, so the bill scales straight with the count.

The plan of the course

Part 1 of MIT 6.5940 is efficient inference, with four tools: pruning, quantization, neural architecture search and knowledge distillation. Of the five pruning questions (what, which pattern, which weights, how much, how to retrain), this lecture answers the first three.

The road

  1. The pruning problem: the formula, the four questions, and the brain.
  2. Prune, finetune, repeat: why you retrain, and why you repeat.
  3. What pruning delivered: parameters against MACs, and the chips that help.
  4. Granularity: scattered or tidy: unstructured against structured.
  5. Granularity in convolutions: five patterns on a four dimensional tensor.
  6. Fine-grained and N:M: 2:4 sparsity and its compressed format.
  7. Channel pruning: a narrower network, and the per-layer ratio.
  8. Magnitude and scale: the simplest scores for synapses and filters.
  9. Second-order scores: Optimal Brain Damage and the Hessian.
  10. Neurons: zeros and regression: scores that look at activations.
  11. The field guide: numbers, code and where to go next.
A layer's weights live in DRAM. One float MAC costs 4.6 pJ and one DRAM fetch costs 640 pJ. You prune 80% of the weights and the chip skips them completely. About how does the layer's energy change?

Chapter 1

Pruning Is a Choice of Which Connections to Keep

Write the problem as one formula, then see why you cannot solve it by trying every answer

You pack a suitcase with a 10 kg limit and a 25 kg pile. For each item you ask: if it stays home, how much does the trip suffer? Pruning asks that of each weight, and the trip is the accuracy.

A neural network is a stack of layers of neurons. Each neuron multiplies its inputs by weights, adds them, and passes the sum through a simple function. A weight joins two neurons, so the lecture also calls it a synapse. Pruning synapses deletes single connections. Pruning neurons deletes a whole unit with every connection into and out of it.

LeCun et al. named the idea Optimal Brain Damage in 1989, and Han et al. revived it in 2015. The brain does it too: about 2,500 synapses per neuron at birth, 15,000 at age two to four, 7,000 in an adult.

The formula

Call the input x and the trained weights W. Call the pruned weights WP: the same table with some entries set to exactly zero. The loss L says how badly the network does. The budget N is the most non-zero weights you may keep.

Say it aloud

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

arg min
arg min try every allowed choice and return the one with the smallest value.
WP
W-P the pruned weights: the trained table W with some entries set to exactly 0.
L(x; WP)
L of x and W-P the loss of the pruned network on input x. Lower is better.
‖WP‖0 ≤ N
the L-zero norm of W-P is at most N count the entries that are not zero. At most N may stay.
In plain words

List every way to zero out weights so that at most N stay. Compute the loss L for each W-P. Keep the one with the lowest loss.

With numbers

With made-up numbers: six weights and N = 3 give 20 masks. Compute L for all 20 and keep the lowest.

Why you cannot just try them all

With M weights and room for N, there are "M choose N" masks. Drag M and read the count.

Count every possible mask

Blue dots stay, hollow dots go. Drag M, then press the button for another random half.

6

The counts are exact. The time assumes an illustrative machine that tests one billion masks a second; a real loss evaluation takes far longer.

At 20 weights there are 184,756 masks. At 64 there are about 1.8 × 1018, some 58 years at a billion tests a second. A real layer has millions. So nobody solves the formula exactly, and every practical method is an approximation.

The four decisions

  1. Granularity: in what pattern do we prune? One weight, a row, or a channel? (Chapters 4 to 7)
  2. Criterion: which synapses or neurons do we prune? We need a score of how much each matters. (Chapters 8 to 10)
  3. Ratio: what share of each layer do we prune: 30%, 50%, 70%? (Lecture 4)
  4. Fine-tune: how do we win back the accuracy the cut cost? (Chapter 2, and Lecture 4)

The choices combine. You can score by size and cut whole channels, or score by curvature and cut single weights.

The failure: counting nearly zero as zero

Symptom: the report says 90% sparse, and the model file is the same size. Measure: the vector (0.0001, 0, 2, 0.0003) has L0 norm 3, because only an exact zero is not counted. Fix: set pruned weights to exactly zero, and keep a mask so they stay zero.

pythonimport torch
w = torch.tensor([0.0001, 0.0, 2.0, 0.0003])
print((w != 0).sum().item())              # L0 norm: 3 non-zeros
mask = (w.abs() > 0.001).float()          # 1 = keep, 0 = prune
print((w * mask).count_nonzero().item())  # after pruning: 1 non-zero
Why can the pruning problem, with the L0 budget, not simply be solved by checking every possible mask?

Chapter 2

Prune, Finetune, Repeat

Watch accuracy fall as you cut, and see how retraining and repeating push the cliff further away

Cut a third of a wild hedge in one afternoon, and it looks thin for weeks. Trim a little each week, and it fills in around every cut. A network behaves the same way.

The lecture's chart (Han et al., 2015) plots accuracy loss against the pruning ratio, the share of weights removed. It adds one curve per step. The values are read off the slide.

  1. Train connectivity. Train the dense network as usual. Its weights form one tall bump around zero.
  2. Prune connections. Remove the smallest weights, and the middle of the bump empties. The Pruning curve falls steeply: about 4% loss at 80% pruned.
  3. Train weights. Hold the cut weights at zero and train the survivors. The Pruning + Finetuning curve stays near zero loss to about 80%.
  4. Repeat. Prune a little, retrain, prune a little more. The Iterative curve stays near zero to about 90%.

Why cutting hurts, and why retraining heals

Weights train together, so each one sits where it is because of the others. Take two nearly equal inputs x1 and x2, and y = 2x1 + 2x2, about 4x. Prune the second weight: y = 2x1, about 2x. The output halves, and the loss rises.

Finetuning reruns training on the survivors. The output is too small, so the gradient pushes the first weight from 2 toward 4. Then y = 4x1: one weight does the job of two. Small cuts work better, because each leaves a small error to repair before the next.

Cut, retrain, repeat

Each curve is test error over the full model's error, on a log scale. Lower is better. Drag the ratio, and switch curves on and off.

80%

Toy run live in your browser: a linear model with 40 correlated inputs, 150 training and 500 test examples, all made up. Pruning drops the smallest weights. Finetune refits the survivors exactly. Iterative drops one weight at a time and refits.

At 50% the plain cut more than doubles the error. The finetuned model sits at about 1.3 times the full model, and the iterative one matches the full model. Near 90% all three suffer, and iterative is still lowest.

The real code

In a deep network, finetuning is normal training plus one rule: multiply the mask back in after every update, so pruned weights stay at exactly zero.

pythondef finetune(model, masks, loader, opt, epochs):
    for _ in range(epochs):
        for x, y in loader:                      # x: (B, ...), y: (B,)
            loss = loss_fn(model(x), y)
            opt.zero_grad(); loss.backward(); opt.step()
            with torch.no_grad():
                for p, m in zip(model.parameters(), masks):
                    p.mul_(m)                    # pruned weights back to exactly 0

def iterative_prune(model, steps=(0.2, 0.4, 0.6, 0.8)):
    for s in steps:                              # a little more each round
        masks = [magnitude_mask(p, s) for p in model.parameters()]
        finetune(model, masks, loader, opt, epochs=2)

The failure: finetuning without the mask

Symptom: the model is 80% sparse before finetuning and 12% after. Measure: count the zeros in each weight tensor after training. Fix: apply the mask after every optimizer step. The optimizer does not know which weights you pruned, so it moves them.

After you prune half of a layer's weights, accuracy falls. Which step best explains why finetuning can win it back?

Chapter 3

What Pruning Delivered, and Who Built Chips for It

Compare weights saved with work saved on five real networks, and meet the hardware that turns zeros into speed

A publisher cuts a book's appendix. The book is cheaper to print, but no faster to read. Pruning has the same split between what you store and what you compute.

The parameter reduction counts the weights left: file size and fetches. The MACs reduction counts the multiply-accumulates left: arithmetic. A fully connected layer uses each weight once per input, so its MACs equal its weights. A convolution reuses each weight at every output position, so its MACs are its weights times the positions.

AlexNet's three fully connected layers hold 9,216 × 4,096 + 4,096 × 4,096 + 4,096 × 1,000 = 58.6 million of its 61 million weights. They do only 58.6 million MACs. The convolutions hold few weights and do most of the arithmetic. Most of the cut falls in the fully connected layers, so weights fall 9 times and MACs only 3 times.

Weights saved against work saved

Top pair: parameters before and after pruning. Bottom: the share of MACs left. A shorter bar is a bigger saving.

Numbers: the lecture's table (Han et al. 2015, and S. Han's Stanford talk). The share of MACs left is one over the table's MACs reduction.

VGG-16 matches AlexNet: 12 times fewer weights, 5 times fewer MACs. GoogleNet and ResNet50 flip it: MACs fall 5 and 6.3 times, weights only 3.5 and 3.4 times. Their pruned weights sat in layers that reuse each weight many times. So count what you must save: parameters for storage, MACs for arithmetic.

Accuracy survives, and chips followed

The lecture shows captions from NeuralTalk, an LSTM (a network that writes one word at a time). Pruned 90%, it says "a basketball player in a white uniform is playing with a basketball". The baseline said "with a ball". The hardware the lecture lists:

HardwareWhat the slide says
EIE (Han et al., ISCA 2016), ESE (FPGA 2017)Custom accelerators for sparse networks
SpArch (HPCA 2020), SpAtten (HPCA 2021)Later sparse accelerators
NVIDIA A1002:4 sparsity (Chapter 6): 2× peak, 1.5× measured on BERT
AMD Xilinx Vitis AI OptimizerPrune and finetune: 5× to 50× less model complexity with minimal accuracy impact

The A100 gap from 2 to 1.5 is normal. Only some layers are sparse, and memory steps do not speed up.

The failure: celebrating a parameter count

Symptom: a team reports "90% sparse" and sees no change in GPU latency. Measure: time the same input through both models on the same card. Fix: check the pattern of the zeros. A chip saves only the zeros it can skip.

ResNet50 is pruned from 26 M to 7.47 M parameters (3.4×), and its MACs fall 6.3×. What does that say about where the pruned weights were?

Chapter 4

Granularity: Scattered Holes or Whole Shelves

Compare cutting single weights with cutting whole rows, and see which one a plain chip can use

A bookcase holds eight shelves of eight books, and half must go. Remove the 32 you like least, and every shelf has gaps. Remove four whole shelves, and the bookcase is half as tall with every shelf full. This choice is pruning granularity: the size of the piece you remove.

A fully connected layer multiplies an input vector x by a weight matrix W. Each row of W makes one output, so a row is one neuron. The lecture prunes an 8 by 8 matrix two ways:

PropertyFine-grained (unstructured)Coarse-grained (structured)
What goesAny single weightWhole rows
Choice of indicesMore flexibleLess flexible: a subset of the fine-grained masks
SpeedHard to accelerate (irregular)Easy: just a smaller matrix

A chip multiplies in blocks of neighbouring numbers. A 4 by 8 matrix is a smaller dense matrix: same code, half the work. Scattered zeros leave the matrix 8 by 8. To skip them, the chip needs an index per weight, extra reads and irregular jumps. A plain GPU multiplies by the zeros instead, and saves nothing.

The price of tidiness

Row pruning must take a whole row, big weights too. Score the damage by squared weight, a rough stand-in for harm, on four rows:

  1. A: 0.9, −0.1, 0.8. Sum of squares 0.81 + 0.01 + 0.64 = 1.46.
  2. B: 0.2, 0.3, −0.2. Sum of squares 0.04 + 0.09 + 0.04 = 0.17.
  3. C: −0.7, 0.6, 0.0. Sum of squares 0.49 + 0.36 + 0 = 0.85.
  4. D: 0.1, 0.0, 0.9. Sum of squares 0.01 + 0 + 0.81 = 0.82.

The total is 3.30. Remove 6 of 12 weights. Scattered, keep the six biggest (0.9, 0.9, 0.8, 0.7, 0.6, 0.3): their squares sum to 3.20, so you drop 3%. By rows, keep A and C: 2.31, so you drop 30%. Same budget, ten times the damage.

Same budget, two masks

Left: keep the biggest weights anywhere. Right: keep the heaviest whole rows. Filled cells stay, hollow cells go.

4 of 8

Illustrative: the hero's made-up 8 by 8 matrix and 48 random inputs. The device measures output error live, as a share of the dense output, and scores rows by the sum of absolute weights. MACs count every stored weight a dense chip runs.

At 4 rows kept, both masks keep 32 weights. The scattered one moves the output by 26%, the row mask by 62%. But on a dense chip the scattered matrix still runs all 64 MACs, and the packed rows run 32. A removed row also lets the next layer drop its matching column, which Chapter 7 uses.

The failure: expecting the scattered mask to run faster

Symptom: the model is 50% sparse, the profiler shows 64 MACs per input, and latency has not moved. Measure: count the MACs the kernel runs, not the non-zeros stored. Fix: use hardware that skips zeros (Chapter 6), or prune in a pattern that gives a smaller dense matrix.

You prune half of an 8 by 8 matrix by removing four whole rows. Compared with a scattered 50% mask, what is true on a plain dense GPU?

Chapter 5

Granularity in Convolutions: Five Patterns on Four Dimensions

Open a convolution layer, name its four dimensions, and slide from the most scattered cut to the most regular one

A sharpening filter is a 3 by 3 grid of numbers that slides over a photo. A vision network runs thousands of such filters. A convolution layer turns an input of several channels (like the red, green and blue planes) into an output of several channels. Its weights have four dimensions, [co, ci, kh, kw]:

Each output channel has one filter of ci kernels. The lecture's toy layer has co = 3, ci = 2 and 3 by 3 kernels: 3 × 2 × 9 = 54 weights. Four dimensions give more ways to cut. The lecture lists five, from irregular to regular (Mao et al., CVPR workshop):

  1. Fine-grained. Any single weight, scattered across the tensor.
  2. Pattern-based. Each kernel keeps one shape from a short list of allowed shapes.
  3. Vector-level. A whole row or column of a kernel: three weights in a line.
  4. Kernel-level. A whole 3 by 3 kernel: one input channel's part of one filter.
  5. Channel-level. A whole channel, so the tensor gets thinner in ci or co.

The slide jokes that the shapes look like Tetris. The cleaner the blocks, the easier a chip finds them.

Prune a 3 by 2 by 3 by 3 tensor

Each small grid is one 3 by 3 kernel. Rows are output channels, columns are input channels. Filled cells stay, hollow cells go.

Illustrative: co = 3, ci = 2, masks from a fixed seed, not by importance. We made up the four 2 by 2 pattern shapes. Decisions counts the separate keep or prune facts the mask stores.

Fine keeps 27 of 54 weights with 54 separate decisions. Channel keeps the same 27 with one decision: keep input channel 1, drop channel 2. The chip must read the mask before it can use it. Fifty-four bits are a table to fetch and decode; one bit is read once. Each step to the right gives up some freedom for a cheaper mask.

What a channel cut does to the tensor

Only channel pruning changes the shape. Drop one input channel, and [3, 2, 3, 3] becomes [3, 1, 3, 3], a smaller dense tensor that any routine can run. On a 14 by 14 output map, the MACs go from 54 × 196 = 10,584 to 27 × 196 = 5,292. The other four keep holes in the old shape. Pattern-based is the clever middle: with few shapes, a chip can have a fast path for each.

The failure: pruning one side of a cut

Symptom: you drop input channel 2 of layer B, and the network crashes ("expected 3 channels, got 2") or wastes work. Measure: print the shapes of neighbouring layers. Layer A's output channels must equal layer B's input channels. Fix: also drop output filter 2 of layer A, which fed only that channel.

A convolution layer has weights of shape [64, 32, 3, 3]. How many weights does it have, and which granularity changes this shape?

Chapter 6

Fine-Grained Pruning and the 2:4 Pattern

Give up a little freedom to get a pattern that hardware can read, and see exactly how the compressed matrix is stored

One library lets a book go on any free spot: flexible, and hard to search. Another puts exactly two books on every shelf of four slots: a little wasteful, and anyone finds a book fast.

Fine-grained pruning is the first library. Its indices are free, so it usually reaches the largest compression (AlexNet 9 times, VGG-16 12 times). It can speed up custom hardware such as EIE, but not a GPU, at least not easily.

N:M sparsity: a rule that keeps the pattern regular

N:M sparsity is the second library, a form of pattern-based pruning. Cut each row into groups of M neighbouring weights, and let N survive in each group. The slide words it as "N of them is pruned"; for 2:4 both readings give half. We count N as kept, as NVIDIA does.

2:4 sparsity is exactly 50% sparse. NVIDIA's Ampere GPUs, such as the A100, run it up to 2 times faster, and it usually keeps accuracy across many tasks. The trick: every group has exactly two survivors, so no group has more work than its neighbours.

The compressed matrix

The chip stores the non-zero values packed together, plus a 2-bit index for each value. Take the group 0.9, −0.1, 0.4, −0.7. Keep 0.9 at position 0 and −0.7 at position 3. Store values (0.9, −0.7) and indices 00 and 11. To multiply by inputs a0 to a3, the chip reads the indices and computes 0.9a0 − 0.7a3: 2 MACs instead of 4.

With 16-bit weights, a dense group takes 64 bits. A compressed group takes 2 × 16 + 2 × 2 = 36 bits, 56% of dense. The indices are why storage falls only to 56%.

Compress with an N:M rule

Top: a 4 by 8 weight slice, kept weights filled. Bottom: packed values in blue, one index per kept weight in purple.

Illustrative: the first four rows of the hero's matrix and 48 random inputs. Weights take 16 bits; an index takes the fewest bits that name a position in a group of M (2 bits for M = 4). Real hardware formats are the vendor's.

At 2:4 the slice takes 288 bits against 512, or 56%. At 1:4 only a quarter stays, the compressed matrix shrinks more, and the error climbs. 2:4 is the sweet spot.

The failure: 50% sparse is not 2:4

Symptom: the model is 50% sparse, and the sparse tensor cores give no speedup. Measure: count the non-zeros in each group of four. Three zeros in one group and one in the next average 50% but break 2:4. Fix: keep the two largest weights in every group, as the code does.

pythonimport torch
def nm_mask(w, n=2, m=4):
    g = w.abs().reshape(-1, m)                  # (rows * cols / m, m)
    idx = g.topk(n, dim=1).indices              # the n biggest in each group
    mask = torch.zeros_like(g).scatter_(1, idx, 1.0)
    return mask.reshape(w.shape)                # same shape as w, exactly n of every m kept
In a compressed 2:4 matrix with 16-bit weights, how many bits does one group of four weights take, and why is that not exactly half of 64?

Chapter 7

Channel Pruning: A Narrower Network That Runs Everywhere

Count exactly how many MACs a channel cut saves, and see why each layer needs its own ratio

Trim every station of a kitchen line by the same share, and the busiest one becomes the bottleneck. Trim each by what it can spare instead. That is channel pruning and its question: how much can each layer lose?

Pro: a direct speedup, because the result is an ordinary network with fewer channels. Con: a smaller compression ratio. One filter of a [256, 128, 3, 3] layer holds 128 × 9 = 1,152 weights, and channel pruning removes all of them, big ones too.

Counting the saving

How many MACs does a convolution layer do for one image? Name its output channels co and input channels ci. Name the kernel size kh by kw and the output map size H by W.

Say it aloud

MACs equals c-o times c-i times k-h times k-w times H times W.

MACs
MACs the multiply-accumulates the layer runs for one input image.
co
c-o output channels, the number of filters.
ci
c-i input channels: the planes the layer reads.
kh × kw
k-h times k-w the kernel height times width, here 3 × 3 = 9.
H × W
H times W the output map's height times width (this W is not the weights).
In plain words

One output value needs c-i times k-h times k-w MACs. There are c-o times H times W output values. Multiply the two.

With numbers

Layer 1 turns 3 channels into 64 on a 56 by 56 map: 64 × 3 × 9 × 3,136 = 5,419,008 MACs. Halve c-o to 32 and it falls to 2,709,504.

A cut of layer l's output channels also shrinks ci of layer l + 1. Add layer 2, from 64 to 128 channels on a 28 by 28 map:

  1. Before: 5,419,008 + 128 × 64 × 9 × 784 = 5,419,008 + 57,802,752 = 63,221,760 MACs.
  2. Halve layer 1's outputs: 2,709,504 + 128 × 32 × 9 × 784 = 2,709,504 + 28,901,376 = 31,610,880. Exactly half, from one cut.

Cut every layer by the same ratio s, and each middle layer loses on both sides. Its MACs fall to about (1 − s)2: with s = 0.3, 0.7 × 0.7 = 49% remains.

Why the ratio must differ by layer

The slide gives five layers their own sparsity (0.5, 0.3, 0.7, 0.2, 0.3), next to uniform shrink at 0.3 everywhere. AMC (He et al., ECCV 2018) shows that per-layer ratios beat uniform scaling on mobile: more ImageNet accuracy at the same latency. How AMC finds them is Lecture 4. Tune five toy layers by hand:

Give each layer its own ratio

0.5
0.3
0.7
0.2
0.3

Toy network: channels 64, 128, 256, 256, 512 on maps 56, 28, 14, 14, 7; exact MAC counts. The loss proxy is ours: 100 times the sum of sensitivity (0.4, 0.7, 0.2, 1.0, 0.7) times ratio squared. Uniform spends your MACs.

The slide's ratios keep about 32% of the MACs. Uniform needs s = 0.43 everywhere for the same MACs, and costs 56 proxy points against 36. The tuned ratios spare the sensitive layer 3.

The failure: one ratio for every layer

Symptom: a 40% shrink on every layer drops accuracy far more than expected. Measure: prune each layer alone and record the accuracy. A few layers cause most of the loss. Fix: lower their ratio and raise it on tolerant layers, until you meet the MACs target.

You prune 30% of the output channels of every convolution layer in a network. About what share of the MACs of the middle layers remains?

Chapter 8

Magnitude and Scale: The Simplest Scores

Score each weight, row or filter by how big it is, and learn where the big number hides in a channel

The less important the removed weights, the better the pruned network. Take the slide's neuron y = ReLU(10x0 − 8x1 + 0.1x2), where a ReLU turns negative numbers into zero. If one weight must go, the 0.1 goes: it barely moves y.

That is magnitude-based pruning: importance is the absolute value |W|. To score a row or filter, call the group the structural set S, each weight in it wi, and pick a power p, 1 or 2.

Say it aloud

The L-p norm of W-S equals the sum over i in S of the size of w-i to the p, all to the power one over p.

‖W(S)‖p
the L-p norm of W-S the group's score. Prune the groups with the smallest scores.
∑i∈S
the sum over i in S one term for each weight in the group: one weight element-wise, a whole row row-wise.
|wi|p
the size of w-i to the p p = 1 gives the L1 norm, p = 2 the L2 norm.
1/p
to the one over p the p-th root, which undoes the power.
In plain words

Take the size of each weight w-i in S. Raise it to the power p and add. Take the p-th root. That is the score of S.

With numbers

The slide's matrix [[3, −2], [1, −5]], half cut. Row L1 scores are 5 and 6, so row 0 goes. Row L2 scores are √13 = 3.61 and √26 = 5.10: the same. Element-wise, 1 and 2 go, leaving [[3, 0], [0, −5]].

The norms can disagree, because squaring rewards a few big weights.

Score by size

Numbers are the weights. Filled cells stay, hollow cells go. Row scores sit at the right of each row.

50%

Illustrative rows, built so L1 and L2 disagree at 50%.

At 50% by rows, L1 keeps A and B; L2 keeps B and D. Row A of four equal weights scores 16 by L1 and 8 by L2.

Scaling-based pruning: a ready-made importance dial

Give each filter a trainable scaling factor on its output channel, and prune the small ones (Liu et al., ICCV 2017). The batch normalization after most convolutions already has one. Call a channel's input zi, the batch mean μB, the batch variance σB2, the scale γ and the shift β.

Say it aloud

z-o equals gamma times z-i minus mu-B, over the square root of sigma-B squared plus epsilon, plus beta.

zo
z-o the channel's output.
γ
gamma the scale, how loud the channel is. This is the scaling factor.
zi
z-i the channel's input value.
μB
mu-B the mean of z-i over the batch.
σB2
sigma-B squared the variance over the batch; its square root is the spread.
ε
epsilon a tiny number that keeps the division safe.
β
beta the shift: the channel's resting level.
In plain words

Subtract mu-B from z-i, divide by the spread, multiply by gamma, add beta. With gamma near 0, z-o is about beta for every input.

With numbers

Inputs 2, 4, 6 standardize to −1.22, 0, 1.22. With gamma 1.17 and beta 0.5, z-o is −0.93, 0.5, 1.93. With gamma 0.10 it is 0.38, 0.5, 0.62: nearly flat, so a constant can replace it.

Prune by scaling factor

Five filters with the lecture's scaling factors. Each wave is one channel's output for the same input. Drag to prune the smallest factors.

2 of 5

Factors from the slide. The waves are illustrative: one shared signal, scaled by each factor, resting at 0.5.

The code, and a trap

pythonimport torch
def magnitude_mask(w, sparsity):
    """1 = keep, 0 = prune. Drops the smallest |w| in this one tensor."""
    k = int(sparsity * w.numel())
    thresh = w.abs().flatten().kthvalue(k).values   # k-th smallest size
    return (w.abs() > thresh).float()

def filter_l1_mask(conv_w, sparsity):                # conv_w: (c_o, c_i, kh, kw)
    score = conv_w.abs().sum(dim=(1, 2, 3))          # one L1 score per filter, (c_o,)
    keep = score.argsort(descending=True)[: int(len(score) * (1 - sparsity))]
    mask = torch.zeros(len(score)); mask[keep] = 1
    return mask.view(-1, 1, 1, 1).expand_as(conv_w)

Symptom: one threshold for the whole network leaves a layer 99% pruned, and the network collapses. Measure: print each layer's sparsity. Fix: give each layer its own ratio (Lecture 4).

Rows A = (4, 4, 4, 4) and B = (0, 0, 0, 12) compete for the single place left. Which one does each norm keep?

Chapter 9

Second-Order Scores: Ask the Loss Itself

Derive Optimal Brain Damage in three assumptions, and see a tiny weight that is more costly to lose than a big one

One metre east crosses a plateau; one metre north drops off a cliff. A step's cost depends on how the ground bends, not on its length.

Training ends at a valley floor of the loss. Pruning weight i moves it by δwi. Call the slope of the loss along weight i the gradient gi. Call the bend of the loss along weights i and j hij, the Hessian; hii is the curvature. A Taylor series adds them up:

Say it aloud

Delta L equals the sum of g-i delta w-i, plus half the sum of h-i-i delta w-i squared, plus half the sum over i not j of h-i-j delta w-i delta w-j, plus order delta W cubed.

δL
delta L the change in loss, L(W) − L(WP) in the slide's sign. Its size is the damage.
∑i, ∑i≠j
the sum over i; over i not j one term per weight; one term per pair of different weights.
gi
g-i the slope of the loss along weight i (first order).
δwi
delta w-i how far weight i moves.
hii
h-i-i the curvature along weight i (second order).
hij
h-i-j the cross term: how weights i and j bend the loss together.
O(‖δW‖3)
order delta W cubed third order and higher; small when the moves are small.
In plain words

For each weight, add slope g-i times the move and half of h-i-i times the move squared. Add the cross terms. The total predicts delta L.

With numbers

With made-up numbers: a weight of 0.1 with g = 0 and h = 100, moved to 0. The first term is 0; the second is (1/2) × 100 × 0.12 = 0.5. The loss rises about 0.5.

Three assumptions, three cuts

Optimal Brain Damage (LeCun et al., 1989) makes three assumptions:

  1. The loss is nearly quadratic. Drop the cubic remainder.
  2. Training has converged. At the valley floor every gi is about 0. Drop the first-order sum.
  3. The damages are independent. Removing one weight does not change another's cost. Drop the cross terms.

One term per weight is left. Zeroing weight i is a move of wi:

Say it aloud

Importance of w-i equals the size of delta L-i, which equals one half h-i-i times w-i squared.

importancewi
importance of w-i the score of weight i. Remove the smallest first.
|δLi|
the size of delta L-i how much the loss changes when you set weight i to zero.
hii
h-i-i the curvature along weight i, never negative at a valley floor.
wi2
w-i squared the squared move, the same square as in a magnitude score.
In plain words

Square the weight w-i, multiply by its curvature h-i-i, and halve. If every h-i-i were equal, this would rank weights like magnitude does.

With numbers

With made-up numbers: w1 = 0.1 with h11 = 100 scores 0.5. w2 = 3 with h22 = 0.01 scores (1/2) × 0.01 × 9 = 0.045. OBD prunes the big weight 2: 11 times less damage.

Which weight costs more to lose

The cross is your trained network. Pruning weight 1 moves you left; weight 2, down. A narrow ellipse is a steep direction.

0.1
3.0
100
0.01

Illustrative loss with no cross terms, L = (1/2)(h1d12 + h2d22), d the move. Curvatures run 0.01 to 100.

On the first preset, weight 1's dot is close to the cross but on a high contour. Weight 2's dot is far away, on a low one.

Why people still use magnitude

The slide's warning: the Hessian is difficult to compute. For 61 million weights it has about 3.7 × 1015 entries, some 15 petabytes. OBD needs only the diagonal, 244 MB, but each entry costs a second derivative.

pythonimport torch
w_star = torch.tensor([0.1, 3.0])              # trained weights (the loss minimum)
h = torch.tensor([100.0, 0.01])
L = lambda w: 0.5 * (h * (w - w_star) ** 2).sum()
H = torch.autograd.functional.hessian(L, w_star)   # (2, 2), here diag(100, 0.01)
saliency = 0.5 * H.diag() * w_star ** 2        # tensor([0.5000, 0.0450])
print(saliency.argsort())                      # tensor([1, 0]): prune weight 1 first, by index

The argsort lists index 1, the weight 3.0, first: the cheaper one to prune.

The failure: the assumptions break

Symptom: OBD ranks well at the end of training and badly in the middle. Measure: check the gradient. If it is not near zero, the first-order term matters. Fix: train to convergence first, or use a first-order score (Molchanov et al.).

A trained network has weight a = 0.2 with curvature h = 50, and weight b = 2 with curvature h = 0.05. Which does Optimal Brain Damage prune first, and why?

Chapter 10

Scoring Neurons: Count the Zeros, or Rebuild the Output

Choose which channels to cut by watching what they output, and fit what is left so the layer's answer barely moves

Now score neurons by what they output. Neuron pruning is coarse-grained weight pruning: a neuron is one row of W in a linear layer, and a channel in a convolution.

Percentage of zeros

ReLU outputs many exact zeros. A channel that is nearly always zero adds almost nothing. The Average Percentage of Zeros (APoZ, Hu et al., 2017) counts channel c's zeros n0 over a batch of B inputs on an H by W output map.

Say it aloud

APoZ of c equals n-zero over B times H times W.

APoZc
APoZ of c the share of channel c's outputs that are zero, from 0 to 1.
n0
n-zero the count of zeros in channel c over the whole batch.
B
B the batch size: how many inputs you measure.
H × W
H times W the output map's height times width.
In plain words

Run a batch. Divide channel c's zero count n-zero by its number of values, B times H times W. A larger APoZ means a less important channel.

With numbers

From the slide: B = 2 on a 4 by 4 map gives 32 values. Zeros 11, 12 and 14 give 0.34, 0.375 and 0.44. Channel 2 goes.

Count zeros after ReLU

Each grid is one channel's output for the first input; hollow cells are zeros. The bar is APoZ over all inputs.

2

Illustrative: pre-ReLU means 0.6, 0.1, −0.5, 0.3 with spread 1, so long-run APoZ is 0.27, 0.46, 0.69, 0.38.

With 2 inputs the ranking wobbles. With 64 inputs, channel 2 wins every time.

Regression-based pruning

Ask an easier question: after the cut, does the layer give nearly the same output? Call the input X (b rows), its columns for channel c Xc, their weights Wc, and the output Z = XWT. Channel c gets a switch βc; at most Nc stay on.

Say it aloud

Arg min over W and beta of the Frobenius norm of Z minus Z-hat, squared, where Z-hat is the sum over c of beta-c X-c W-c transpose, with at most N-c non-zero betas.

arg minW, β
arg min over W and beta pick the weights and switches that make the miss smallest.
‖·‖F2
Frobenius norm, squared square every entry of a matrix and add them: the Frobenius norm is the root of that sum.
Ẑ
Z-hat the output of the pruned layer.
∑c
the sum over c one term per input channel, from c = 0 to c-i minus 1.
βc
beta-c the switch for channel c. Zero means pruned.
Xc WcT
X-c W-c transpose channel c's part of the output.
‖β‖0 ≤ Nc
the L-zero norm of beta is at most N-c at most N-c channels stay.
In plain words

Fix W and choose the non-zero beta-c, to pick channels. Then fix beta and refit W. Repeat. The weights change too.

With numbers

In the device below, 3 of 6 channels stay. Picking by weight size misses Z by 27%, refitting gives 24%, and regression gives 7%.

Rebuild the layer's output

A layer with 6 input channels and 3 outputs. Pick how many stay.

3 of 6

Illustrative: 80 random inputs; channel 3 copies channel 0, channel 4 mixes 1 and 2, channel 5 is weak. Regression tries every set and refits by least squares; He et al. (ICCV 2017) alternate instead.

Regression picks channels 0, 1 and 2, which can rebuild 3 and 4. A channel with small weights can be the one nothing replaces.

pythondef apoz(act):                                # act: (B, C, H, W), after ReLU
    return (act == 0).float().mean(dim=(0, 2, 3))   # (C,) the share of zeros per channel

def regression_refit(X, Z, keep):             # X: (b, c_i), Z: (b, c_o), keep: indices
    Xp = X[:, keep]                           # (b, k)
    Wp = torch.linalg.lstsq(Xp, Z).solution   # (k, c_o) minimises ||Z - Xp Wp||_F
    return Wp

The failure: a score from too little data

Symptom: you prune by APoZ, and a channel that mattered disappears. Measure: compute APoZ again on another batch. If the ranking changes, the first was noise. Fix: measure on a large, varied set of inputs.

Channel 0 has APoZ 0.34, channel 1 has 0.375, channel 2 has 0.44. You must prune one channel by APoZ. Which, and why?

Chapter 11

The Field Guide to Pruning, Part I

Keep the numbers, the terms, the checklist and the code, and know where Part II picks up

Pruning is four choices: a granularity, a criterion, a ratio, and a finetune. Scattered zeros compress best but need special hardware. Regular patterns, like 2:4 and whole channels, give up some accuracy to run fast on common chips.

Numbers to remember

FactValueWhere it came from
DRAM fetch against float MULT640 pJ against 3.7 pJ, about 173×Horowitz table, Chapter 0
Papers on pruningabout 3,000 a year by 2022Publication chart, Chapter 1
Synapses per neuron in a human2,500 at birth, 15,000 at 2 to 4 years, 7,000 as an adultBrain slide, Chapter 1
AlexNet61 M to 6.7 M parameters (9×), MACs 3×Han et al. 2015, Chapter 3
VGG-16138 M to 10.3 M (12×), MACs 5×Chapter 3
GoogleNet7 M to 2.0 M (3.5×), MACs 5×Chapter 3
ResNet5026 M to 7.47 M (3.4×), MACs 6.3×Chapter 3
SqueezeNet1 M to 0.38 M (3.2×), MACs 3.5×Chapter 3
2:4 sparsity50% sparse, up to 2× faster, 1.5× measured on BERTA100 slide, Chapters 3 and 6
Compressed 2:4 group, 16-bit weights36 bits against 64 (56%)Our arithmetic, Chapter 6
Channel cut on every layer by sMACs about (1 − s)2Our derivation, Chapter 7
OBD importance(1/2) hii wi2LeCun et al. 1989, Chapter 9
APoZ of one channelzeros / (batch × height × width)Hu et al. 2017, Chapter 10

The terms

TermPlain meaning
Synapse, neuronA weight is a connection. A neuron is a unit that holds many.
Sparsity, L0 normThe share of zeros. The L0 norm counts the non-zeros.
GranularityThe size and shape of the piece you remove.
Structured, unstructuredWhole groups removed, or single weights removed.
N:M sparsityN weights kept in every group of M. 2:4 is the case with hardware support.
CriterionThe score that ranks what to remove.
Pruning ratioThe share removed, for the network or one layer.
FinetuneTrain the survivors while the mask holds the zeros.

The pruning checklist

The core as code

pythonimport torch

def mask_fine(w, sparsity):                        # any shape; 0 < sparsity < 1
    k = max(1, int(sparsity * w.numel()))
    t = w.abs().flatten().kthvalue(k).values       # k-th smallest size
    return (w.abs() > t).float()

def mask_nm(w, n=2, m=4):                          # w: (rows, cols), cols divisible by m
    g = w.abs().reshape(-1, m)
    idx = g.topk(n, dim=1).indices                 # n biggest in each group
    return torch.zeros_like(g).scatter_(1, idx, 1.0).reshape(w.shape)

def mask_filter(w, sparsity, p=1):                 # w: (c_o, c_i, kh, kw)
    score = w.abs().pow(p).sum(dim=(1, 2, 3))      # one L_p score per filter, (c_o,)
    keep = score.argsort(descending=True)[: round(len(score) * (1 - sparsity))]
    m = torch.zeros(len(score)); m[keep] = 1
    return m.view(-1, 1, 1, 1).expand_as(w)

def apoz(act):                                     # act: (B, C, H, W), after ReLU
    return (act == 0).float().mean(dim=(0, 2, 3))  # (C,) share of zeros per channel

def obd_saliency(w, h_diag):                       # h_diag: curvature of each weight
    return 0.5 * h_diag * w ** 2                   # smallest values are pruned first

# Then: apply the mask, finetune with p.mul_(mask) after every step (Chapter 2),
# and repeat with a slightly higher sparsity.

Check them on the lesson's examples. On [[3, −2], [1, −5]] at 50%, mask_fine keeps 3 and −5. On the group (0.9, −0.1, 0.4, −0.7), mask_nm keeps 0.9 and −0.7. On weights (0.1, 3.0) with curvatures (100, 0.01), obd_saliency gives (0.5, 0.045).

Where this sits

This lecture answers three of the five questions: what pruning is, in what pattern, and which weights. Lecture 4 covers the ratio for each layer, how to finetune the pruned network, automated ways to find the ratios, and system support for each granularity. Quantization comes next, in Lecture 5.

Keep going

The takeaway. Memory is the bill, so fewer weights saves energy. Choose the pattern first, because the pattern decides whether a chip can use the zeros. Then choose a score, a ratio per layer, and finetune with the mask held fixed.
You must cut the latency of a vision model on a plain dense GPU with no sparse hardware. Which pruning choice is most likely to work?

Credit and sources

This lesson follows Lecture 3 of MIT 6.5940, TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Find the lecture and its slides on the course site. Every idea is re-taught here in our own words and devices. We label toy numbers illustrative. Papers the lecture cites:

Now press Teach and explain, from memory, why a 90% sparse model may not run any faster, and what pattern fixes that. Then go back to the layer at the top and try all three patterns once more.

MIT 6.5940 Lecture 3: Pruning and Sparsity (Part I)
The course site and slides · Back to Lecture 2 · On to Lecture 4 · Back to Gleams