TExcelTAD

Pruning: Removing Weights

Trained networks are over-parameterised: many weights end up close to zero and contribute almost nothing. Pruning removes them. Done well, it can delete half or more of a network's weights with no measurable loss. But "fewer weights" and "faster model" are not the same thing. Whether pruning saves time and memory depends on which weights you remove: scattered single weights (unstructured pruning) or whole neurons, channels and attention heads (structured pruning). This lesson measures both on a small network, fine-tunes after pruning, and counts the bytes a sparse matrix really needs.

Masks and sparsity

Pruning multiplies the weights by a binary mask MM of the same shape: W′=M⊙WW' = M \odot W. The sparsity is the fraction of zeros in MM. The simplest and still very strong criterion is magnitude: keep a weight if its absolute value exceeds a threshold τ\tau,

Mij=1[ ∣Wij∣>τ ],τ=the s-quantile of ∣W∣  ⇒  sparsity≈sM_{ij} = \mathbb{1}\big[\,|W_{ij}| > \tau\,\big], \qquad \tau = \text{the } s\text{-quantile of } |W| \;\Rightarrow\; \text{sparsity} \approx s

The quantile can be taken per layer (every layer gets the same sparsity) or over all layers together (global pruning: layers with many small weights lose more of them). Removing weight ww changes the loss by about 12Hwww2\tfrac{1}{2} H_{ww} w^2 at a minimum (second-order Taylor; the first-order term vanishes there), so small ∣w∣|w| is a reasonable proxy for small damage when the curvatures HwwH_{ww} are similar.

Structured pruning removes groups. For hidden unit jj of a dense layer, a natural score is the product of the norms of its incoming column and its outgoing row,

scorej=∥W:,j(1)∥2⋅∥Wj,:(2)∥2\text{score}_j = \lVert W^{(1)}_{:,j} \rVert_2 \cdot \lVert W^{(2)}_{j,:} \rVert_2

and removing unit jj deletes the column, the row and the bias: the matrices become genuinely smaller.

Sparsity against accuracy, from scratch

A network with one hidden layer of 128 units, trained on the 8 x 8 digit images (1,257 training, 540 test images), has 9,472 weights. The same fraction of weights is removed in two ways: globally by magnitude, and as whole hidden units (removing 50 % of the weights = removing 64 of the 128 units). No retraining yet.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(128,), max_iter=600, random_state=0).fit(X_tr, y_tr)
(W0, W1), (b0, b1) = mlp.coefs_, mlp.intercepts_

def acc(W0, b0, W1):
    h = np.maximum(X_te @ W0 + b0, 0.0)
    return ((h @ W1 + b1).argmax(1) == y_te).mean()

def magnitude_prune(Ws, sparsity):
    """Global unstructured pruning: zero the given fraction of all weights, smallest |w| first."""
    allw = np.concatenate([np.abs(W).ravel() for W in Ws])
    thr = np.quantile(allw, sparsity)
    return [np.where(np.abs(W) > thr, W, 0.0) for W in Ws]

def neuron_prune(fraction):
    """Structured pruning: remove whole hidden units with the smallest weight norm (in and out)."""
    score = np.linalg.norm(W0, axis=0) * np.linalg.norm(W1, axis=1)
    keep = np.sort(np.argsort(score)[int(round(fraction * len(score))):])
    return W0[:, keep], b0[keep], W1[keep, :]

n_weights = W0.size + W1.size
print(f"dense: {n_weights} weights, test accuracy {acc(W0, b0, W1):.3f} (n = {len(y_te)})")
print("removed | unstructured acc | structured: units left  acc")
for frac in (0.5, 0.7, 0.8, 0.9, 0.95, 0.98):
    P0, P1 = magnitude_prune([W0, W1], frac)
    S0, sb0, S1 = neuron_prune(frac)
    print(f"  {frac:4.0%}  |       {acc(P0, b0, P1):.3f}      |            {S0.shape[1]:3d}      {acc(S0, sb0, S1):.3f}")
dense: 9472 weights, test accuracy 0.981 (n = 540)
removed | unstructured acc | structured: units left  acc
   50%  |       0.987      |             64      0.946
   70%  |       0.957      |             38      0.815
   80%  |       0.913      |             26      0.607
   90%  |       0.491      |             13      0.572
   95%  |       0.356      |              6      0.261
   98%  |       0.111      |              3      0.100

Unstructured pruning is remarkably harmless at first: with half of the weights gone the accuracy is 0.987 (the dense model has 0.981; the difference is 3 of 540 images, noise). At 70 % it is still 0.957, and then it falls off a cliff: 0.913 at 80 %, 0.491 at 90 %. Structured pruning hurts much earlier: removing half of the units gives 0.946, 70 % gives 0.815. That is the general pattern: at equal parameter count, scattered zeros cost less accuracy than missing neurons, because unstructured pruning can keep the important weights of every unit.

Fine-tuning after pruning

The weights that remain were trained to work together with the ones that were removed. A few epochs of training with the mask held fixed (the pruned weights are set back to zero after every update) let them compensate. Two schedules with the same budget of 20 epochs: one-shot (prune to 95 % at once, then fine-tune for 20 epochs) and gradual (prune to 50, 70, 80, 90 and 95 %, fine-tuning 4 epochs after each step).

python · try it yourself
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.exceptions import ConvergenceWarning
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

warnings.filterwarnings("ignore", category=ConvergenceWarning)
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

def train():
    return MLPClassifier(hidden_layer_sizes=(128,), max_iter=600, random_state=0).fit(X_tr, y_tr)

def prune_to(mlp, sparsity, masks=None):
    """Global magnitude pruning; already-pruned weights stay pruned."""
    allw = np.concatenate([np.abs(W).ravel() for W in mlp.coefs_])
    thr = np.quantile(allw, sparsity)
    masks = [np.abs(W) > thr for W in mlp.coefs_]
    for W, m in zip(mlp.coefs_, masks):
        W *= m
    return masks

def fine_tune(mlp, masks, epochs):
    for _ in range(epochs):
        mlp.partial_fit(X_tr, y_tr)                  # one pass of Adam over the training set ...
        for W, m in zip(mlp.coefs_, masks):
            W *= m                                   # ... then put the pruned weights back to zero

def sparsity(mlp):
    return np.mean(np.concatenate([(W == 0).ravel() for W in mlp.coefs_]))

target = 0.95
mlp = train()
print(f"dense model: test accuracy {mlp.score(X_te, y_te):.3f}")
masks = prune_to(mlp, target)
print(f"one-shot to {sparsity(mlp):.1%} zeros: accuracy {mlp.score(X_te, y_te):.3f}")
fine_tune(mlp, masks, 20)
print(f"  + 20 epochs fine-tuning: accuracy {mlp.score(X_te, y_te):.3f} (zeros {sparsity(mlp):.1%})")

mlp = train()
for s in (0.5, 0.7, 0.8, 0.9, 0.95):                 # gradual: prune a little, fine-tune, repeat (20 epochs in all)
    masks = prune_to(mlp, s)
    fine_tune(mlp, masks, 4)
    print(f"gradual step to {s:.0%} zeros, 4 epochs: accuracy {mlp.score(X_te, y_te):.3f}")
dense model: test accuracy 0.981
one-shot to 95.0% zeros: accuracy 0.356
  + 20 epochs fine-tuning: accuracy 0.857 (zeros 95.0%)
gradual step to 50% zeros, 4 epochs: accuracy 0.981
gradual step to 70% zeros, 4 epochs: accuracy 0.981
gradual step to 80% zeros, 4 epochs: accuracy 0.983
gradual step to 90% zeros, 4 epochs: accuracy 0.917
gradual step to 95% zeros, 4 epochs: accuracy 0.709

One-shot pruning to 95 % leaves 0.356 accuracy, and 20 epochs of fine-tuning bring it back to 0.857 with the same 95 % zeros. The gradual schedule is free up to 80 % (accuracy 0.981 to 0.983 after each step) but ends at 0.709 at 95 %, because it had only 4 epochs at the final sparsity. Here, with a fixed budget, one-shot plus fine-tuning won. Gradual schedules (for example the cubic schedule of Zhu and Gupta, 2017) pay off when pruning is spread over a long training run, so that the network adapts at every step. The lesson that holds in both cases: never judge a pruned model before fine-tuning it, and compare schedules at equal training cost.

Why unstructured sparsity rarely makes a model faster

A dense matrix product does the same work whatever the values are: multiplying by zero takes as long as multiplying by 0.3. To skip zeros, the matrix must be stored in a sparse format. The common one, CSR (compressed sparse row), stores every non-zero value (4 bytes for float32), its column index (4 bytes for int32) and one offset per row. For a matrix with rr rows and nnz\text{nnz} non-zeros:

bytesCSR=4 nnz+4 nnz+4 (r+1)againstbytesdense=4 r c\text{bytes}_{\text{CSR}} = 4\,\text{nnz} + 4\,\text{nnz} + 4\,(r + 1) \quad\text{against}\quad \text{bytes}_{\text{dense}} = 4\,r\,c

so CSR is smaller only when fewer than about half of the entries are non-zero. And memory is not the end of it: sparse kernels jump through memory following the indices, so they need roughly 90 % sparsity or more before they beat a well-tuned dense kernel on a CPU, and on GPUs the gap is larger.

python · try it yourself
import numpy as np
from scipy import sparse

rng = np.random.default_rng(0)
rows, cols = 1024, 1024
W = rng.normal(0, 0.05, (rows, cols)).astype(np.float32)
dense_bytes = W.nbytes
print(f"dense {rows}x{cols} float32: {dense_bytes / 2**20:.2f} MiB, {2 * rows * cols / 1e6:.1f} MFLOP per input vector")
print("zeros | CSR size (MiB)  vs dense | nonzero MFLOP | same count as whole rows: dense shape -> MiB")
for s in (0.5, 0.7, 0.9, 0.95):
    Wp = np.where(np.abs(W) > np.quantile(np.abs(W), s), W, 0).astype(np.float32)
    csr = sparse.csr_matrix(Wp)
    csr_bytes = csr.data.nbytes + csr.indices.nbytes + csr.indptr.nbytes
    kept_rows = int(round(rows * (1 - s)))
    print(f" {s:4.0%} |     {csr_bytes / 2**20:5.2f}       {csr_bytes / dense_bytes:5.2f}x |      {2 * csr.nnz / 1e6:5.2f}    "
          f"|   {kept_rows:4d} x {cols} -> {kept_rows * cols * 4 / 2**20:.2f}")
dense 1024x1024 float32: 4.00 MiB, 2.1 MFLOP per input vector
zeros | CSR size (MiB)  vs dense | nonzero MFLOP | same count as whole rows: dense shape -> MiB
  50% |      4.00        1.00x |       1.05    |    512 x 1024 -> 2.00
  70% |      2.40        0.60x |       0.63    |    307 x 1024 -> 1.20
  90% |      0.80        0.20x |       0.21    |    102 x 1024 -> 0.40
  95% |      0.40        0.10x |       0.10    |     51 x 1024 -> 0.20

The measurement with SciPy agrees with the formula: at 50 % sparsity, the CSR matrix takes 4.00 MiB, exactly as much as the dense one (1.00x), while doing half the multiply-adds on paper (1.05 instead of 2.1 MFLOP). At 90 % it is 0.80 MiB (0.20x). Structured pruning that removes the same number of weights as whole rows gives a plain dense matrix (102 x 1024 at 90 %, 0.40 MiB) that every BLAS library, GPU and NPU runs at full speed with no index overhead.

Hardware is meeting sparsity half-way: NVIDIA's Ampere and later GPUs accelerate 2:4 semi-structured sparsity (in every group of 4 consecutive weights, 2 are zero), which gives up to about twice the throughput of dense matrix products for those layers. Outside such patterns, the practical uses of unstructured sparsity are smaller files (with compression) and research; to speed up a serving model, prune structure, or distil into a smaller dense model, or quantize.

PyTorch: torch.nn.utils.prune

PyTorch implements pruning with masks. A recorded example (PyTorch 2.14.1, run in the course's Docker image):

python · try it yourself
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
fc1, fc2 = model[0], model[2]

prune.l1_unstructured(fc1, name="weight", amount=0.5)          # 50 % smallest |w| in this layer
print("fc1 parameters:", [n for n, _ in fc1.named_parameters()])
print("fc1 buffers:   ", [n for n, _ in fc1.named_buffers()])
print(f"fc1 zeros: {(fc1.weight == 0).float().mean().item():.1%}, shape still {tuple(fc1.weight.shape)}")

prune.ln_structured(fc2, name="weight", amount=0.3, n=2, dim=0)  # 30 % of output rows, by L2 norm
zero_rows = int((fc2.weight.abs().sum(dim=1) == 0).sum())
print(f"fc2 rows that are all zero: {zero_rows} of {fc2.weight.shape[0]}")

for m in (fc1, fc2):
    prune.remove(m, "weight")                                     # make the zeros permanent, drop the mask
print("fc1 parameters after remove:", [n for n, _ in fc1.named_parameters()])

model2 = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
prune.global_unstructured([(model2[0], "weight"), (model2[2], "weight")],
                          pruning_method=prune.L1Unstructured, amount=0.8)
for i in (0, 2):
    print(f"global 80 %: layer {i} zeros {(model2[i].weight == 0).float().mean().item():.1%}")
fc1 parameters: ['bias', 'weight_orig']
fc1 buffers:    ['weight_mask']
fc1 zeros: 50.0%, shape still (32, 64)
fc2 rows that are all zero: 3 of 10
fc1 parameters after remove: ['bias', 'weight']
global 80 %: layer 0 zeros 82.9%
global 80 %: layer 2 zeros 61.3%

l1_unstructured replaces the parameter weight with a parameter weight_orig and a buffer weight_mask; the layer's weight is recomputed as their product before each forward pass, so gradients flow only to the kept weights and fine-tuning keeps the zeros automatically. ln_structured with dim=0 zeroes whole output rows (3 of the 10 rows of fc2, by L2 norm). prune.remove makes the zeros permanent and restores a plain weight parameter. Note what does not change: the weight's shape is still (32, 64), so the layer runs at exactly the dense speed. To actually shrink a layer you build a smaller one and copy the kept rows into it (libraries such as torch-pruning automate this across connected layers). global_unstructured with 80 % pruned 82.9 % of the first layer and 61.3 % of the second: the global threshold takes more from the layer with more small weights.

Pitfalls

  • Reporting sparsity as speed. "90 % sparse" says nothing about latency. Measure on the target runtime; expect speed-ups only from structured pruning, 2:4 patterns on supporting GPUs, or dedicated sparse runtimes.
  • Evaluating before fine-tuning, or comparing a fine-tuned pruned model with an untuned dense one. Give the dense baseline the same extra epochs.
  • Pruning the wrong layers. First and last layers and small layers are usually the most sensitive. Prune layer by layer and measure the sensitivity of each before choosing per-layer sparsities.
  • Forgetting prune.remove before exporting: the saved model then carries weight_orig plus a mask, twice the size of the dense model.

Practice

  1. A 4096 x 4096 float32 matrix is pruned to 75 % sparsity and stored in CSR. Compute its size and compare it with dense.
Answer

nnz=0.25⋅40962=4,194,304\text{nnz} = 0.25 \cdot 4096^2 = 4{,}194{,}304. CSR: 8⋅4,194,304+4⋅4097≈33.68 \cdot 4{,}194{,}304 + 4 \cdot 4097 \approx 33.6 MB (32.0 MiB); dense: 4⋅40962≈67.14 \cdot 4096^2 \approx 67.1 MB (64 MiB). Half the size, but not 4 times smaller.

  1. In the first example, replace global pruning by per-layer pruning (the same quantile in each layer). What do you expect at 90 %, and why?
Answer

Per-layer pruning removes 90 % of the small output layer (1,280 weights) as well as of the large first layer. The output layer has few redundant weights, so accuracy is likely to drop further than with global pruning, which takes more from the first layer. Run it to check.

  1. Why does the gradient of a masked weight stay zero during fine-tuning with torch.nn.utils.prune?
Answer

The forward pass uses weight = weight_orig * weight_mask. The gradient with respect to weight_orig is the gradient with respect to weight times the mask, which is 0 where the mask is 0, so those entries never change.

Test yourself

At the same number of removed weights, which kind of pruning kept more accuracy without fine-tuning?

  1. Unstructured magnitude pruning
  2. Removing whole hidden units
  3. They were identical
  4. Neither changed the accuracy

Below what fraction of non-zeros is a float32 CSR matrix smaller than the dense one?

  1. About 50 %
  2. About 90 %
  3. About 10 %
  4. Any sparsity makes it smaller

Why does 90 % unstructured sparsity usually not make inference 10 times faster on a GPU?

  1. Dense kernels do the same work regardless of zeros, and sparse kernels pay for irregular memory access
  2. GPUs cannot store zeros
  3. Pruning increases the number of layers
  4. Sparse matrices always use float64

After prune.l1_unstructured(layer, 'weight', 0.5) in PyTorch, what does the layer hold?

  1. A parameter weight_orig and a buffer weight_mask; weight is their product
  2. A smaller weight matrix
  3. A sparse CSR tensor
  4. Only the mask