Part 09›
✎

03. Pruning and Sparsity#

Level: Practitioner · Reading time: 20 min · Exercise: 60 min Prerequisites: Neural Network Basics for Efficiency

In one sentence: After this chapter you can remove a chosen share of a network's weights with a method you can justify, recover the accuracy with fine-tuning, and predict whether the result will run faster on your hardware.

Why this matters#

Your model file is too large for a phone app. A blog post says 90% of the weights are redundant. You zero out the 90% with the smallest values and save the file. Two problems: the file is the same size, and inference is just as slow.

Zeros stored as ordinary floating-point numbers take the same bytes as any other number, and a regular matrix-multiply kernel multiplies every one of them. Pruning worked as an idea and did nothing as an engineering change. This chapter is about closing that gap: which weights to remove, how to keep the quality, and how to remove them so the hardware notices.

The core idea#

Pruning sets weights to zero and stops storing or computing them. Sparsity is the fraction of zeros. A dense model has few zeros; a sparse model has many.

Song Han formulates it as an optimization (Lecture 3, 4:00): minimize the loss of the pruned model, subject to keeping no more than a target number of non-zero weights.

The analogy is dead-code elimination in a compiler: find what makes no difference and delete it. The analogy breaks on importance. A line of code either runs or it does not. A weight's importance is a matter of degree, and many small weights can matter together, which is why aggressive pruning always needs retraining afterwards.

Four decisions make up a pruning method:

  1. Granularity: what unit you remove.
  2. Criterion: which units count as unimportant.
  3. Ratio: how much to remove from each layer.
  4. Fine-tuning: how to recover.

How it works, step by step#

Step 1: Choose the granularity#

Granularity What is removed Effect on commodity hardware Quality at equal sparsity
Fine-grained (unstructured) single weights, anywhere none by default: needs sparse kernels and indices best
Pattern-based (for example 2:4) at most 2 non-zeros in every block of 4 speeds up on hardware that supports the pattern good
Vector or kernel a row of one filter, or a whole filter some: smaller tensors medium
Channel or neuron (structural) a whole output channel or neuron always: matrices get smaller lower
Layer whole layers always: fewer sequential steps depends on the layer

Han's summary of the trade: fine-grained pruning is the most flexible because it can remove any weight in any location, and it is the most irregular, so it is hard to accelerate (Lecture 4, 2:00).

Worked numbers for a 4,096 × 4,096 weight block in 16-bit, which is 16.8 million weights and 33.6 MB:

The lesson: scattered pruning pays off at high sparsity or on special hardware. Structural pruning pays off immediately.

Step 2: Choose the criterion#

Han's own position on which is best: it depends on the data set and the network, and it has to be tried experimentally (Lecture 3, 32:00).

Removing a neuron is a coarse version of weight pruning. In a linear layer it deletes one row of the weight matrix. In a convolution it deletes the whole kernel of one output channel (Lecture 3, 34:00).

Step 3: Choose the ratio for each layer#

Layers tolerate different amounts of pruning. Two ways to set the ratios:

Han considers this decision so important that he tells the class the per-layer ratio is "super crucial compared with uniform pruning ratio" (Lecture 3, 56:00).

Step 4: Fine-tune, a little at a time#

  1. Prune to the chosen ratios.
  2. Fine-tune on the training data, updating only the surviving weights.
  3. Evaluate. Not at the target yet? Prune a little more and repeat.

Figure 1. Iterative pruning: the loop stops only when the pruned model meets its target.

flowchart LR
    P["Prune to the chosen ratios"] --> F["Fine-tune surviving weights"]
    F --> E["Evaluate accuracy"]
    E -->|"target not reached"| P
    E -->|"target reached"| S["Keep the model"]

Each turn removes only a little, which lets the final sparsity exceed what one large cut allows.

One round of pruning plus fine-tuning is one iteration (Han's Lecture 4, slides 46 to 53). For aggressive targets, go in steps. Han reports that gradual pruning beats pruning 70% in one shot and then fine-tuning everything (Lecture 4, 26:00). The same example lifted AlexNet's pruning ratio from 5× to 9×. He also adds regularization during fine-tuning, L1 or L2, to push unimportant weights toward zero; in his experience there is little to choose between the two (his 2015 paper used L2, Network Slimming used L1), so compare them (26:00).

Step 5: Match the hardware#

His summary of the lesson from this work: "First principle of efficient AI is to be lazy" (Lecture 4, 46:00). In his list: avoid redundant computation, quickly reject work (if a value is zero, do not compute on it), use fewer bits, or delay the work. He names one opening per domain: only the edited region when editing an image, token sparsity for transformers, temporal redundancy in video, and point clouds, which are naturally sparse.

The lottery ticket hypothesis#

This idea is not covered in the lectures; it is included because you will meet it. The lottery ticket hypothesis (Frankle and Carbin, 2019) says that a dense network contains a small subnetwork that, trained from its original initial values, reaches the accuracy of the full network. The test: train, prune, reset the surviving weights to their initial values, and train the subnetwork alone. For larger networks the reset has to go back to an early iteration rather than to the start.

It is useful as an insight: initialization and connectivity matter together. It is rarely used as a production compression method, because finding the tickets costs several full training runs.

Worked example#

One linear layer, pruned three ways, with NumPy. The measure is how much the layer's output changes. It is a stand-in for accuracy: no dataset, no training loop.

import numpy as np

rng = np.random.default_rng(0)
# One linear layer: 128 inputs, 64 outputs. Neurons have very different scales.
W = rng.standard_normal((64, 128)) * np.linspace(0.1, 2.0, 64)[:, None]
X = rng.standard_normal((1000, 128))      # 1,000 calibration inputs
Y = X @ W.T                               # what the dense layer outputs

def error(W_pruned):
    """Relative change of the layer's output (0 means unchanged)."""
    return np.linalg.norm(X @ W_pruned.T - Y) / np.linalg.norm(Y)

def magnitude(W, keep):
    """Fine-grained: keep the `keep` fraction of weights with the largest |w|."""
    threshold = np.quantile(np.abs(W), 1 - keep)
    return W * (np.abs(W) >= threshold)

def random_keep(W, keep):
    """Baseline: keep a random `keep` fraction of weights."""
    return W * (rng.random(W.shape) < keep)

def by_neuron(W, keep):
    """Structural: keep the `keep` fraction of neurons with the largest L1 norm."""
    norms = np.abs(W).sum(axis=1)
    alive = norms >= np.quantile(norms, 1 - keep)
    return W * alive[:, None]

for keep in (0.5, 0.2, 0.05):
    print(f"keep {keep:>4}: magnitude {error(magnitude(W, keep)):.2f}  "
          f"random {error(random_keep(W, keep)):.2f}  "
          f"neurons {error(by_neuron(W, keep)):.2f}")

def fine_tune(W_pruned, steps=50, lr=0.5):
    """Gradient descent on the output error; only surviving weights move."""
    mask = W_pruned != 0
    W_ft = W_pruned.copy()
    for _ in range(steps):
        grad = 2 * (X @ W_ft.T - Y).T @ X / len(X)   # mean squared error
        W_ft -= lr * grad * mask
    return W_ft

W20 = magnitude(W, 0.2)
print(f"magnitude 0.2: {error(W20):.2f} -> {error(fine_tune(W20)):.2f} after fine-tuning")

What to observe:

What the practitioners say#

Pitfalls#

  1. Pruning and expecting a speed-up on a GPU. Fix: use structural pruning or a hardware-supported pattern, or accept storage savings only.
  2. Using one ratio for every layer. Fix: run a sensitivity analysis first.
  3. Skipping fine-tuning above roughly 10 to 20% sparsity. Fix: fine-tune after each pruning step and evaluate against your baseline.
  4. Pruning the first and last layers as hard as the middle. Fix: these are usually the most sensitive; keep their ratios low.
  5. Reporting accuracy on the training set. Fix: evaluate on held-out data with your eval harness.
  6. Forgetting activation sparsity. A pruned weight matrix can make the inputs of the next layer sparser, which changes where its time goes. Fix: profile the whole model, not one layer.

Try it#

Prune a small classifier three ways and report. In PyTorch, prune as in the NumPy example: build a mask, multiply the weight by it, and keep it during fine-tuning so that only surviving weights move.

  1. Train a small model on a built-in dataset (for example handwritten digits).
  2. Apply fine-grained magnitude pruning at 25%, 50% and 75%, uniformly.
  3. Repeat with structural pruning (drop whole neurons by L1 norm).
  4. Fine-tune each pruned model for the same number of steps.

You are done when you have a table with six rows (three ratios, two granularities) and four columns: accuracy before fine-tuning, accuracy after fine-tuning, bytes on disk, and measured latency. The last column must come from a timer, not from the MAC count.

Stretch: replace the uniform ratio with one from a per-layer sensitivity analysis and show that it beats the uniform result at the same total sparsity.

Key takeaways#

Self-check#

  1. A model has 50% of its weights set to zero, scattered at random positions. Stored as 16-bit floats, how large is the file compared with before?
  2. Why does removing whole output channels speed up inference when removing half of the weights at random does not?
  3. Layer A tolerates 90% pruning and layer B only 30%. Which step uses that fact, and how?
  4. What is the role of the Hessian in second-order pruning, and why is it approximated?
  5. Why is 2:4 sparsity more useful than unstructured sparsity on a GPU?
  6. You prune a model in one pass to 70% and fine-tune. Han recommends what instead?
Show answers 1. The same size. A zero takes as many bytes as any other 16-bit number. 2. The weight matrices and the activation tensors shrink, so every operation on them is smaller. Scattered zeros leave the matrix shapes unchanged. 3. Step 3, the per-layer ratio: a sensitivity analysis gives each layer its own ratio, 90% for A and 30% for B. 4. It measures how much the loss rises when a weight changes. Computing it is expensive, so methods estimate it. 5. Because tensor cores on hardware that supports the pattern can skip the known empty slots, while arbitrary zeros cannot be skipped. 6. Iterate: prune a little, fine-tune, and repeat.

Sources#

Next#

→ Quantization, the second half of compression: instead of removing weights, store each one in fewer bits.