AI Logic

Model Compression

Network Slimming

Updated:

How Network Slimming works. The left side shows the flow of obtaining a thin network by repeating, if needed, "train with an L1 penalty on γ → remove channels with small γ → retrain." The right side stacks, from bottom to top, the convolution of layer i, the BN γ, and the weights of layer i+1, and shows the two channels with γ of 0.001 and 0.003 being removed as vertical bands

Background and Overview

Network Slimming, proposed by Liu et al. (2017), is a method that identifies "channels that can be removed" during training and removes those channels entirely. It is a form of structured pruning that removes whole channels, so the layers themselves become thinner, and the model becomes smaller and faster on ordinary GPUs and CPUs with standard deep learning libraries.

The key idea is to use the coefficient γ\gamma of the Batch Normalization (BN) layers as the importance of each channel. In many CNNs, BN is placed after the convolution, and BN multiplies each channel's output by γ\gamma. Adding the sum of the absolute values of γ\gamma to the training loss as a penalty pushes the γ\gamma of many channels toward 0. Channels with γ\gamma near 0 have little effect on the output, so removing them barely hurts accuracy.

Pruning at the channel level offers a good balance between ease of use and effectiveness. The paper organizes the pruning granularities as follows.

Pruning unitFlexibilityWhat is needed for speedup
WeightHighest; can remove the mostSparse computation libraries or specialized hardware
ChannelModerateNothing special (layers simply become thinner)
LayerLow (removes whole layers)Nothing special, but only effective when the network is deep enough (e.g., 50+ layers)

As an everyday analogy, Network Slimming is like giving each employee a "contribution knob" and having them work for a year under a rule that rewards turning the knob down. At the end of the year, removing the duties of people whose knob is almost at 0 barely changes the company's results.

Theory (L1 Penalty on Scaling Factors)

A scaling factor γ\gamma that multiplies the output of each channel is introduced and trained jointly with the network weights WW. The training objective is the ordinary loss plus a penalty on γ\gamma (Eq. (1) in the paper).

L=∑(x,y)l(f(x,W),y)+λ∑γ∈Γg(γ)L = \sum_{(x, y)} l\bigl(f(x, W), y\bigr) + \lambda \sum_{\gamma \in \Gamma} g(\gamma)

(x,y)(x, y) are the training inputs and targets, and Γ\Gamma is the set of γ\gamma for all channels. The penalty is g(s)=∣s∣g(s) = |s| (the L1 norm), which tends to push many values exactly toward 0 (regularization). λ\lambda balances the two terms. Since ∣s∣|s| is not differentiable at 0, it is updated with the subgradient (λ sign(γ)\lambda\,\mathrm{sign}(\gamma)).

The BN γ\gamma is used directly as the scaling factor. BN normalizes the input with the mean μB\mu_{\mathcal{B}} and standard deviation σB\sigma_{\mathcal{B}} of the mini-batch B\mathcal{B}, then multiplies each channel by γ\gamma and adds β\beta (Eq. (2)).

z^=zin−μBσB2+ϵ,zout=γz^+β\hat{z} = \frac{z_{\mathrm{in}} - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}}, \qquad z_{\mathrm{out}} = \gamma \hat{z} + \beta

The procedure is as follows (Figure 2).

  1. Train the network with an L1 penalty on the BN γ\gamma.
  2. Collect the γ\gamma of all layers together and use a chosen fraction (percentile) as the threshold. For example, to remove 70%, the 70th percentile value is the threshold.
  3. Remove the channels whose γ\gamma is below the threshold. Also remove the incoming connections to that channel (the filter in the preceding convolution) and the outgoing connections (the corresponding inputs of the next layer).
  4. Retrain the thinned network (fine-tuning).
  5. If needed, apply steps 1–4 to the thinned network again (multi-pass).

Why Use the BN γ

The paper explains why the BN γ\gamma is the best choice for the scaling factor by comparing it with other placements.

  • Adding factors to a CNN without BN makes their values meaningless. Both convolution and multiplication by a factor are linear, so the same output can be produced by making the factor smaller and the convolution weights larger. A small factor does not mean the channel is unimportant.
  • Placing the factor before BN cancels its effect. BN's normalization cancels out the multiplied factor.
  • Placing the factor after BN results in two consecutive factors. It overlaps with the BN γ\gamma and is redundant.

Using the BN γ\gamma provides the importance of each channel without adding anything to the network. Since the BN output is normalized, a channel with γ\gamma near 0 outputs nearly a constant value, zout≈βz_{\mathrm{out}} \approx \beta, and passes no information to the next layer.

The larger the penalty strength λ\lambda, the more the γ\gamma values cluster near 0 (Figure 4). With λ=0\lambda = 0, the distribution of γ\gamma is relatively flat, but with λ=10−4\lambda = 10^{-4}, most γ\gamma values cluster near 0. This clearly separates "channels that can be removed without harm" from "necessary channels," so accuracy drops less after pruning.

When trying to remove channels from a normally trained model, as in filter pruning, it is rare for all the weights going into and out of a channel to be near 0, so few channels can be removed. The paper cites a report that only about 10% of the parameters of a trained ResNet could be removed. Network Slimming avoids this problem by steering the network toward an easily prunable state during training.

Experimental Results

These are the results on CIFAR-10 (Table 1(a) of the paper; lower error is better; "70% pruned" means 70% of the channels were removed).

ModelOriginal errorError after pruningParameters removedComputation removed
VGGNet (70% pruned)6.34%6.20%88.5%51.0%
DenseNet-40 (40% pruned)6.11%5.19%35.7%28.4%
DenseNet-40 (70% pruned)6.11%5.65%65.2%55.0%
ResNet-164 (40% pruned)5.42%5.08%14.9%23.7%
ResNet-164 (60% pruned)5.42%5.27%35.2%44.9%

On ImageNet, removing 50% of the channels from the 11-layer VGG-A, which includes fully connected layers, reduced parameters by 82.5% and computation by 30.4%, with validation error going from 36.69% to 36.66% (Table 2). Computation decreased less than parameters because only 378 of 2,752 channels were removed from the computation-heavy convolutional layers, whereas 5,094 of 8,192 were removed from the parameter-heavy fully connected layers.

With multi-pass pruning (Table 4(a), VGGNet on CIFAR-10, removing at most 50% per layer), the model after the fifth round of training had 20 times fewer parameters and 5 times less computation, with an error of 5.96%, lower than the original 6.34%.

These results show the following.

  • Accuracy can be almost fully preserved even when more than 60% of the channels are removed. Parameters were reduced by up to about 10 times, and computation by roughly half.
  • Removing about 40% often improves accuracy over the original. This was seen in ResNet and DenseNet, and the paper attributes it to the regularization effect of the L1 penalty.
  • Architectures that are already efficient see smaller reductions. ResNet-164 was not reduced as much as VGGNet, possibly because its bottleneck structure already narrows the channels.

Practical Considerations

  • It assumes a CNN with BN. In architectures without BN after the convolution, γ\gamma cannot be used as the importance.
  • There are two hyperparameters. The penalty strength λ\lambda and the pruning ratio. In the paper, λ\lambda was chosen from 10−310^{-3}, 10−410^{-4}, and 10−510^{-5} on validation data, using 10−410^{-4} for VGGNet and 10−510^{-5} for ResNet and DenseNet. Beyond a certain pruning ratio, accuracy drops sharply (for DenseNet-40, beyond 80% the original accuracy could no longer be reached even after retraining).
  • Architectures with residual connections or concatenation require extra work. In ResNet (pre-activation) and DenseNet, BN comes before the convolution, and the output of one layer feeds into multiple layers. Therefore, a "channel selection layer" that uses only some of the channels is placed at the entrance of a layer to remove the pruned channels.
  • Budget time for retraining. Both training with the penalty and retraining after pruning are needed.

Because the threshold is shared across all layers, all channels in some layer may be removed. In the paper as well, a shared threshold sometimes removed entire layers in the fully connected network on MNIST, so it was changed to remove 80% from each of the two hidden layers. In multi-pass pruning, at most 50% is removed per layer. In architectures without residual connections, such as VGG, removing an entire layer breaks the network, so set a per-layer upper limit.

Comparison with Other Methods

The following table compares structured pruning methods that remove channels or filters from the same perspectives.

MethodHow importance is determinedTraining procedureExtra parametersHow the pruning ratio is decided
Network SlimmingBN γ\gammaTrain with an L1 penalty on γ\gamma, prune, and retrainNone (uses BN γ\gamma)A percentile shared across all layers
Filter pruning (Li et al. 2017)L1 norm of filter weightsTrain normally, prune, and retrainNoneDecided per layer (stage)
Structured Sparsity Learning (SSL, Wen et al. 2016)Group-wise norm of filter weightsTrain with a group-wise penalty on the weights (group LASSO)NoneWhatever the penalty drives to 0
Magnitude-based pruningAbsolute value of weightsTrain normally, prune, and retrainNonePer-layer threshold

Compared with SSL, Network Slimming only places a penalty on one value γ\gamma per channel, so it does not need to compute penalty gradients for all weights, and its objective is much simpler. On the fully connected network on MNIST, it removed slightly more parameters than SSL (84.4% vs. 83.5%) and had a slightly lower error (1.49% vs. 1.53%, Table 3).

  • When you can train from scratch and want to thin a CNN with BN, Network Slimming is the easy choice.
  • To quickly apply pruning to an already trained model, filter pruning, which does not require changing the training procedure, is a better fit.
  • Since the number of channels kept in each layer is determined automatically, Network Slimming can also be used as "architecture search for the width of each layer."

PyTorch example

Show code
python
import torch
import torch.nn as nn


def make_model(widths=(64, 128, 256), num_classes=10):
    layers, c_in = [], 3
    for w in widths:
        layers += [nn.Conv2d(c_in, w, 3, padding=1, bias=False), nn.BatchNorm2d(w), nn.ReLU()]
        c_in = w
    layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(c_in, num_classes)]
    return nn.Sequential(*layers)


model = make_model()
for m in model.modules():
    if isinstance(m, nn.BatchNorm2d):
        nn.init.constant_(m.weight, 0.5)   # the paper initializes γ to 0.5


# 1. Training: add λ Σ|γ| to the loss (Eq. (1)). Just add the subgradient λ·sign(γ) of |γ| to the gradient
def add_l1_on_bn(model, lam=1e-4):
    for m in model.modules():
        if isinstance(m, nn.BatchNorm2d):
            m.weight.grad.add_(lam * torch.sign(m.weight.detach()))

opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)
x, y = torch.randn(8, 3, 32, 32), torch.randint(0, 10, (8,))
model.train()
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad()
loss.backward()
add_l1_on_bn(model, lam=1e-4)              # after the ordinary gradient, add the γ penalty term
opt.step()


# 2. Threshold: pool the γ of all BN layers and compute the percentile of the pruning ratio
def global_threshold(model, ratio=0.5):
    gammas = torch.cat([m.weight.detach().abs() for m in model.modules() if isinstance(m, nn.BatchNorm2d)])
    return torch.quantile(gammas, ratio)


# 3. Prune: build a thin model that keeps only channels with γ at or above the threshold
@torch.no_grad()
def slim(model, ratio=0.5, min_keep=1):
    th = global_threshold(model, ratio)
    mods = list(model)
    new_layers, keep_prev = [], torch.arange(3)          # keep all 3 input channels
    for i, m in enumerate(mods):
        if isinstance(m, nn.Conv2d):
            bn = mods[i + 1]
            keep = (bn.weight.abs() >= th).nonzero().flatten()
            if len(keep) < min_keep:                      # prevent an entire layer from being removed
                keep = bn.weight.abs().topk(min_keep).indices.sort().values
            conv = nn.Conv2d(len(keep_prev), len(keep), m.kernel_size, m.stride, m.padding, bias=False)
            conv.weight.copy_(m.weight[keep][:, keep_prev])  # remove both outgoing and incoming sides
            new_bn = nn.BatchNorm2d(len(keep))
            for name in ["weight", "bias", "running_mean", "running_var"]:
                getattr(new_bn, name).copy_(getattr(bn, name)[keep])
            new_layers += [conv, new_bn]
            keep_prev = keep
        elif isinstance(m, nn.Linear):
            fc = nn.Linear(len(keep_prev), m.out_features)
            fc.weight.copy_(m.weight[:, keep_prev])
            fc.bias.copy_(m.bias)
            new_layers.append(fc)
        elif not isinstance(m, nn.BatchNorm2d):
            new_layers.append(m)
    return nn.Sequential(*new_layers)


small = slim(model, ratio=0.5)
print([m.out_channels for m in small if isinstance(m, nn.Conv2d)])  # the number kept per layer is determined automatically
small.eval()
print(small(torch.randn(1, 3, 32, 32)).shape)  # torch.Size([1, 10])
# 4. then call small.train() and retrain (without the penalty)

FAQ

Q. How should λ (the penalty strength) be chosen?
A.

In the paper, it was chosen from 10−310^{-3}, 10−410^{-4}, and 10−510^{-5} on validation data, using 10−410^{-4} for VGGNet and 10−510^{-5} for ResNet and DenseNet. The larger λ\lambda is, the more γ\gamma clusters near 0 and the easier pruning becomes, but if it is too large, the accuracy of training itself drops. Choose it while looking at the desired pruning ratio and the accuracy of the model trained with the penalty.

Q. Can it be used for architectures without BN, such as Transformers?
A.

Network Slimming assumes a CNN with BN after the convolution, and the paper's experiments are on CNNs and fully connected networks. It cannot be used as-is in architectures where the BN γ\gamma is unavailable. Per-channel factors can be added, but the paper points out that placing a factor after a linear layer without BN does not serve as an importance measure, because it cancels out against the weight magnitudes.

Q. How far can the fraction of pruned channels be increased?
A.

It depends on the model and data. For DenseNet-40 on CIFAR-10, up to 80% could be pruned while keeping the original accuracy after retraining, but beyond that the original accuracy could no longer be reached. On datasets with many classes such as CIFAR-100, the amount that could be pruned tended to be smaller. Increase the ratio gradually and check on validation data.

References

  1. Z. Liu, J. Li, Z. Shen, G. Huang, S. Yan, and C. Zhang, "Learning Efficient Convolutional Networks through Network Slimming," arXiv:1708.06519, 2017.
  2. liuzhuang13/slimming (implementation by the authors)
  3. H. Li, A. Kadav, I. Durdanovic, H. Samet, and H. P. Graf, "Pruning Filters for Efficient ConvNets," ICLR, 2017. arXiv:1608.08710.