AI Logic

Architectures

ShuffleNet V2

Updated:

Architecture of ShuffleNet V2. The left side shows the overall flow (3×3 convolution, max pooling, three stages of units, 1×1 convolution, global average pooling, fully connected layer). The right side shows the inside of the units (the basic unit, which splits the channels, convolves only one half, concatenates, and shuffles; and the unit with two branches that halves the spatial size and doubles the channel count) and the four design guidelines

Background and overview

ShuffleNet V2 derives four guidelines for designing lightweight networks based on actual speed on real hardware rather than computational cost (FLOPs), and redesigns the ShuffleNet unit according to them. It is a convolutional neural network proposed in 2018 by Ma et al. from Megvii (Face++) and Tsinghua University.

Earlier lightweight models (MobileNet, MobileNetV2, ShuffleNet, and others) were designed with the goal of reducing FLOPs. Yet models with the same FLOPs can differ greatly in actual speed. For example, MobileNetV2 runs much faster than NASNet-A, which has similar FLOPs. The paper identifies two causes of this discrepancy.

  • Some time is not counted in FLOPs: memory reads and writes (memory access cost, MAC) and the degree of parallelism are not counted in FLOPs. Breaking down the runtime of ShuffleNet and MobileNetV2 shows that operations that contribute almost nothing to FLOPs, such as data shuffling, ReLU, and addition, take a non-negligible share of the time (Figure 2 of the paper).
  • The same FLOPs take different times on different devices: for example, GPU libraries are especially optimized for 3×33 \times 3 convolutions, so a 3×33 \times 3 convolution is not necessarily 9 times slower than a 1×11 \times 1 one.

The paper therefore takes the position of measuring and comparing speed itself on the target device, and through experiments on a GPU (GTX 1080Ti) and a smartphone CPU (ARM, Snapdragon 810) derives four design guidelines, then builds a new unit that satisfies all of them.

The main results of the paper are as follows.

  • On ImageNet, at about 40 MFLOPs, its top-1 error is 3.5 points lower than ShuffleNet (V1) and 3.7 points lower than MobileNetV2.
  • At about 500 MFLOPs on a GPU, it runs 58% faster than MobileNetV2 and 63% faster than ShuffleNet (V1).
  • In COCO object detection, it is also more accurate and faster than other lightweight models with the same FLOPs.

It is also included in torchvision as shufflenet_v2_x1_0 and related models.

Theory: four guidelines for fast networks

The paper summarizes the factors that determine actual speed on hardware as four guidelines (G1–G4). Each is verified by keeping FLOPs fixed, changing only the structure, and measuring speed on a GPU and on ARM.

G1: Equal input and output channel counts minimize memory access

Most of the computation in lightweight models is 1×11 \times 1 convolution. With c1c_1 input channels, c2c_2 output channels, and a feature map of height and width h,wh, w, the FLOPs BB and the memory access cost (MAC) are as follows (assuming a sufficiently large cache).

B=hwc1c2,MAC=hw(c1+c2)+c1c2B = hwc_1c_2, \qquad \mathrm{MAC} = hw(c_1 + c_2) + c_1c_2

The first term is reading and writing the input and output feature maps, and the second is reading the weights. By the inequality of arithmetic and geometric means, the following holds.

MAC≥2hwB+Bhw\mathrm{MAC} \geq 2\sqrt{hwB} + \frac{B}{hw}

Equality holds when c1=c2c_1 = c_2. In other words, for fixed FLOPs, MAC is smallest when the input and output channel counts are equal. Indeed, when FLOPs are kept fixed and c1:c2c_1 : c_2 is varied from 1:1 to 1:12, 1:1 is the fastest (1480 vs. 748 batches per second on the GPU; Table 1 of the paper).

G2: Excessive group convolution increases memory access

For a 1×11 \times 1 grouped convolution with gg groups, the FLOPs become B=hwc1c2/gB = hwc_1c_2/g, and the MAC is as follows.

MAC=hw(c1+c2)+c1c2g=hwc1+Bgc1+Bhw\mathrm{MAC} = hw(c_1 + c_2) + \frac{c_1c_2}{g} = hwc_1 + \frac{Bg}{c_1} + \frac{B}{hw}

With the input shape and FLOPs fixed, MAC grows as gg increases. Splitting into groups allows more channels for the same FLOPs, but reads and writes increase accordingly. In experiments, g=8g = 8 was more than twice as slow as g=1g = 1 (ordinary convolution) on the GPU and up to 30% slower on ARM (Table 2 of the paper).

G3: Network fragmentation reduces parallelism

Splitting a block into many small operations (fragmentation), as in GoogLeNet or automatically searched architectures, may help accuracy but slows things down on highly parallel devices such as GPUs. It also adds overhead for launching kernels and synchronizing the separate paths. With FLOPs fixed, splitting a 1×11 \times 1 convolution into four reduced the speed on the GPU to about one third of the single-path version (Table 3 of the paper). On ARM, the difference was smaller.

G4: Element-wise operations are non-negligible

Element-wise operations such as ReLU, addition, and adding a bias have small FLOPs but large MAC. The paper also counts depthwise convolution, which has a high MAC relative to its FLOPs, in this category. Removing ReLU and the shortcut from a ResNet bottleneck block made it about 20% faster on both the GPU and ARM (Table 4 of the paper).

From the four guidelines, the paper concludes that an efficient network should "(1) use convolutions with equal input and output channel counts, (2) be aware of the cost of group convolution, (3) reduce fragmentation, and (4) reduce element-wise operations." For example, ShuffleNet (V1) relies heavily on group convolutions (violating G2) and narrows the width in its bottleneck (violating G1). MobileNetV2 expands the width and then shrinks it back (violating G1), and applies depthwise convolution and ReLU on wide feature maps (violating G4).

The ShuffleNet V2 unit

The ShuffleNet V2 unit splits the channels into two, passes one half through unchanged, convolves only the other half, concatenates the two, and finally mixes them with a channel shuffle. The right side of the figure at the top of the article shows the inside of the unit.

The basic unit (Figure 3(c) of the paper), with cc input channels, computes as follows.

  1. Channel split: split the input channels into two branches of c−c′c - c' and c′c' channels. In the paper, c′=c/2c' = c/2.
  2. One branch is passed through unchanged (G3: no added fragmentation).
  3. The other branch goes through a 1×11 \times 1 convolution (BN, ReLU), a 3×33 \times 3 depthwise convolution (BN only), and a 1×11 \times 1 convolution (BN, ReLU). All three have equal input and output channel counts (G1). The 1×11 \times 1 convolutions are not grouped (G2).
  4. Concatenate the two branches. The channel count returns to cc, the same as the input.
  5. Mix the channels of the two branches with the same channel shuffle as in ShuffleNet (V1).

The "addition" of the shortcut in the V1 unit is gone. ReLU and depthwise convolution apply to only one branch, and the three operations "concatenate", "channel shuffle", and "channel split of the next unit" can be merged into a single element-wise operation (G4).

In the spatial downsampling unit (Figure 3(d) of the paper), there is no channel split; the input is fed to both branches.

  • One branch is a 3×33 \times 3 depthwise convolution (stride 2, BN) followed by a 1×11 \times 1 convolution (BN, ReLU).
  • The other branch is the same three convolutions as in the basic unit, with the depthwise convolution at stride 2.
  • Because the two branches are concatenated, the number of output channels is twice the input. A channel shuffle is then applied.

The channel shuffle ensures that, at the next unit's channel split, both the pass-through side and the convolved side receive channels from both branches of the previous unit. It is like splitting a deck of cards into two piles, reshuffling only one of them, and then interleaving the two piles back together; after a few repetitions, every card has been reshuffled.

Overall architecture

The overall flow of ShuffleNet V2 is almost the same as ShuffleNet (V1); the only difference is that one 1×11 \times 1 convolution is added right before global average pooling. The left side of the figure at the top of the article shows the overall flow of ShuffleNet V2 1×.

An image flows through in the following order (for a 224×224 ImageNet image; Table 5 of the paper).

  1. A 3×33 \times 3 convolution (24 channels, stride 2) reduces it to 112×112.
  2. A 3×33 \times 3 max pooling (stride 2) reduces it to 56×56.
  3. Three stages (Stage2–4) stack 4, 8, and 4 units. The first unit of each stage is a downsampling unit, and the rest are basic units (56 → 28 → 14 → 7).
  4. A 1×11 \times 1 convolution (Conv5) mixes the features.
  5. Global average pooling turns them into a vector, and a 1000-class fully connected layer predicts the class.

Four model sizes are built by varying the number of output channels of each stage (Table 5 of the paper).

Model0.5×1×1.5×2×
Stage2 output channels48116176244
Stage3 output channels96232352488
Stage4 output channels192464704976
Conv5 output channels1024102410242048
FLOPs41M146M299M591M
Parameters1.4M2.3M3.5M7.4M

The training settings (hyperparameters and so on) are exactly the same as in the ShuffleNet (V1) paper.

In each unit, half of the channels are passed straight to the next unit. As a result, the number of channels directly connecting the ii-th and i+ji+j-th units is (1/2)jc(1/2)^j c, decreasing exponentially with distance. The paper views this as achieving DenseNet-style "feature reuse" at low cost. In DenseNet, too, connections between nearby layers are known to be strong and those between distant layers weak, and this pattern is similar.

Experimental results

Comparison on ImageNet (top-1 error %; GPU is batches per second on a GTX 1080Ti with batch size 8; ARM is images per second on a single thread of a Snapdragon 810. Higher speed values are faster. Excerpt from Table 8 of the paper)

FLOPs levelModelMFLOPsErrorGPUARM
~40MShuffleNet V2 0.5×4139.741757.0
0.25 MobileNet (V1)4149.450236.4
0.4 MobileNetV2 (reimpl., 160×160)4343.433333.2
ShuffleNet (V1) 0.5× (g=3g = 3)3843.234756.8
~140MShuffleNet V2 1×14630.634124.4
0.5 MobileNet (V1)14936.338216.5
0.75 MobileNetV2 (reimpl., 192×192)14532.123515.9
ShuffleNet (V1) 1× (g=3g = 3)14032.621321.8
~300MShuffleNet V2 1.5×29927.425511.8
0.75 MobileNet (V1)32531.631410.6
1.0 MobileNetV230028.01808.9
ShuffleNet (V1) 1.5× (g=3g = 3)29228.516410.3
~500MShuffleNet V2 2×59125.12176.7
1.0 MobileNet (V1)56929.42476.5
1.4 MobileNetV258525.31375.4
ShuffleNet (V1) 2× (g=3g = 3)52426.31336.4
ShuffleNet V2 2× (with SE)59724.61615.6
NASNet-A (reimpl.)56426.01304.6

At every level, ShuffleNet V2 has the lowest error. The gap is larger for smaller models, and the paper suggests that MobileNetV2 performs poorly at the 40 MFLOPs level because it has too few channels.

In terms of speed, MobileNet (V1) is faster than ShuffleNet V2 on the GPU at some levels. The paper explains that the V1 structure satisfies many of the guidelines (for example, it is less fragmented than ShuffleNet V2). On ARM, ShuffleNet (V1), Xception, and ShuffleNet V2 run at similar speeds, while MobileNetV2 is slower, especially at small FLOPs. The paper also attributes the slowness of automatically searched models such as NASNet-A to their high fragmentation.

Large models (Table 6 of the paper)

ModelFLOPsTop-1 error
ShuffleNet V2-502.3G22.8%
ShuffleNet (V1)-50 (the authors' implementation)2.3G25.2%
ResNet-503.8G24.0%
SE-ShuffleNet V2-164 (with residual path)12.7G18.56%
SENet20.7G18.68%

ShuffleNet V2 also scales to large models. A 50-layer ShuffleNet V2 achieves lower error than ResNet-50 with 40% fewer FLOPs. For very deep models of more than 100 layers, a residual path is added to the unit to speed up convergence.

Object detection (COCO minival, replacing the backbone of Light-Head R-CNN, input 800×1200. mmAP %. FLOPs are for a 224×224 input; Table 7 of the paper)

Backbone40M140M300M500M
Xception21.929.031.332.9
ShuffleNet (V1)20.927.029.932.9
MobileNetV220.724.430.030.6
ShuffleNet V222.529.031.833.3
ShuffleNet V2* (larger receptive field)23.729.632.234.2

Xception does even better in detection than in classification, which the paper attributes to the larger receptive field of the Xception block (7 vs. 3). ShuffleNet V2*, which enlarges the receptive field by adding one 3×33 \times 3 depthwise convolution before the first 1×11 \times 1 of each unit, further improves accuracy at a small additional cost. In GPU speed, ShuffleNet V2 is also about 40% faster than ShuffleNet (V1) and about 16% faster than MobileNetV2.

Practical considerations

Keep the following points in mind when using ShuffleNet V2.

  • Use an even number of channels: the channel split divides the channels in half and the channel shuffle uses 2 groups, so each stage's channel count must be divisible by 2.
  • The downsampling unit doubles the channel count: since the outputs of the two branches are concatenated, design each branch to output "half of the output channels".
  • Adding SE and similar modules slows it down: the 2× model with SE lowered error by 0.5 points, but on the GPU it slowed from 217 to 161 batches per second.

The guidelines and speed comparisons in the paper were measured with implementations optimized by the authors on a GTX 1080Ti and a Snapdragon 810. The paper itself notes that actual MAC deviates from the theoretical value depending on cache size and library optimizations. For example, 0.25 MobileNet (V1) turns out faster on the GPU than ShuffleNet V2 0.5×, which has fewer FLOPs. Measure the actual runtime on your target device and framework before choosing.

torchvision's shufflenet_v2_x0_5, x1_0, x1_5, and x2_0 correspond to the four sizes in Table 5 of the paper. Weights trained on ImageNet can be loaded, so they can be used directly for fine-tuning.

Comparison with other models

The following compares ShuffleNet V2 with contemporary lightweight models in terms of the paper's four guidelines.

ModelBlock shape1×1 convolutionShortcutRelation to the guidelines
MobileNet (V1)depthwise → 1×1OrdinaryNoneLittle fragmentation, fast on GPU
MobileNetV2expand → depthwise → shrinkOrdinary (input/output widths differ)AdditionViolates G1 and G4
ShuffleNet (V1)1×1 group → shuffle → depthwise → 1×1 groupGroup convolutionAdditionViolates G1, G2, and G4
ShuffleNet V2split → 3 layers on one half → concat → shuffleOrdinary (equal input/output widths)Concatenates the split half as isSatisfies all four guidelines

In the small regime of about 40–140 MFLOPs, ShuffleNet V2 has 2–3.5 points lower error than ShuffleNet (V1) and runs as fast or faster on ARM.

As a rule of thumb:

  • To get high accuracy quickly with few FLOPs on smartphones or GPUs: ShuffleNet V2 is a strong choice. The gap over other models is especially large in the small regime of tens of MFLOPs.
  • To run fast on a GPU with the simplest possible structure: MobileNet (V1) is also an option, at the cost of accuracy.
  • To use a model searched with smartphone CPU latency as the criterion: also compare MnasNet and MobileNetV3. Whereas ShuffleNet V2 applies the guidelines by hand, these automatically search the architecture while measuring latency on real devices.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.models import shufflenet_v2_x1_0, ShuffleNet_V2_X1_0_Weights

"""
Build the ShuffleNet V2 unit exactly as in Figure 3(c)(d) of the paper.
torchvision's shufflenet_v2_x1_0 and related models are built-in models corresponding to the four sizes in Table 5 of the paper.
"""


def channel_shuffle(x, groups=2):
    # (N, g·n, H, W) → (N, g, n, H, W) → transpose → (N, g·n, H, W). V2 mixes two branches, so g = 2
    n_batch, ch, h, w = x.shape
    x = x.view(n_batch, groups, ch // groups, h, w).transpose(1, 2).contiguous()
    return x.view(n_batch, ch, h, w)


def conv_bn(c_in, c_out, k, stride=1, groups=1, relu=True):
    layers = [nn.Conv2d(c_in, c_out, k, stride, k // 2, groups=groups, bias=False), nn.BatchNorm2d(c_out)]
    if relu:
        layers.append(nn.ReLU(inplace=True))
    return nn.Sequential(*layers)


class ShuffleV2Unit(nn.Module):
    def __init__(self, c_in, c_out, stride):
        super().__init__()
        self.stride = stride
        half = c_out // 2                                   # Each branch outputs half of the output channels
        if stride == 2:                                     # Fig. 3(d): no split; feed the input to both branches
            self.branch1 = nn.Sequential(
                conv_bn(c_in, c_in, 3, stride=2, groups=c_in, relu=False),  # Depthwise (BN only)
                conv_bn(c_in, half, 1),                                      # 1×1 (BN, ReLU)
            )
            b2_in = c_in
        else:                                               # Fig. 3(c): pass half through unchanged
            assert c_in == c_out and c_in % 2 == 0
            b2_in = half
        self.branch2 = nn.Sequential(                       # All three have equal input/output channels (G1)
            conv_bn(b2_in, half, 1),                                         # 1×1 (not grouped: G2)
            conv_bn(half, half, 3, stride=stride, groups=half, relu=False),  # 3×3 depthwise (BN only)
            conv_bn(half, half, 1),                                          # 1×1 (BN, ReLU)
        )

    def forward(self, x):
        if self.stride == 1:
            x1, x2 = x.chunk(2, dim=1)                      # Channel split (c' = c/2)
            out = torch.cat([x1, self.branch2(x2)], dim=1)  # Concatenate instead of add
        else:
            out = torch.cat([self.branch1(x), self.branch2(x)], dim=1)  # Channel count doubles
        return channel_shuffle(out, 2)


unit = ShuffleV2Unit(116, 116, stride=1)
print(unit(torch.randn(1, 116, 28, 28)).shape)             # torch.Size([1, 116, 28, 28])
down = ShuffleV2Unit(116, 232, stride=2)
print(down(torch.randn(1, 116, 28, 28)).shape)             # torch.Size([1, 232, 14, 14])

# torchvision built-in (ShuffleNet V2 1×, ImageNet-trained weights)
model = shufflenet_v2_x1_0(weights=ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1)
model.eval()                                                # BN uses the running mean and variance accumulated during training
with torch.no_grad():
    print(model(torch.randn(1, 3, 224, 224)).shape)        # torch.Size([1, 1000])
model.train()                                               # During training, BN uses the mini-batch mean and variance

FAQ

Q. How does ShuffleNet V2 differ from ShuffleNet (V1)?
A.

V1 used group convolution for the 1×11 \times 1 layers and narrowed the width in a bottleneck to reduce FLOPs. Following four guidelines based on actual hardware speed, V2 switches the 1×11 \times 1 layers back to ordinary convolutions, keeps the input and output widths equal, and replaces the shortcut addition with "channel split and concatenation". The channel shuffle is kept to mix the two branches. In the overall architecture, one 1×11 \times 1 convolution is added before global average pooling.

Q. Isn't a model with fewer FLOPs always faster?
A.

Not necessarily. FLOPs do not include memory reads and writes (MAC), the degree of parallelism, or the time spent on element-wise operations. In the ShuffleNet V2 paper, even with FLOPs held fixed, increasing the number of groups from 1 to 8 made the GPU more than twice as slow, and splitting a block into four paths made it about three times slower. When choosing a model, measure the runtime on the target device.

Q. Why doesn't accuracy drop even though half the channels pass through untouched?
A.

The paper gives two reasons. One is that, because the unit is lightweight, more channels can be used for the same FLOPs. The other is "feature reuse": the passed-through channels are used again in the next unit. The number of channels directly connecting the ii-th and i+ji+j-th units is (1/2)jc(1/2)^j c, a DenseNet-like pattern where nearer layers are more strongly connected. Thanks to the channel shuffle, the passed-through channels also get convolved in subsequent units.

References

  1. Ma, N., Zhang, X., Zheng, H.-T., & Sun, J. (2018). ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design. Proceedings of the European Conference on Computer Vision (ECCV), 116–131. arXiv:1807.11164.
  2. Zhang, X., Zhou, X., Lin, M., & Sun, J. (2018). ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices. CVPR 2018. arXiv:1707.01083.
  3. Sandler, M., Howard, A., Zhu, M., Zhmoginov, A., & Chen, L.-C. (2018). MobileNetV2: Inverted Residuals and Linear Bottlenecks. CVPR 2018. arXiv:1801.04381.
  4. PyTorch. torchvision.models.shufflenet_v2_x1_0.