AI Logic

Model Compression

Pruning

Updated:

How pruning works. The left side shows the flow of training normally and then repeating "assign importance scores, remove the lowest-scoring items, fine-tune" N times. The right side shows the difference in the unit removed: removing individual weights makes the matrix sparse, while removing channels removes the output of layer i and the input of layer i+1 together, making the matrix narrower.

Background and Overview

Pruning makes a model smaller and lighter by removing weights or structures from a trained network that have little effect on accuracy. Deep learning models usually have far more parameters than the task requires. Trimming this excess reduces storage memory, inference compute, and power consumption.

An everyday analogy is pruning a garden tree. Cutting off overgrown branches that contribute little to fruit or flowers does not harm the tree; if anything, it gives the tree a better shape. In a network as well, setting small-valued weights to 0 often barely changes the output.

The idea of pruning dates back to the late 1980s; according to the survey by Blalock et al. (2020), pruning by weight magnitude goes back to Janowsky (1989). It became widely known in deep learning through Han et al. (2015), who showed that the parameters of AlexNet could be reduced from 61 million to 6.7 million (9×) and those of VGG-16 from 138 million to 10.3 million (13×) without losing accuracy on ImageNet.

Pruning is one of the main ways to shrink a model, alongside quantization, knowledge distillation, and low-rank factorization. Many methods grew out of this idea, including Deep Compression, which combines it with quantization; filter pruning, which removes whole filters; Network Slimming, which selects channels to remove during training; and the lottery ticket hypothesis, which studies the properties of the small networks found by pruning.

Theory (Masks and the Basic Procedure)

Blalock et al. (2020) define pruning in terms of a mask. Pruning takes a model f(x;W)f(x; W) and produces the following model.

f(x; M⊙W′),M∈{0,1}∣W′∣f(x;\ M \odot W'), \qquad M \in \{0, 1\}^{|W'|}

MM is a matrix of 0s and 1s with the same shape as the weights, and it fixes the weights at positions with 0 to zero. ⊙\odot is the element-wise product. In practice, instead of storing a mask, weights are set to 0 or removed from the matrix.

Most of the methods collected in the survey derive from the following procedure (Algorithm 1 in Blalock et al., originally from Han et al. 2015).

  1. Train the network normally until convergence.
  2. Assign an importance score to each weight (or to each group, such as a channel). The simplest score is the absolute value of the weight, ∣w∣|w|.
  3. Select a fixed fraction with the lowest scores and set the corresponding elements of the mask MM to 0.
  4. Since accuracy drops, retrain the remaining weights (fine-tuning).
  5. Repeat steps 3 and 4 NN times, shrinking the network gradually.

In pruning by absolute weight value (magnitude pruning), a threshold τ\tau is set for each layer, and weights smaller than it are removed.

Mij={1∣Wij∣≥τ0∣Wij∣<τM_{ij} = \begin{cases} 1 & |W_{ij}| \ge \tau \\ 0 & |W_{ij}| < \tau \end{cases}

Han et al. (2015) set the threshold as "a quality parameter × the standard deviation of that layer's weights". How much has been removed is usually expressed as the sparsity (the fraction of weights set to 0), 1−∥M∥0/∣W∣1 - \|M\|_0 / |W|, or as the compression ratio (original parameter count ÷ remaining parameter count). For example, removing 90% gives a compression ratio of 10×.

PyTorch's torch.nn.utils.prune is also built around this "apply a mask" form. When a layer is pruned, the original weights are stored as weight_orig and the mask as weight_mask, and weight=weight_orig⊙weight_mask\text{weight} = \text{weight\_orig} \odot \text{weight\_mask} is computed just before the forward pass.

Four Choices That Distinguish Methods

Blalock et al. (2020) organize the differences among pruning methods mainly into the following four choices.

ChoiceMain optionsWhat it affects
Structure (what unit to remove)Individual weights (unstructured) / neurons, filters, or channels (structured)Whether it gets faster
Score (how importance is measured)Absolute weight value, learned importance coefficients, contribution to activations or gradientsWhich weights remain
Scope of comparisonWithin a layer (local) / across the whole network (global)Fraction kept in each layer
Schedule (when and how much to remove)All at once / gradually over many rounds / during training or at initializationHow much can be removed, and how long it takes

Retraining methods also differ: continuing from the weights before removal (the most common), rewinding to a state partway through training, or reinitializing.

The right of the top figure shows the difference in structure. Unstructured pruning, which removes individual weights, allows fine-grained selection and so can remove a lot, but the matrix keeps its shape and only becomes sparse inside. Structured pruning, which removes groups such as neurons, filters, or channels, makes the matrix itself narrower, so it gets faster with ordinary dense computation. Removing one channel removes that layer's output and the next layer's input together.

Why Accuracy Can Be Preserved

Pruning can preserve accuracy because networks have more parameters than they need. The reports of Han et al. (2015) and Blalock et al. (2020) show the following.

  • Retraining is essential. In the AlexNet experiments of Han et al. (2015), without retraining, accuracy began to drop once only one third of the original connections remained. With retraining, accuracy was preserved even at one tenth. The remaining weights take over the role played by the removed ones.
  • The remaining weights are carried over without reinitialization. Han et al. (2015) report that continuing from the trained values works better than reinitializing some layers and retraining.
  • Removing gradually allows removing more. Repeating pruning and retraining increased the amount that could be removed from AlexNet without losing accuracy to 5 to 9 times that of one-shot removal (Han et al. 2015).
  • Layers differ in how easily they can be pruned. In AlexNet, fully connected layers could be pruned more than convolutional layers, and the first convolutional layer, which connects directly to the input image, was the most sensitive (Figure 6 in Han et al. 2015). For this reason, varying the pruning ratio per layer or comparing across the whole network (global) tends to give better accuracy than pruning every layer at the same ratio (Blalock et al. 2020).
  • Light pruning can improve accuracy. This is thought to be because reducing excess degrees of freedom suppresses overfitting (Han et al. 2015, Blalock et al. 2020).

Pruning resembles Dropout, but there are differences. Dropout randomly disables neurons only during training and uses all of them at inference. Pruning never restores removed weights. Han et al. (2015) recommend lowering the Dropout rate during retraining, since pruning reduces the model's capacity.

Experimental Results

Han et al. (2015) report the following results with magnitude pruning and retraining (Table 1; lower error is better).

Model (data)Original errorError after pruningOriginal parametersRemaining parametersCompression ratio
LeNet-300-100 (MNIST)1.64%1.59%267K22K12×
LeNet-5 (MNIST)0.80%0.77%431K36K12×
AlexNet (ImageNet, top-1)42.78%42.77%61M6.7M9×
VGG-16 (ImageNet, top-1)31.50%31.34%138M10.3M13×

However, compute does not shrink as much as the parameter count does. In AlexNet, 11% of the weights remained, but 30% of the required floating-point operations remained (Table 4). Most parameters are in the fully connected layers, but most computation is in the convolutional layers, which cannot be pruned as much as the fully connected layers.

Blalock et al. (2020) collected results from 81 papers and summarized them as follows.

  • Many methods can compress models substantially with almost no loss of accuracy. When removing a lot, many methods outperform random removal.
  • For the same number of parameters, sparse (pruned) large models tend to be more accurate than dense small models.
  • On the other hand, pruning rarely delivers as much benefit as switching to a more efficient architecture (such as EfficientNet), and the benefit tended to be larger for architectures that were inefficient to begin with.

Practical Considerations

  • Decide first what you want to reduce. If the goal is to reduce storage size, unstructured pruning is enough; if the goal is faster inference, you need structured pruning or libraries and hardware that support sparse computation.
  • Parameter counts and FLOPs are only rough proxies for actual speed. Blalock et al. (2020) also point out that they are crude stand-ins for real latency, memory, and power consumption. Measure in the environment you will actually use.
  • Check each layer's sensitivity. Pruning one layer at a time and watching how accuracy drops reveals which layers must not be over-pruned (such as the first layer).
  • Budget time for retraining. For AlexNet in Han et al. (2015), the original training took 75 hours, while retraining after pruning took 173 hours. Pruning is generally applied once the model is finalized and ready for deployment.
  • Use the same conditions when comparing methods. Blalock et al. (2020) point out that datasets, models, evaluation metrics, and the amount of retraining vary from paper to paper, making fair comparisons between methods difficult.

Even if unstructured pruning sets 90% of the weights to 0, computing with the dense matrix as is leaves compute and speed nearly unchanged. PyTorch's torch.nn.utils.prune also only applies a mask and does not make the matrix smaller. To get a speedup, you need to remove whole channels and rebuild smaller layers, or use a sparse matrix format with dedicated kernels.

Comparison with Other Methods

The following table compares representative pruning methods from the same viewpoints.

MethodUnit removedImportance scoreWhen removedFaster?
Magnitude pruning (Han et al. 2015)Individual weightsAbsolute weight valueAfter training (iterative)Needs sparse computation support
Deep CompressionIndividual weights (+ quantization, Huffman coding)Absolute weight valueAfter trainingMainly reduces size
Filter pruningConvolutional filtersL1 norm of filter weightsAfter trainingFaster as is
Network SlimmingChannelsBatch Normalization scale factor γ\gammaShrink γ\gamma during training, remove after trainingFaster as is
Lottery ticket hypothesisIndividual weightsAbsolute weight valueRemove after training, reset to initial values, and retrainResearch on how small networks learn

It is also compared with other ways to shrink models.

MethodWhat it reducesRetraining?Combinations
PruningNumber of weights or channelsUsually requiredCan be combined with quantization and knowledge distillation
QuantizationBits per valueNot required for post-training quantizationExample of quantizing after pruning (Deep Compression)
Knowledge distillationOverall model size (trains a small student)RequiredA pruned model can serve as the student
Low-rank factorizationMatrix size (product of thin matrices)Usually requiredLike structured pruning, faster with dense computation
  • To reduce file size or storage memory, combining unstructured pruning with quantization is effective.
  • To speed up inference on ordinary GPUs or CPUs, structured pruning that removes filters or channels is a good fit.
  • If the model can be redesigned from scratch, also consider choosing an efficient architecture or training a small model with knowledge distillation.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune

model = nn.Sequential(
    nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(),
    nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(),
    nn.Linear(32, 10),
)

# 1. Unstructured: set the 30% of one layer's weights with the smallest absolute value (L1) to 0
#    amount is a fraction if a float in 0-1, or the number to remove if an integer
prune.l1_unstructured(model[2], name="weight", amount=0.3)
print(hasattr(model[2], "weight_orig"), hasattr(model[2], "weight_mask"))  # True True

# 2. Structured: measure the L2 norm (n=2) per output channel (dim=0) and zero the smallest 50%
#    They only become 0; the matrix shape (number of output channels) does not change
prune.ln_structured(model[0], name="weight", amount=0.5, n=2, dim=0)

# 3. Global: compare several layers together and remove 20% overall (the fraction per layer varies)
params = [(model[2], "weight"), (model[6], "weight")]
prune.global_unstructured(params, pruning_method=prune.L1Unstructured, amount=0.2)

def sparsity(t):
    return float((t == 0).sum()) / t.numel()

print(f"conv2 sparsity: {sparsity(model[2].weight):.2f}")

# 4. Repeat pruning and fine-tuning (the approach of Han et al. 2015)
def prune_and_finetune(model, train_step, rounds=3, amount=0.2):
    layers = [(m, "weight") for m in model.modules() if isinstance(m, (nn.Conv2d, nn.Linear))]
    for _ in range(rounds):
        # Applying it repeatedly to the same weights multiplies the masks (20% of the remaining weights each time)
        prune.global_unstructured(layers, pruning_method=prune.L1Unstructured, amount=amount)
        model.train()
        train_step(model)  # recover accuracy with the remaining weights (the mask zeroes gradients of removed weights)
    return model

# 5. Make pruning permanent: delete weight_orig and weight_mask, keeping only weight (with its zeros)
for m, name in params:
    prune.remove(m, name)
print(sorted(n for n, _ in model[2].named_parameters()))  # ['bias', 'weight'] (weight_orig is gone)

FAQ

Q. What fraction can be removed?
A.

It varies widely by model and task. In Han et al. (2015), with retraining, AlexNet's parameters could be reduced to 1/9 and VGG-16's to 1/13 without losing accuracy. Both are models with much redundancy in their fully connected layers. Models designed to be efficient from the start (such as MobileNetV2) allow less removal. Remove gradually and decide while checking accuracy on validation data.

Q. Does pruning make inference faster?
A.

It depends on how weights are removed. Unstructured pruning, which sets individual weights to 0, does not change the matrix shape, so it does not speed up ordinary dense computation. A speedup requires libraries or hardware that support sparse matrices. Structured pruning, which removes whole filters or channels, makes the layers themselves smaller, so it speeds things up even on ordinary GPUs and CPUs.

Q. What happens if the model is not retrained after removal?
A.

If only a little is removed, accuracy does not drop much even without retraining. For AlexNet in Han et al. (2015), the connections could be halved without retraining. Removing a lot, however, makes accuracy drop sharply, and the gap with the retrained case (which held up to 1/10) grows large. When removing a lot, plan on retraining.

References

  1. D. Blalock, J. J. Gonzalez Ortiz, J. Frankle, and J. Guttag, "What is the State of Neural Network Pruning?," Proceedings of MLSys, 2020. arXiv:2003.03033.
  2. S. Han, J. Pool, J. Tran, and W. J. Dally, "Learning both Weights and Connections for Efficient Neural Networks," arXiv:1506.02626, 2015.
  3. PyTorch Tutorials, "Pruning Tutorial."
  4. PyTorch Documentation, "torch.nn.utils.prune.global_unstructured."