AI Logic

Model Compression

Filter Pruning (Structured Pruning)

Updated:

How filter pruning works. The left side shows the flow: compute the L1 norm of each filter, remove the m smallest together with their feature maps and the corresponding kernels in the next layer, copy the weights into a thinner layer, and retrain. The right side stacks, from bottom to top, the filters of layer i, the feature maps, and the kernels of layer i+1, and removes the two channels with the smallest scores as vertical bands

Background and Overview

Filter pruning is a form of pruning that removes convolutional filters one whole filter at a time. It was proposed by Li et al. (2017) in "Pruning Filters for Efficient ConvNets." Methods that remove groups of weights such as filters or channels, rather than individual weights, are collectively called structured pruning.

This method arose because removing weights one at a time does not reduce computation as much as expected.

  • When weights are removed individually, most of the removed weights are in fully connected layers. Yet in VGG-16, fully connected layers account for 90% of the parameters but less than 1% of the computation (floating-point operations). Most of the computation is in the convolutional layers.
  • Sparsely removing weights in convolutional layers does not change the shape of the matrices. Speeding them up requires libraries that handle sparse matrices or dedicated hardware.

Removing entire filters reduces the number of outputs of a layer (the number of feature maps) itself. Since the matrices simply become smaller, computation gets faster with ordinary dense matrix operations, and the speedup can be estimated from the number of filters removed.

As an everyday analogy, removing weights one at a time is like pulling books out of a bookshelf here and there, leaving it full of gaps. Filter pruning is like removing entire shelves that are rarely read, so the bookshelf itself becomes smaller.

Theory (Selecting Filters by L1 Norm)

The ii-th convolutional layer transforms nin_i input feature maps xi∈Rni×hi×wix_i \in \mathbb{R}^{n_i \times h_i \times w_i} into ni+1n_{i+1} output feature maps xi+1x_{i+1}. To do so, it uses ni+1n_{i+1} three-dimensional filters Fi,j∈Rni×k×kF_{i,j} \in \mathbb{R}^{n_i \times k \times k}. Each filter produces one feature map, and each filter consists of nin_i kernels of size k×kk \times k. The computation of this layer is ni+1nik2hi+1wi+1n_{i+1} n_i k^2 h_{i+1} w_{i+1}.

Li et al. (2017) measure the importance of a filter by the sum of the absolute values of its weights (the L1 norm).

sj=∑l=1ni∑∣Kl∣=∥Fi,j∥1s_j = \sum_{l=1}^{n_i} \sum |K_l| = \|F_{i,j}\|_1

KlK_l is the ll-th kernel of filter Fi,jF_{i,j}. The procedure for removing mm filters from one layer is as follows (Section 3.1).

  1. For each filter Fi,jF_{i,j}, compute the sum of absolute weights sjs_j.
  2. Sort the filters by sjs_j.
  3. Remove the mm filters with the smallest sjs_j and the feature maps they produce. Also remove the kernels in the next layer that were applied to the removed feature maps.
  4. Create new kernel matrices for layers ii and i+1i+1, and copy the remaining weights.

As shown on the right of the figure at the top, removing one filter removes its feature map xi+1,jx_{i+1,j}, and also removes from each filter in the next layer the one kernel applied to that feature map. Therefore, removing mm filters from layer ii reduces the computation of both layer ii and layer i+1i+1 by m/ni+1m / n_{i+1}. If a batch normalization layer follows the convolution, its weights for the corresponding channels are removed as well.

Why the L1 Norm Works as a Criterion

  • Filters with small weights produce only weak outputs. All filters within a layer have the same number of kernels (nin_i), so sjs_j reflects the average magnitude of the kernel weights. Filters with small weights tend to produce feature maps with small values, and removing them is expected to have little effect on the next layer.
  • Removing the smallest filters first was also effective in experiments. For VGG-16 on CIFAR-10, removing the filters with the smallest L1 norm gave higher accuracy than removing filters at random in most layers, while removing the largest filters first caused accuracy to drop sharply (Section 4.4).
  • No data is needed. Methods that select based on feature map values (activations) need to run training data through the network to collect statistics. The L1 norm can be computed from the weights alone. The paper reports that, even compared with activation-based criteria, the L1 norm is a good data-free criterion (Section 4.5). There was no notable difference from the L2 norm.

Magnitude-based pruning (removing weights one at a time) also removes an entire filter if all of its weights fall below the threshold. However, it is hard to determine in advance how many filters will disappear, and the filters that remain stay sparse. Filter pruning lets the number of filters to remove be set directly, which makes it easy to tune toward a target speed.

Applying It to the Whole Network

To thin the whole network rather than a single layer, decide how many filters to remove from which layers and how to retrain.

Analyze each layer's sensitivity. Prune only one layer and check the accuracy on validation data (Section 3.2). Prune more from layers whose accuracy holds up, and prune only a little from sensitive layers or leave them untouched. In VGG-16 and ResNet, layers that handle feature maps of the same size (the same stage) have similar sensitivity, so pruning the same fraction per stage reduces the number of hyperparameters to tune.

Decide how to handle consecutive layers. When pruning multiple layers at once, there are two ways to select filters (Section 3.3).

StrategyHow sjs_j is computedCharacteristics
IndependentIncludes kernels applied to feature maps removed in the previous layerSimple to decide per layer
GreedyExcludes kernels applied to feature maps removed in the previous layerHigher accuracy when pruning a lot

Architectures with residual connections constrain how pruning is done. In a ResNet residual block, the first convolutional layer can be pruned freely. The output of the second convolutional layer is added to the shortcut path, so the channels with the same indices as on the shortcut side must be removed (Figure 4). The paper aligns the channels removed from the second layer with the selection for the shortcut's 1 × 1 convolution (projection).

Retrain. There are two ways to retrain (Section 3.4).

  • Prune once and retrain: For layers whose accuracy holds up after pruning, a short training run restores the original accuracy. This saves a lot of time for deep networks.
  • Prune layer by layer (or filter by filter) and retrain each time: Accuracy tends to be higher, but deep networks need many epochs.

In the paper's experiments, retraining used a learning rate of 0.001 for 40 epochs on CIFAR-10 and 20 epochs on ImageNet, a quarter of the original training length.

Experimental Results

These are the results from Table 1 of Li et al. (2017) (CIFAR-10 and ImageNet; lower error is better).

Model (data)Original errorError after pruningComputation reducedParameters reduced
VGG-16 (CIFAR-10)6.75%6.60%34.2%64.0%
ResNet-56 (CIFAR-10), B6.96%6.94%27.6%13.7%
ResNet-110 (CIFAR-10), B6.47%6.70%38.6%32.4%
ResNet-34 (ImageNet, top-1), A26.77%27.44%15.5%7.6%
ResNet-34 (ImageNet, top-1), B26.77%27.83%24.2%10.8%

The table shows the following.

  • For VGG-16, computation was cut by a third while preserving accuracy. In VGG-16 on CIFAR-10, the later layers (layers 8–13) that handle small 4 × 4 and 2 × 2 feature maps had many redundant filters, and removing 50–75% of them did not reduce accuracy.
  • ResNet allows less pruning than VGG. This is because it is already an efficient architecture with few parameters. Even so, computation for ResNet-110 was reduced by 38.6%. In ResNet, blocks near the points where the number of feature maps changes were more sensitive.
  • Pruning and retraining gave higher accuracy than training the small model from scratch. Training the same architecture from scratch gave 6.88% for VGG-16, 8.69% for ResNet-56 (B), and 7.06% for ResNet-110 (B), all higher error rates than the pruned and retrained models.

Practical Considerations

  • Identify sensitive layers before pruning. How easily a layer can be pruned varies greatly. Pruning the whole network by the same fraction right away can leave sensitive layers unable to recover their accuracy.
  • Check the network's structural constraints. With residual connections, concatenation, grouped convolution, and similar structures, the channel indices of multiple layers are linked. Linked layers must have the same channels removed together.
  • The more efficient the model, the less can be removed. For ResNet-34 on ImageNet in the paper, cutting computation by 24% increased the top-1 error by about 1 point.
  • PyTorch's built-in utility only applies a mask. torch.nn.utils.prune.ln_structured zeros out channels, but the layer's shape does not change, so it does not get faster. To speed things up, build new layers using only the remaining channels.

The L1 norm can only be compared among filters within the same layer. The distribution of weight magnitudes varies greatly between layers (Figure 2(a) in the paper), so comparing L1 norms across the whole network with a single threshold can end up removing filters from only certain layers. The paper also sets the pruning fraction per layer (or per stage).

Comparison with Other Methods

The table compares methods by pruning unit and filter selection.

MethodUnit removedHow importance is determinedTraining procedureFaster?
Magnitude-based pruning (Han et al. 2015)Individual weightsAbsolute value of weightsPrune after normal trainingRequires sparse computation support
Filter pruning (Li et al. 2017)Filters (output channels)L1 norm of filtersPrune after normal trainingFaster as is
Network Slimming (Liu et al. 2017)ChannelsBatch Normalization coefficient γ\gammaTrain with an L1 penalty on γ\gamma, then pruneFaster as is
Structured sparsity learning (Wen et al. 2016, etc.)Filters, channels, layersSum of L2 norms of filter weights (group regularization)Drive groups toward 0 with a penalty during trainingFaster as is

Filter pruning has the advantage that it can be applied directly to a trained model and needs no additional regularization. Network Slimming and structured sparsity learning, on the other hand, push the model toward an "easy-to-prune" state from the training stage, so accuracy is easier to preserve even when pruning a lot (at the cost of retraining).

  • To speed up an existing trained model with little effort, filter pruning is a good fit.
  • When training from scratch is possible and more should be removed, methods that induce sparsity during training, such as Network Slimming, are a good fit.
  • It can also be combined with approaches such as using an efficient model from the start (MobileNet, etc.) 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


def l1_scores(conv):
    """Sum of absolute weights of each filter (output channel): s_j = Σ|F_i,j|"""
    return conv.weight.detach().abs().sum(dim=(1, 2, 3))   # shape (out_channels,)


@torch.no_grad()
def prune_filters(conv, bn, next_conv, m):
    """Remove the m filters of conv with the smallest L1 norm, along with the corresponding channels of bn and next_conv.
    Build and return new (thinner) layers using only the remaining channels"""
    s = l1_scores(conv)
    keep = torch.argsort(s, descending=True)[: conv.out_channels - m].sort().values

    new_conv = nn.Conv2d(conv.in_channels, len(keep), conv.kernel_size,
                         conv.stride, conv.padding, bias=conv.bias is not None)
    new_conv.weight.copy_(conv.weight[keep])                  # copy the remaining filters
    if conv.bias is not None:
        new_conv.bias.copy_(conv.bias[keep])

    new_bn = nn.BatchNorm2d(len(keep))                         # match the channels in batch normalization too
    for name in ["weight", "bias", "running_mean", "running_var"]:
        getattr(new_bn, name).copy_(getattr(bn, name)[keep])

    new_next = nn.Conv2d(len(keep), next_conv.out_channels, next_conv.kernel_size,
                         next_conv.stride, next_conv.padding, bias=next_conv.bias is not None)
    new_next.weight.copy_(next_conv.weight[:, keep])           # in the next layer, remove "input channels"
    if next_conv.bias is not None:
        new_next.bias.copy_(next_conv.bias)
    return new_conv, new_bn, new_next


conv1, bn1 = nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64)
conv2 = nn.Conv2d(64, 128, 3, padding=1)
c1, b1, c2 = prune_filters(conv1, bn1, conv2, m=16)            # remove 16 of 64 filters
print(c1.weight.shape, c2.weight.shape)  # (48, 3, 3, 3) and (128, 48, 3, 3): both layer i and layer i+1 get thinner

net = nn.Sequential(c1, b1, nn.ReLU(), c2)
net.eval()                                  # inference uses the BN running averages
y = net(torch.randn(1, 3, 32, 32))
print(y.shape)                              # the output shape is unchanged (128 channels)
# next, switch to net.train() and retrain with a small learning rate


# For reference: PyTorch's built-in utility. Compare L1 norms (n=1) per output channel (dim=0) and zero out 25%
# However, this only sets values to 0; the layer's shape does not change (no speedup)
conv = nn.Conv2d(3, 64, 3, padding=1)
prune.ln_structured(conv, name="weight", amount=0.25, n=1, dim=0)
zero_filters = (conv.weight.detach().abs().sum(dim=(1, 2, 3)) == 0).sum().item()
print(zero_filters)  # 16

FAQ

Q. Can it remove more than pruning weights one at a time?
A.

In terms of parameter count, removing weights one at a time usually removes more, because the targets can be chosen at a finer granularity. For example, Han et al. (2015) reduced VGG-16's parameters by 13×, whereas Li et al. (2017)'s filter pruning reduced the parameters of VGG-16 on CIFAR-10 by about 64%. In exchange, filter pruning makes the layers themselves smaller, so inference actually gets faster on ordinary GPUs and CPUs. Choose based on what should be reduced (size or speed).

Q. How should the pruning fraction be decided?
A.

First prune one layer at a time to see how accuracy drops (sensitivity analysis), then prune less from sensitive layers and more from insensitive ones. Li et al. (2017) grouped layers that handle feature maps of the same size (the same stage) and used the same fraction for them, leaving especially sensitive layers unpruned. If there is a target amount of computation, it can be estimated using the fact that removing mm filters from layer ii reduces the computation of both layer ii and layer i+1i+1 by m/ni+1m / n_{i+1}.

Q. Is it fine to retrain the pruned model from scratch?
A.

In the experiments of Li et al. (2017), training a model with the same architecture as the pruned one from scratch gave higher error than pruning and retraining (6.88% versus 6.60% for VGG-16, and 8.69% versus 6.94% for ResNet-56). Retraining while inheriting the trained weights tends to reach better accuracy in less time.

References

  1. H. Li, A. Kadav, I. Durdanovic, H. Samet, and H. P. Graf, "Pruning Filters for Efficient ConvNets," ICLR, 2017. arXiv:1608.08710.
  2. 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.
  3. PyTorch Tutorials, "Pruning Tutorial."