AI Logic

Architectures

MobileNetV3

Updated๏ผš

Structure of MobileNetV3-Large. The left side shows the overall flow (a 3ร—3 convolution, 15 blocks in 5 stages, a 1ร—1 convolution, global average pooling, and two 1ร—1 convolutions); the right side shows the inside of a block (1ร—1 expansion, depthwise convolution, SE, and 1ร—1 projection with the input added), the inside of SE, and the formulas for h-swish and hard-sigmoid

Background and Overview

MobileNetV3 is a lightweight convolutional neural network that adds SE, which reweights channels, and h-swish, an activation function that is fast to compute, to the MobileNetV2 block, and determines the overall shape by automated search guided by speed measured on a smartphone. It was proposed by Howard et al. at Google in 2019.

MobileNet (V1) and MobileNetV2 were designed by hand. MobileNetV3 determines its skeleton with neural architecture search (NAS), a method that searches for network structures automatically, and then manually fixes parts that the search has difficulty finding. The paper proposes two models: MobileNetV3-Large for devices with more resources and MobileNetV3-Small for devices with fewer.

The main results of the paper are as follows (measured on one core of a Google Pixel 1 smartphone).

  • MobileNetV3-Large is 3.2 points more accurate than MobileNetV2 on ImageNet (75.2% vs. 72.0%), with latency of 51 ms vs. 64 ms, about 20% lower.
  • MobileNetV3-Small is 6.6 points more accurate than MobileNetV2 (width 0.35) at similar latency (67.4% vs. 60.8%).
  • For object detection it is more than 25% faster than MobileNetV2 at nearly the same accuracy, and for semantic segmentation, combined with a new lightweight head (LR-ASPP), it is 34% faster at similar accuracy.

Theory: Search and Manual Improvements

MobileNetV3 is built in two stages: architecture search and manual improvements.

1. Determining the skeleton by search

  1. Block-wise search: A NAS that takes real-device latency into account decides the type of each block (filter size, expansion factor, whether to use SE, and so on). For Large, MnasNet-A1, already found by the same method, is used as the starting point as-is. For Small, a new search is run with the reward weight changed for small models.
  2. Layer-wise tuning (NetAdapt): Starting from the seed model, candidate changes that slightly reduce latency are generated, each is briefly retrained and compared, and the best candidate is selected; this repeats until the target latency is reached. There are two kinds of candidate changes: reducing the channel count of a block's expanded layer, and jointly reducing the channel count of the narrow layers of blocks connected at the same width.
  3. Once the target latency is reached, the resulting structure is retrained from scratch.

The search reward uses the accuracy ACC(m)\mathrm{ACC}(m) and latency LAT(m)\mathrm{LAT}(m) of model mm and the target latency TAR\mathrm{TAR}, in the following form (the same form as MnasNet).

ACC(m)ร—[LAT(m)TAR]w\mathrm{ACC}(m) \times \left[ \frac{\mathrm{LAT}(m)}{\mathrm{TAR}} \right]^{w}

Because accuracy changes more sharply with latency in small models, the Small search uses w=โˆ’0.15w = -0.15 (MnasNet uses w=โˆ’0.07w = -0.07). In NetAdapt, each step selects the candidate with the largest ฮ”Accโˆฃฮ”latencyโˆฃ\frac{\Delta \mathrm{Acc}}{|\Delta \mathrm{latency}|} (change in accuracy per unit reduction in latency).

2. Manual improvements

The following four changes, outside the search space, were added.

  • Lighter last stage: In MobileNetV2, the final 1ร—1 convolution (1280 channels) was computed on a 7ร—7 feature map. MobileNetV3 moves this layer after average pooling so that it is computed at 1ร—1 size. This makes the depthwise convolution and projection layer of the preceding block unnecessary, so they were removed. Accuracy barely changed, while latency dropped by 7 ms (11% of the total) and computation by 30 million multiply-adds.
  • Lighter first layer: The number of filters in the first 3ร—3 convolution was reduced from 32 to 16, with h-swish as the activation. Accuracy was unchanged, saving 2 ms and 10 million multiply-adds.
  • Using h-swish: An activation function that is fast to compute, described below, is used in the second half of the network.
  • Larger SE: The inner width of SE was fixed at 1/4 of the channel count of the expanded layer. Parameters increase slightly, but accuracy improves with almost no change in latency.

3. Inside a block

A MobileNetV3 block is the inverted residual block of MobileNetV2 with the SE (Squeeze-and-Excitation) of SENet added (the same shape as MnasNet).

  1. A 1ร—11 \times 1 convolution expands the channels, followed by batch normalization (BN) and an activation function (ReLU in the first half, h-swish in the second half).
  2. A 3ร—33 \times 3 or 5ร—55 \times 5 depthwise convolution is applied, followed by BN and the activation function.
  3. In blocks that use SE, per-channel weights are computed and multiplied in.
    • The global average reduces each channel to a single value, which passes through a fully connected layer (1/4 width, ReLU) and a fully connected layer (original width, hard-sigmoid) to produce weights between 0 and 1.
  4. A 1ร—11 \times 1 convolution projects back, followed by BN (no activation function).
  5. Only when the stride is 1 and the input and output have the same number of channels is the input added.

A distinctive feature is that SE is placed not at the end of the block, as when it is added to ResNet, but after the depthwise convolution (where the channel count is largest).

h-swish: A Fast-to-Compute Swish

h-swish is an activation function that replaces the sigmoid function inside Swish with a piecewise-linear function built from ReLU6.

Swish was known to improve accuracy when used in place of ReLU.

swish(x)=xโ‹…ฯƒ(x)\mathrm{swish}(x) = x \cdot \sigma(x)

However, the sigmoid function ฯƒ\sigma involves an exponential, which is slow to compute on smartphones. The paper therefore approximates the sigmoid with the following piecewise-linear function (hard-sigmoid).

h-sigmoid(x)=ReLU6(x+3)6,ReLU6(x)=minโก(maxโก(x,0),6)\text{h-sigmoid}(x) = \frac{\mathrm{ReLU6}(x + 3)}{6}, \qquad \mathrm{ReLU6}(x) = \min(\max(x, 0), 6)

h-sigmoid is 0 for xโ‰คโˆ’3x \le -3, 1 for xโ‰ฅ3x \ge 3, and linear in between. The approximation of Swish built from it is h-swish.

h-swish(x)=xโ‹…ReLU6(x+3)6\text{h-swish}(x) = x \cdot \frac{\mathrm{ReLU6}(x + 3)}{6}

The paper lists the following advantages of this replacement.

  • Fast on any device: Optimized implementations of ReLU6 exist in almost all software and hardware.
  • Little accuracy loss under quantization: It eliminates numerical discrepancies in integer computation caused by different implementations approximating the sigmoid in different ways.
  • No change in accuracy: In the paper's experiments, replacing sigmoid and Swish with h-sigmoid and h-swish made no noticeable difference in accuracy.

In addition, h-swish is used only in the second half of the network (from the 80-channel stage onward). Each time the resolution drops, the memory of the feature maps roughly halves, so the cost of the activation function is smaller in deeper layers, and most of the benefit of Swish was obtained in the deeper layers alone. The gate inside SE also uses h-sigmoid instead of the sigmoid function.

In PyTorch, h-swish is built in as nn.Hardswish and h-sigmoid as nn.Hardsigmoid, both with the same formulas as the paper.

Overall Architecture

MobileNetV3-Large and MobileNetV3-Small use the same types of blocks but differ in the number of stages and channels. In the figure at the top of the article, the left side shows the overall flow of Large and the right side shows the inside of a block.

MobileNetV3-Large (for a 224ร—224 image; Table 1 of the paper)

Stage (output size)BlocksDepthwise filterOutput channelsSEActivation
First 3ร—3 conv (112ร—112)โˆ’โˆ’16โˆ’h-swish
112ร—11213ร—316NoReLU
56ร—5623ร—324NoReLU
28ร—2835ร—540YesReLU
14ร—1463ร—380 โ†’ 112Last 2h-swish
7ร—735ร—5160Yesh-swish
1ร—1 conv (7ร—7)โˆ’โˆ’960โˆ’h-swish
Average pooling โ†’ 1ร—1 conv (no BN)โˆ’โˆ’1280โˆ’h-swish
1ร—1 conv (no BN)โˆ’โˆ’Number of classesโˆ’โˆ’

There are 15 blocks in total. The channel count of the expanded layer differs from block to block (16 to 960), as a result of tuning with NetAdapt. In the first block of each stage, the depthwise convolution uses stride 2 to halve the height and width.

MobileNetV3-Small (Table 2 of the paper) has 11 blocks with fewer output channels, 16 โ†’ 24 โ†’ 40 โ†’ 48 โ†’ 96; its final 1ร—1 convolution has 576 channels and the layer after pooling has 1024 channels. It uses stride 2 from the very first block, and most blocks use SE and h-swish.

As with MobileNet (V1) and V2, the size can be tuned with the width multiplier and the input resolution. The paper tries width multipliers from 0.35 to 1.25 and inputs from 96 to 256.

The ImageNet training settings in the paper (partial) are as follows.

ItemValue
OptimizationRMSprop (momentum 0.9), synchronous on a 4ร—4 TPU Pod, batch size 4096
Learning rateStarts at 0.1 and is lowered in steps
Weight Decay0.00001
OtherExponential moving average of weights (decay 0.9999); batch normalization moving average decay 0.99

Experimental Results

ImageNet image classification (Table 3 of the paper; latency measured with TFLite on one core of a Google Pixel 1, batch size 1)

ModelAccuracy (top-1)Mult-adds (millions)ParametersLatency
V3-Large 1.075.2%2195.4M51 ms
V3-Large 0.7573.3%1554.0M39 ms
MnasNet-A175.2%3153.9M71 ms
ProxylessNAS74.6%3204.0M72 ms
MobileNetV2 1.072.0%3003.4M64 ms
V3-Small 1.067.4%562.5M15.8 ms
V3-Small 0.7565.4%442.0M12.8 ms
MnasNet-small64.9%65.11.9M20.3 ms
MobileNetV2 0.3560.8%59.21.6M16.6 ms

V3-Large matches the accuracy of its starting point, MnasNet-A1, at about 3/4 of the latency. When quantized to 8-bit integers, V3-Large also reached 73.8% (44 ms), surpassing MobileNetV2's 70.9% (52 ms) (Table 4).

Comparison of where to place activation functions (V3-Large, Table 5 of the paper; latency with an unoptimized h-swish implementation also shown)

SettingAccuracyLatencyLatency with unoptimized h-swish
V3-Large (h-swish from the 80-channel stage)75.2%51.4 ms57.5 ms
All ReLU74.5%50.5 ms50.5 ms
h-swish from the 16-channel stage75.4%53.5 ms68.9 ms
h-swish from the 112-channel stage75.0%51 ms54.4 ms

Using h-swish only in the second half gave 0.7 points higher accuracy than all ReLU, with about 1 ms of extra latency. The optimized implementation is 6 ms faster than the unoptimized one.

Object detection (COCO test-dev; used as the SSDLite backbone; Table 6 of the paper)

BackbonemAPLatencyParametersMult-adds (billions)
MobileNet (V1)22.2228 ms5.1M1.3
MobileNetV222.1162 ms4.3M0.80
MnasNet23.0174 ms4.88M0.84
MobileNetV3-Large22.0137 ms4.97M0.62
MobileNetV3-Large (second-half channels halved)22.0119 ms3.22M0.51
MobileNetV3-Small16.052 ms2.49M0.21
MobileNetV3-Small (second-half channels halved)16.143 ms1.77M0.16

Reasoning that the second-half layers designed for ImageNet's 1000 classes are too large for COCO's 90 classes, the authors halved their channel counts; mAP did not drop and latency fell by about 15%.

Practical Considerations

Keep the following points in mind when using MobileNetV3.

  • Choose Large or Small by target device and latency goal: In Figure 7 of the paper, Small was nearly 3 points more accurate than Large thinned with a width multiplier to the same performance. For a small latency target, use Small rather than thinning Large.
  • The second half can be thinned for detection and segmentation: For tasks with fewer classes than classification, halving the channel counts of the second-half layers barely reduced accuracy and made the model faster.
  • Use h-swish with an optimized implementation: In Table 5 of the paper, an unoptimized h-swish implementation was 6 ms slower than an optimized one. Check whether your framework can execute h-swish as a single operation.

The structure of MobileNetV3 was searched and tuned for latency on the CPU (one core) of a Google Pixel smartphone. On other hardware, such as GPUs or dedicated inference chips, it is not necessarily as fast. For example, 5ร—5 depthwise convolutions and SE can take time disproportionate to their computation on some devices. Measure latency on the target device before choosing a model.

torchvision's MobileNetV3 implements the 1ร—1 convolutions after pooling as fully connected layers (nn.Linear). A 1ร—1 convolution on a 1ร—1 feature map and a fully connected layer are the same computation.

Comparison with Other Models

The table below compares the three versions of MobileNet and MnasNet, the starting point of MobileNetV3. Accuracy values are for the standard size in each paper (width 1.0, 224ร—224).

ModelHow the structure was determinedBlock shapeActivationImageNet accuracy
MobileNet (V1)Hand-designedDepthwise โ†’ 1ร—1ReLU70.6%
MobileNetV2Hand-designedInverted residual (linear bottleneck)ReLU672.0%
MnasNet-A1NAS accounting for real-device latencyInverted residual + SEโˆ’75.2%
MobileNetV3-LargeNAS + NetAdapt + manual improvementsInverted residual + SE (1/4 width)ReLU and h-swish75.2%

MnasNet-A1 and MobileNetV3-Large have the same accuracy, but their latency on a Pixel 1 is 71 ms vs. 51 ms, so MobileNetV3-Large is about 30% faster (Table 3 of the paper).

Rough guidelines for choosing:

  • For the highest accuracy at the lowest latency on a smartphone CPU: Use MobileNetV3-Large. For something even lighter, use MobileNetV3-Small.
  • To run reliably across many devices and frameworks: MobileNetV2, which uses neither SE nor h-swish, can be easier to work with.
  • 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 MobileNetV3 block (Figure 4) following the formulas in the paper.
The full network is built into torchvision (shown at the end).
"""


def h_swish(x):
    # h-swish(x) = x ยท ReLU6(x + 3) / 6 (Section 5.2); same as nn.Hardswish
    return x * torch.clamp(x + 3, 0, 6) / 6


class SqueezeExcite(nn.Module):
    """Average pooling โ†’ FC (1/4, ReLU) โ†’ FC (hard-sigmoid) โ†’ multiply per channel"""

    def __init__(self, ch):
        super().__init__()
        self.pool = nn.AdaptiveAvgPool2d(1)
        self.fc1 = nn.Conv2d(ch, ch // 4, 1)    # inner width fixed at 1/4 of the expanded layer (Section 5.3)
        self.fc2 = nn.Conv2d(ch // 4, ch, 1)
        self.gate = nn.Hardsigmoid()            # ReLU6(x + 3) / 6

    def forward(self, x):
        w = self.gate(self.fc2(torch.relu(self.fc1(self.pool(x)))))
        return x * w


class V3Block(nn.Module):
    def __init__(self, in_ch, exp_ch, out_ch, kernel, stride, use_se, use_hs):
        super().__init__()
        act = nn.Hardswish if use_hs else nn.ReLU
        self.use_shortcut = stride == 1 and in_ch == out_ch
        layers = []
        if exp_ch != in_ch:                      # expanding 1ร—1 (omitted in blocks that do not expand)
            layers += [nn.Conv2d(in_ch, exp_ch, 1, bias=False), nn.BatchNorm2d(exp_ch), act()]
        layers += [
            nn.Conv2d(exp_ch, exp_ch, kernel, stride=stride, padding=kernel // 2, groups=exp_ch, bias=False),
            nn.BatchNorm2d(exp_ch),
            act(),
        ]
        if use_se:
            layers.append(SqueezeExcite(exp_ch))  # SE goes after the depthwise convolution
        layers += [nn.Conv2d(exp_ch, out_ch, 1, bias=False), nn.BatchNorm2d(out_ch)]  # linear (no activation)
        self.block = nn.Sequential(*layers)

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


# 5th block of the 14ร—14 stage in Table 1 (112 โ†’ 672 โ†’ 112, 3ร—3, with SE, h-swish)
block = V3Block(112, 672, 112, kernel=3, stride=1, use_se=True, use_hs=True)
block.eval()
with torch.no_grad():
    print(block(torch.randn(1, 112, 14, 14)).shape)   # torch.Size([1, 112, 14, 14])

# For the full network, use the torchvision built-in
from torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights, mobilenet_v3_small

model = mobilenet_v3_large(weights=MobileNet_V3_Large_Weights.IMAGENET1K_V1)  # weights=None gives random weights
small = mobilenet_v3_small(weights=None)
model.classifier[3] = nn.Linear(model.classifier[3].in_features, 10)  # replace the head for 10-class classification
model.train()   # during training, BN uses mini-batch statistics and the dropout before the classifier is active
model.eval()    # at inference, BN uses the accumulated statistics and dropout is inactive

FAQ

Q. How should I choose between MobileNetV3-Large and MobileNetV3-Small?
A.

Choose by latency target. In the paper's Pixel 1 measurements, Large reached 75.2% accuracy at 51 ms and Small 67.4% at 15.8 ms. The paper itself compares Small with small models at 20โ€“40 ms latency and Large with models at 40โ€“100 ms (Figure 1). For a small target, using Small rather than thinning Large gave nearly 3 points higher accuracy.

Q. Is h-swish less accurate than Swish?
A.

In the paper's experiments, replacing the sigmoid function and Swish with h-sigmoid and h-swish, respectively, made no noticeable difference in accuracy. h-swish is xโ‹…ReLU6(x+3)/6x \cdot \mathrm{ReLU6}(x+3)/6; since it uses no exponential, it is fast even on smartphones and causes few numerical discrepancies under quantization.

Q. Is MobileNetV3 a hand-designed model?
A.

Its skeleton was determined by automated search and then improved by hand. Large starts from MnasNet-A1, found by a NAS that accounts for real-device latency, and its per-layer channel counts were tuned with NetAdapt. On top of that, people made changes: lightening the first and last layers, using h-swish in the second half, and fixing the SE width at 1/4.

References

  1. Howard, A., Sandler, M., Chu, G., Chen, L.-C., Chen, B., Tan, M., Wang, W., Zhu, Y., Pang, R., Vasudevan, V., Le, Q. V., & Adam, H. (2019). Searching for MobileNetV3. Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 1314โ€“1324. arXiv:1905.02244.
  2. Sandler, M., Howard, A., Zhu, M., Zhmoginov, A., & Chen, L.-C. (2018). MobileNetV2: Inverted Residuals and Linear Bottlenecks. CVPR 2018. arXiv:1801.04381.
  3. Tan, M., Chen, B., Pang, R., Vasudevan, V., Sandler, M., Howard, A., & Le, Q. V. (2019). MnasNet: Platform-Aware Neural Architecture Search for Mobile. CVPR 2019. arXiv:1807.11626.
  4. PyTorch. torchvision.models.mobilenet_v3_large / torch.nn.Hardswish.