AI Logic

Architectures

MobileNetV2

Updated:

Structure of MobileNetV2. The left side shows the overall flow (a 3×3 convolution, 17 bottleneck blocks in 7 stages, a 1×1 convolution, global average pooling, and a 1×1 convolution as the classifier); the right side shows the inside of an inverted residual block (a stride-1 block that adds its input and a stride-2 block, and how the channel counts differ from a ResNet bottleneck)

Background and Overview

MobileNetV2 is a lightweight convolutional neural network for smartphones and similar devices that uses "inverted residuals", which connect layers with few channels through residual connections, and "linear bottlenecks", which place no activation function after those narrow layers. It was proposed by Sandler et al. at Google in 2018 as an improvement on MobileNet (V1).

MobileNet (V1) greatly reduced computation by replacing standard convolutions with depthwise separable convolutions. MobileNetV2 keeps this building block but changes the shape of the block so that it reaches similar accuracy with less computation and memory.

The main results of the paper are as follows.

  • Its ImageNet accuracy is 72.0%, above the 70.6% of MobileNet (V1). Computation is about half (300M vs. 575M multiply-adds), parameters are 3.4M vs. 4.2M, and latency on a smartphone (Google Pixel 1) is 75 ms vs. 113 ms.
  • For object detection, combined with "SSDLite", which also lightens the detection head, it achieved higher mAP than YOLOv2 with about 1/20 of the computation and about 1/10 of the parameters.
  • The peak memory that must be held during inference is about 1/4 that of MobileNet (V1).

The inverted residual block later became the basic building block of MnasNet and MobileNetV3.

Theory: Inverted Residuals and Linear Bottlenecks

A MobileNetV2 block first expands the small number of input channels, applies a depthwise convolution in the expanded space, and finally projects back to a small number of channels. The projected layer has no activation function, and a shortcut connects the narrow input and output layers.

Let the input be h×wh \times w with kk channels, the output have k′k' channels, the expansion factor be tt, and the stride be ss. One block (a bottleneck residual block) computes the following steps (Table 1 of the paper).

  1. Expand: A 1×11 \times 1 convolution expands kk channels to tktk channels, followed by batch normalization (BN) and ReLU6.
  2. Convolve spatially: A 3×33 \times 3 depthwise convolution (stride ss) is applied to each of the tktk channels, followed by BN and ReLU6. The output is hs×ws×tk\frac{h}{s} \times \frac{w}{s} \times tk.
  3. Project: A 1×11 \times 1 convolution projects back to k′k' channels, followed by BN. No activation function is placed here (linear bottleneck).
  4. Add: Only when the stride is 1 and the input and output have the same number of channels (k=k′k = k') is the input added as-is.

ReLU6 is ReLU with its output capped at 6. Because the range of values is fixed, it helps preserve accuracy even when computing with few bits.

ReLU6(x)=min⁡(max⁡(x,0),6)\mathrm{ReLU6}(x) = \min(\max(x, 0), 6)

The number of multiply-adds in one block is as follows.

h⋅w⋅k⋅t (k+32+k′)h \cdot w \cdot k \cdot t \,(k + 3^2 + k')

The term k+32+k′k + 3^2 + k' corresponds to the three layers: the expanding 1×11 \times 1, the depthwise 3×33 \times 3, and the projecting 1×11 \times 1. The block has one more 1×11 \times 1 layer than a MobileNet (V1) block, but because the channel counts at the block's entrance and exit (kk, k′k') can be much smaller, the total computation is lower.

The name inverted residual comes from the fact that the channel counts change in the opposite way to a ResNet bottleneck block.

BlockChannel patternLayers connected by the shortcut
ResNet bottleneckWide → narrow → wideWide layers
MobileNetV2 inverted residualNarrow → wide → narrowNarrow layers (bottlenecks)

The expansion factor tt is 6 in all of the paper's main experiments (1 only in the first stage). According to the paper, performance is nearly the same between 5 and 10, with slightly smaller factors working a little better for small models and slightly larger factors for large models.

Overall Architecture

MobileNetV2 starts with a 32-channel standard convolution followed by a stack of bottleneck residual blocks. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of a block.

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

Input shapeLayerExpansion ttOutput channelsRepeatsFirst stride
224×224×33×3 conv−3212
112×112×32Bottleneck11611
112×112×16Bottleneck62422
56×56×24Bottleneck63232
28×28×32Bottleneck66442
14×14×64Bottleneck69631
14×14×96Bottleneck616032
7×7×160Bottleneck632011
7×7×3201×1 conv−128011
7×7×12807×7 average pooling−−1−
1×1×12801×1 conv−Number of classes−−

Blocks in the same row share the same shape, and only the first block of each row uses stride 2. The first block of each row changes the number of channels or the spatial size, so it does not add its input.

As in MobileNet (V1), the model size can be tuned with the width multiplier and the input resolution. The paper varies the width multiplier from 0.35 to 1.4 and the input from 96 to 224, producing models with 1.7M to 6.9M parameters and up to 585M multiply-adds. One small difference from V1 is that even when the width multiplier is below 1, the last 1×1 convolution (1280 channels) is not thinned, because this improves the performance of small models.

The ImageNet training settings in the paper are as follows.

ItemValue
OptimizationRMSprop (decay and momentum both 0.9), asynchronous on 16 GPUs, batch size 96
Learning rateStarts at 0.045, multiplied by 0.98 every epoch
Weight Decay0.00004
NormalizationBatch normalization after every layer
OtherDropout during training

The text of the paper says "19 residual bottleneck layers", but the repeat counts in Table 2 add up to 17. Implementations such as torchvision build the network with 17 blocks, as in Table 2.

Why This Shape Works

The paper explains why the block shape works from two angles: information loss caused by ReLU and memory usage.

Activation functions destroy information

The set of outputs of a layer (the channel vectors at each pixel) has long been thought to lie in a subspace of lower dimension than the number of channels. The paper calls this the "manifold of interest". This is also why the width multiplier of MobileNet (V1) works: even with fewer channels, this low-dimensional information can still be represented.

However, applying ReLU to a layer with few channels turns negative values into 0, and the information along those directions is lost. The paper demonstrated this with an experiment (Figure 1) that embeds a 2D spiral into nn dimensions with a random matrix, applies ReLU, and projects it back to 2D. For n=2,3n = 2, 3, some points of the spiral collapsed onto each other and information was lost, but for n=15n = 15 to 3030 the shape was largely preserved.

From this, the paper derives two guidelines.

  • To apply a nonlinear transformation while preserving information, expand the channels first and then apply ReLU.
  • Do not apply ReLU to layers with few channels (bottlenecks).

This is what gives the block its shape: expand, apply the depthwise convolution and ReLU6, and keep the projected layer linear. If the wide layer is like spreading paint on a large palette to mix it and the narrow layer is like storing the mixed color in a small container, the point is to avoid spilling from the container while storing it (throwing away values with ReLU).

Experimental support (Figure 6 of the paper; values appear only in the graphs)

  • Models with ReLU6 in the projected layer had lower ImageNet accuracy than models that kept it linear.
  • Models with shortcuts "between narrow layers" performed better than models with shortcuts "between expanded layers" or with no shortcuts.

Less memory

During inference, the wide layer inside a block (tktk channels) is processed by the depthwise convolution and ReLU6, which work per channel, so it can be computed a few channels at a time and discarded immediately. As a result, only the narrow layers at the block's entrance and exit need to be held in memory in full. Table 3 of the paper gives the peak memory that must be held, counted with 16-bit floats, as follows.

ModelPeak memory required
MobileNet (V1)1,600 KB
ShuffleNet (2×, g=3g = 3)600 KB
MobileNetV2400 KB

On embedded devices with only a small, fast cache, fewer reads and writes to main memory translate into speed.

Experimental Results

ImageNet image classification (Table 4 of the paper; latency measured with TF-Lite on one core of a Google Pixel 1)

ModelAccuracy (top-1)ParametersMult-addsLatency
MobileNet (V1)70.6%4.2M575M113 ms
ShuffleNet (1.5)71.5%3.4M292M−
ShuffleNet (×2)73.7%5.4M524M−
NASNet-A74.0%5.3M564M183 ms
MobileNetV272.0%3.4M300M75 ms
MobileNetV2 (1.4)74.7%6.9M585M143 ms

Mult-adds is the number of multiply-adds. Latency is not listed for ShuffleNet because TF-Lite at the time could not run grouped convolutions and channel shuffle efficiently. MobileNetV2 with width multiplier 1.4 is more accurate than NASNet-A at nearly the same computation, and also faster.

Object detection (COCO test-dev, 320×320 input; Table 6 of the paper)

The paper proposed "SSDLite", which replaces all standard convolutions in the prediction layers of SSD with depthwise separable convolutions. For 80-class prediction, parameters drop from 14.8M to 2.1M and computation from 1.25B to 0.35B (Table 5).

ModelmAPParametersMult-addsLatency
SSD30023.236.1M35.2B−
SSD51226.836.1M99.5B−
YOLOv221.650.7M17.5B−
MobileNet (V1) + SSDLite22.25.1M1.3B270 ms
MobileNetV2 + SSDLite22.14.3M0.8B200 ms

Semantic segmentation (PASCAL VOC 2012 validation set, mIOU; used as the backbone of DeepLab v3, output stride 16, single-scale inference; Table 7 of the paper)

BackboneASPPmIOUParametersMult-adds
MobileNet (V1)Yes75.2911.15M14.25B
MobileNetV2Yes75.704.52M5.8B
MobileNetV2No75.322.11M2.75B
ResNet-101Yes80.4958.16M81.0B

For MobileNetV2, the DeepLab v3 head is attached not to the final 1280-channel layer but to the 320-channel feature map just before it. Removing ASPP (a module of parallel dilated convolutions) lowered mIOU only slightly while cutting computation by more than half.

Practical Considerations

Keep the following points in mind when using MobileNetV2.

  • Shortcuts only when shapes match: The input is added only in blocks where the input and output have the same number of channels and the stride is 1. The first block of each stage has no 1×1 projection shortcut like the one in ResNet.
  • Changing the expansion factor changes computation a lot: A block's computation is proportional to tt. The paper tunes model size with the width multiplier and input resolution and fixes the factor at 6.
  • For detection and segmentation, choose which layer to take features from: The paper attaches the first SSDLite layer to the expanded layer of the 15th block (output stride 16) and the DeepLab v3 head to the 320-channel layer. The 1280-channel layer exists for ImageNet classification.

The "no activation" of the linear bottleneck applies only to the last 1×1 convolution of the block. ReLU6 is applied after the expanding 1×1 and after the depthwise convolution. If, when building it yourself, you put an activation after every layer, or conversely remove all of them, the result differs from the paper's design. In the paper's experiments, adding ReLU6 to the projected layer lowered accuracy.

Even with low computation, actual speed depends on the device and implementation. In Table 4 of the paper, ShuffleNet (1.5), which needs less computation than MobileNetV2, has no latency measurement because grouped convolutions and channel shuffle did not run efficiently on TF-Lite at the time.

Comparison with Other Models

The table below compares MobileNetV2 with closely related lightweight models, focusing on the shape of their blocks.

ModelBlock shapeShortcutCharacteristics
MobileNet (V1)Depthwise → 1×1NoneSimple; ReLU also follows the 1×1 layer
ShuffleNet1×1 grouped convolution → shuffle → depthwise → 1×1 grouped convolutionBetween wide layersReduces 1×1 computation; grouped convolutions can be slow on real devices
MobileNetV21×1 expansion → depthwise → 1×1 projection (linear)Between narrow layersLow inference memory; built only from standard operations
MobileNetV3V2 block + SE + h-swishBetween narrow layersStructure found by network search and tuned for latency on real devices

Rough guidelines for choosing:

  • As a first backbone to try for image classification or detection on smartphones and similar devices: MobileNetV2 uses no special operations, so it is a standard choice that runs easily on many frameworks and devices. torchvision also provides pretrained weights.
  • For higher accuracy at the same latency: Use MobileNetV3.
  • When compute is plentiful and accuracy comes first: Consider larger models such as EfficientNet or ResNet.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
Build the MobileNetV2 inverted residual block as in Table 1 and Figure 4(d) of the paper.
The full network is built into torchvision (shown at the end).
"""


class InvertedResidual(nn.Module):
    """1×1 expansion → 3×3 depthwise → 1×1 projection (linear). Add the input only when shapes match"""

    def __init__(self, in_ch, out_ch, stride, expand_ratio=6):
        super().__init__()
        hidden = in_ch * expand_ratio            # the expansion factor t multiplies the input channels
        self.use_shortcut = stride == 1 and in_ch == out_ch
        layers = []
        if expand_ratio != 1:                    # when t = 1 the expansion layer is pointless, so omit it (as in torchvision)
            layers += [nn.Conv2d(in_ch, hidden, 1, bias=False), nn.BatchNorm2d(hidden), nn.ReLU6(inplace=True)]
        layers += [
            nn.Conv2d(hidden, hidden, 3, stride=stride, padding=1, groups=hidden, bias=False),  # depthwise convolution
            nn.BatchNorm2d(hidden),
            nn.ReLU6(inplace=True),
            nn.Conv2d(hidden, out_ch, 1, bias=False),  # projecting 1×1
            nn.BatchNorm2d(out_ch),                    # no activation function here (linear bottleneck)
        ]
        self.block = nn.Sequential(*layers)

    def forward(self, x):
        out = self.block(x)
        return x + out if self.use_shortcut else out


# Check: with stride 1 and equal channels, the input is added
block = InvertedResidual(32, 32, stride=1)
block.eval()                                     # BN uses the mean and variance accumulated during training
with torch.no_grad():
    print(block(torch.randn(1, 32, 28, 28)).shape)   # torch.Size([1, 32, 28, 28])

# For the full network (Table 2), use the torchvision built-in
from torchvision.models import mobilenet_v2, MobileNet_V2_Weights

model = mobilenet_v2(weights=MobileNet_V2_Weights.IMAGENET1K_V1)  # weights=None gives random weights
# width_mult changes the width multiplier (e.g. mobilenet_v2(width_mult=0.5); pretrained weights exist only for 1.0)
model.classifier[1] = nn.Linear(model.last_channel, 10)           # replace the head for 10-class classification
model.train()                                    # during training, BN uses mini-batch statistics and dropout is active

FAQ

Q. Why is it called an "inverted" residual?
A.

A ResNet bottleneck block has a "wide → narrow → wide" shape and connects the wide layers with a shortcut. A MobileNetV2 block has the opposite "narrow → wide → narrow" shape and connects the narrow layers, so it is called an inverted residual.

Q. Why is there no activation function after the last 1×1 convolution?
A.

Applying ReLU to a layer with few channels turns negative values into 0, and the information along those directions is lost. The paper regards the information as concentrated in the narrow layers and keeps them linear. In experiments, adding ReLU6 to the projected layer also lowered ImageNet accuracy.

Q. Why use ReLU6 instead of ReLU?
A.

With the output capped at 6, accuracy is easier to preserve even in computations that represent numbers with few bits (low-precision computation). The paper cites robustness in low-precision computation as the reason. The formula is ReLU6(x)=min⁡(max⁡(x,0),6)\mathrm{ReLU6}(x) = \min(\max(x, 0), 6).

References

  1. Sandler, M., Howard, A., Zhu, M., Zhmoginov, A., & Chen, L.-C. (2018). MobileNetV2: Inverted Residuals and Linear Bottlenecks. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 4510–4520. arXiv:1801.04381.
  2. Howard, A. G., Zhu, M., Chen, B., Kalenichenko, D., Wang, W., Weyand, T., Andreetto, M., & Adam, H. (2017). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications. arXiv:1704.04861.
  3. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  4. PyTorch. torchvision.models.mobilenet_v2.