AI Logic

Architectures

MnasNet

Updated:

MnasNet architecture. Left: the overall flow of the searched MnasNet-A1 (3×3 convolution, SepConv, MBConv in 6 blocks, pooling, fully connected layer). Right: the search loop (a controller samples a model, computes a reward from the trained accuracy and the latency measured on a smartphone, and is updated), the choices made per block, and the inside of an MBConv layer

Background and overview

MnasNet is a lightweight convolutional neural network whose architecture, with a good balance between accuracy and speed, was found automatically by neural architecture search (NAS) that builds latency actually measured on a smartphone into the search objective. It was proposed by Tan et al. at Google Brain in 2018 and presented at CVPR 2019. The name stands for "Mobile Neural Architecture Search".

Models for smartphones need to be small, fast, and accurate. When people design them by hand, as with MobileNetV2, there are far too many possible architectures to strike this balance manually. Automatic searches such as NASNet, on the other hand, either optimized accuracy alone or used computation (FLOPs) as a stand-in for speed. Computation, however, is a poor proxy for speed. For example, MobileNet and NASNet have nearly the same computation (575M vs. 564M), yet their latencies on a smartphone differ greatly: 113 ms vs. 183 ms.

MnasNet tackles this problem with two ideas.

  • Put measured latency into the reward: Each model sampled during the search is run on a real smartphone (Pixel 1) to measure its latency, and the search is driven by a reward that combines latency with accuracy.
  • A search space that allows different layers in each block: Instead of repeating the same cell, the network is split into several blocks, and the layer type is chosen for each block.

The main results of the paper are as follows.

  • On ImageNet, MnasNet-A1 reaches 75.2% top-1 accuracy with 78 ms latency on a Pixel 1. It is 1.8 times faster than MobileNetV2 (1.4× width) with 0.5 points higher accuracy, and 2.3 times faster than NASNet-A with 1.2 points higher accuracy.
  • The slightly larger MnasNet-A3 achieves higher accuracy than ResNet-50 (76.7%) with 4.8 times fewer parameters and 10 times less computation.
  • In object detection on COCO, it also gives higher mAP than MobileNet (V1 and V2) backbones.

MnasNet's search method and block design became the starting point for later models such as MobileNetV3 and EfficientNet.

Theory: search with real-device latency

The MnasNet search consists of three parts: the objective function, the search space, and the search procedure. In the figure at the top of this article, the upper right shows the search loop and the lower right shows the search space.

Objective: multiply accuracy by latency

Let ACC(m)\mathrm{ACC}(m) be the accuracy of model mm, LAT(m)\mathrm{LAT}(m) its latency on a smartphone, and TT the target latency. If latency is made a hard constraint ("at most TT") and only accuracy is maximized, each search yields just one answer. MnasNet therefore maximizes the following value (Eqs. 2 and 3 of the paper).

ACC(m)×[LAT(m)T]w,w={α(LAT(m)≤T)β(otherwise)\mathrm{ACC}(m) \times \left[ \frac{\mathrm{LAT}(m)}{T} \right]^{w}, \qquad w = \begin{cases} \alpha & (\mathrm{LAT}(m) \leq T) \\ \beta & (\text{otherwise}) \end{cases}

Since ww is negative, the value shrinks as latency grows. Based on the empirical observation that "doubling latency raises accuracy by about 5% in relative terms", the paper chooses β≈−0.07\beta \approx -0.07 so that two such models receive the same reward, and uses α=β=−0.07\alpha = \beta = -0.07. The target latency then becomes a "soft constraint": a model slightly slower than the target still scores well if its accuracy is high enough. In this way, a single search collects several good models with different accuracy-latency trade-offs (models close to Pareto optimal). Setting α=0\alpha = 0 and β=−1\beta = -1 gives a "hard constraint" that heavily penalizes models exceeding the target.

Search space: choose layers per block

MnasNet divides the network into 7 blocks that reduce spatial size while increasing the number of channels, and for each block ii it chooses the following (Figure 4 of the paper).

  • Convolution type: regular convolution, depthwise convolution, or the MobileNetV2 inverted residual block (MBConv)
  • Kernel size: 3×33 \times 3 or 5×55 \times 5
  • SE ratio: 0 or 0.25
  • Shortcut: pooling, identity residual, or none
  • Output channels FiF_i: 0.75×, 1.0×, or 1.25× those of MobileNetV2
  • Number of layers NiN_i: −1-1, 00, or +1+1 relative to MobileNetV2

Within a block, the same layer is repeated NiN_i times, but different blocks may use different layers. The paper argues that being able to choose suitable layers for each block matters because earlier blocks process more data and have a larger effect on latency. With BB blocks, SS choices per block, and NN layers per block, the search space shrinks from SB⋅NS^{B \cdot N} (choosing per layer) to SBS^B (with S=432S = 432, B=5B = 5, N=3N = 3, from about 103910^{39} to about 101310^{13}).

Search procedure

The search uses the same reinforcement learning framework as NASNet and repeats the following steps (Figure 1 and Section 4.2 of the paper).

  1. An RNN "controller" outputs a sequence of tokens describing an architecture, and a model is sampled.
  2. The sampled model is trained on ImageNet for only 5 epochs, and its accuracy is measured on 50,000 held-out images.
  3. The same model is run on the CPU of a Pixel 1 (one big core) to measure its latency.
  4. The reward is computed with the equation above, and the controller is updated with PPO (Proximal Policy Optimization) to maximize the expected reward.

One search tries about 8,000 models and takes 4.5 days on 64 TPUv2 devices. Only the top 15 are trained to completion on ImageNet.

Searching on a small dataset (such as CIFAR-10) and transferring to a large dataset does not work well when latency matters. Transferring to a larger task requires scaling up the model, which changes its latency. MnasNet therefore searches directly on ImageNet.

Overall architecture

The searched MnasNet-A1 is built mainly from the same inverted residual block (MBConv) as MobileNetV2, with the expansion ratio, kernel size, and use of SE differing from block to block. The left side of the figure at the top of this article shows the overall flow.

An image flows through the following stages (for a 224×224 ImageNet image; Figure 7(a) of the paper).

BlockLayerRepeatsOutput shape
First3×33 \times 3 convolution (stride 2)1112×112×32
1SepConv (3×33 \times 3)1112×112×16
2MBConv6 (3×33 \times 3)256×56×24
3MBConv3 (5×55 \times 5) + SE328×28×40
4MBConv6 (3×33 \times 3)414×14×80
5MBConv6 (3×33 \times 3) + SE214×14×112
6MBConv6 (5×55 \times 5) + SE37×7×160
7MBConv6 (3×33 \times 3)17×7×320
LastPooling and fully connected layer11000 classes

The number after MBConv is how many times the block expands the number of channels internally (the expansion ratio). Each layer has the following form (Figure 7(b)(c) of the paper).

  1. A 1×11 \times 1 convolution (BN, ReLU) expands the channels by 3 or 6 times.
  2. A 3×33 \times 3 or 5×55 \times 5 depthwise convolution (BN, ReLU) is applied.
  3. In layers with SE, SE is applied here (pooling → fully connected → ReLU → fully connected → sigmoid → multiply per channel).
  4. A 1×11 \times 1 convolution (BN, no activation) restores the original number of channels.
  5. When the input and output shapes match, the input is added.

The first SepConv is a layer consisting only of a 3×33 \times 3 depthwise convolution (BN, ReLU) and a 1×11 \times 1 convolution (BN).

The paper highlights that both 3×33 \times 3 and 5×55 \times 5 kernels are used. Earlier mobile models used only 3×33 \times 3. For depthwise convolution, the computation is H⋅W⋅M⋅(K2+N)H \cdot W \cdot M \cdot (K^2 + N) (KK is the kernel size, MM and NN are the input and output channels), so increasing KK adds little computation when NN is large.

The ImageNet training settings are as follows (Section 5 of the paper).

ItemValue
OptimizerRMSprop (decay 0.9, momentum 0.9)
Learning rateRaised from 0 to 0.256 over the first 5 epochs (warmup), then multiplied by 0.97 every 2.4 epochs
Batch size4096
RegularizationWeight Decay 1e-5, Dropout 0.2 on the last layer
BNAfter every convolution, momentum 0.99
PreprocessingInception preprocessing, 224×224

Why it works

The paper confirms that each of MnasNet's two ideas (the objective function and the search space) contributes.

Effect of the objective and the search space (ImageNet; Table 5 of the paper)

RewardSearch spaceLatencyTop-1 accuracy
Accuracy onlyNASNet cell183 ms74.0%
Accuracy and latencyNASNet cell100 ms72.0%
Accuracy and latencyMnasNet blocks78 ms75.2%

Adding latency to the reward while keeping the NASNet search space finds faster models, but at the cost of accuracy. Switching to the MnasNet search space as well improves both speed and accuracy.

Effect of layer diversity (Table 6 of the paper; same number of layers and channels, with every layer set to a single type)

ModelTop-1 accuracyLatency
MnasNet-A175.2%78 ms
MBConv3 (3×33 \times 3) only71.8%63 ms
MBConv3 (5×55 \times 5) only72.5%79 ms
MBConv6 (3×33 \times 3) only74.9%116 ms
MBConv6 (5×55 \times 5) only75.6%146 ms

With a single layer type, the fast variants are less accurate and the accurate variants are slow. MnasNet-A1, which can vary the layer by block, sits at a good point in between. In cooking terms, it is like automatically finding a plan that handles the time-consuming prep work (the high-resolution early stages) with quick methods and spends more effort on the finishing touches (the later stages).

Soft and hard constraints (Figure 6 of the paper): With a target latency of 75 ms, the hard constraint (α=0\alpha = 0, β=−1\beta = -1) led the controller to avoid penalties and try only fast models. With the soft constraint (α=β=−0.07\alpha = \beta = -0.07), it explored widely around 75 ms, including models faster than 40 ms and slower than 110 ms, so several models with different latencies (A1, A2, A3) could be picked from a single search.

Experimental results

Comparison on ImageNet (latency on a big core of the Pixel 1 CPU, batch size 1; excerpt from Table 1 of the paper)

ModelDesignParametersComputation (multiply-adds)Top-1 accuracyLatency
MobileNet (V1)Manual4.2M575M70.6%113 ms
MobileNetV2Manual3.4M300M72.0%75 ms
MobileNetV2 (1.4×)Manual6.9M585M74.7%143 ms
NASNet-AAutomatic5.3M564M74.0%183 ms
AmoebaNet-AAutomatic5.1M555M74.5%190 ms
MnasNet-A1Automatic3.9M312M75.2%78 ms
MnasNet-A2Automatic4.8M340M75.6%84 ms
MnasNet-A3Automatic5.2M403M76.7%103 ms

The target latency is set to T=75T = 75 ms, about the same as MobileNetV2. MnasNet-A1 is 3.2 points more accurate than MobileNetV2 at nearly the same latency.

Without SE (Table 2 of the paper): MnasNet-B1, searched with SE removed from the search space, also reaches 74.5% at 77 ms, beating MobileNetV2 (75 ms, 72.0%) and NASNet (183 ms, 74.0%).

Scaling the model (Figure 5 of the paper): Whether the width multiplier is varied from 0.35 to 1.4 or the input size from 96 to 224, MnasNet-A1 is more accurate than MobileNetV2 in every setting; when the input size is varied, the gap reaches up to 4.1 points.

Width multiplier0.350.50.751.01.4
MnasNet-A164.1%68.9%73.3%75.2%77.2%
MobileNetV260.3%65.4%69.8%72.0%74.7%

Searching again for a new target (Table 4 of the paper): Models found by a new search targeting 22 ms latency are more accurate (64.9% at 22.0 ms, 66.0% at 23.2 ms) than MnasNet-A1 thinned to 0.35× (22.8 ms, 64.1%).

Object detection (COCO test-dev2017, SSDLite, a lightweight version of SSD, with 320×320 input; Table 3 of the paper)

ModelParametersComputation (multiply-adds)mAPLatency
SSD30036.1M35.2B23.2−
MobileNet (V1) + SSDLite5.1M1.3B22.2270 ms
MobileNetV2 + SSDLite4.3M0.8B22.1200 ms
MnasNet-A1 + SSDLite4.9M0.8B23.0203 ms

SSDLite with a MnasNet-A1 backbone achieves nearly the same mAP as the standard SSD300 with 7.4 times fewer parameters and 42 times less computation.

Practical considerations

Keep the following points in mind when using MnasNet.

  • The searched architecture is tuned to the device it was searched on: MnasNet-A1 was selected based on latency on the Pixel 1 CPU. It is not guaranteed to be equally fast on other devices.
  • Rerunning the search requires large compute resources: The paper's search took 4.5 days on 64 TPUv2 devices. In most cases, use a found model such as MnasNet-A1 as is and adjust its size with the width multiplier.
  • Size can be changed with the width multiplier and input size: In the paper, MnasNet stays more accurate than MobileNetV2 whether scaled by the same width multipliers (0.35–1.4) or input sizes (96–224) as MobileNetV2.

torchvision's mnasnet0_5, mnasnet0_75, mnasnet1_0, and mnasnet1_3 use the architecture of MnasNet-B1, which has no SE, and differ from MnasNet-A1 in Table 1 of the paper. They also have a 1280-channel 1×11 \times 1 convolution before pooling. The ImageNet accuracy of torchvision's mnasnet1_0 is 73.456%, lower than the paper's A1 (75.2%). When comparing against the paper's A1 numbers, check which architecture you are using.

MnasNet's search method was later used to search the architecture of MobileNetV3 (the block-wise search) and the baseline model EfficientNet-B0 of EfficientNet. EfficientNet-B0 was searched in the same search space as MnasNet, but with computation instead of latency in the objective.

Comparison with other models

The table below compares MnasNet with earlier and later mobile models, focusing on how their architectures were determined. Accuracy is ImageNet top-1 and latency is on a Pixel 1 (MobileNetV2 and NASNet from Table 1 of the MnasNet paper, MobileNetV3 from the MobileNetV3 paper).

ModelHow the architecture was determinedSearch unitTreatment of speedAccuracyLatency
MobileNetV2Designed by hand−Designed with computation in mind72.0%75 ms
NASNet-AReinforcement-learning NASRepeated identical cellIgnored (accuracy only)74.0%183 ms
MnasNet-A1Reinforcement-learning NASLayers chosen per blockReal-device latency in the reward75.2%78 ms
MobileNetV3-LargeMnasNet search + NetAdapt + manual refinementsBlocks, plus channels per layerReal-device latency75.2%51 ms

Latency measurement differs between papers; in the MobileNetV3 paper's measurements, MnasNet-A1 runs at 71 ms. Measured under the same conditions, MobileNetV3-Large is about 30% faster than MnasNet-A1.

MnasNet searches architectures with reinforcement learning, but other search methods exist. For example, DARTS replaces the choice of operations with continuous weights and searches the architecture by gradient descent.

A rough guide to choosing:

  • You want higher accuracy than MobileNetV2 at nearly the same speed on a smartphone: MnasNet-A1 is a candidate.
  • You want even more speed: Use MobileNetV3, which builds on MnasNet's method.
  • You have compute to spare and prioritize accuracy: Consider EfficientNet, which scales up a model found in MnasNet's search space.
  • You want to search for your own device: MnasNet's idea (putting measured latency into the reward) applies. The search needs large compute resources, though, so also compare other search methods such as DARTS and ProxylessNAS.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.models import mnasnet1_0, MNASNet1_0_Weights

"""
Build the MnasNet-A1 layers (MBConv, SE) and full model as in Figure 7 of the paper.
torchvision's mnasnet1_0 and related models use the MnasNet-B1 architecture without SE (different from the paper's A1).
"""


class SE(nn.Module):
    # pooling -> fully connected -> ReLU -> fully connected -> sigmoid -> multiply per channel (Fig. 7(b))
    def __init__(self, ch, squeeze_ch):
        super().__init__()
        self.fc = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Conv2d(ch, squeeze_ch, 1), nn.ReLU(inplace=True),
                                nn.Conv2d(squeeze_ch, ch, 1), nn.Sigmoid())

    def forward(self, x):
        return x * self.fc(x)


class MBConv(nn.Module):
    def __init__(self, c_in, c_out, k, stride, expand, se=False):
        super().__init__()
        mid = c_in * expand
        layers = [nn.Conv2d(c_in, mid, 1, bias=False), nn.BatchNorm2d(mid), nn.ReLU(inplace=True),   # expand
                  nn.Conv2d(mid, mid, k, stride, k // 2, groups=mid, bias=False), nn.BatchNorm2d(mid),
                  nn.ReLU(inplace=True)]                                                         # depthwise
        if se:
            layers.append(SE(mid, max(1, int(c_in * 0.25))))     # SE ratio 0.25
        layers += [nn.Conv2d(mid, c_out, 1, bias=False), nn.BatchNorm2d(c_out)]                  # project (linear)
        self.body = nn.Sequential(*layers)
        self.use_res = stride == 1 and c_in == c_out              # add the input only when shapes match

    def forward(self, x):
        out = self.body(x)
        return x + out if self.use_res else out


def mnasnet_a1(num_classes=1000):
    # (expansion, kernel, out channels, repeats, first stride, SE): blocks 2-7 of Fig. 7(a)
    cfg = [(6, 3, 24, 2, 2, False), (3, 5, 40, 3, 2, True), (6, 3, 80, 4, 2, False),
           (6, 3, 112, 2, 1, True), (6, 5, 160, 3, 2, True), (6, 3, 320, 1, 1, False)]
    layers = [nn.Conv2d(3, 32, 3, 2, 1, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True),
              # block 1: SepConv (3x3 depthwise -> 1x1)
              nn.Conv2d(32, 32, 3, 1, 1, groups=32, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True),
              nn.Conv2d(32, 16, 1, bias=False), nn.BatchNorm2d(16)]
    c = 16
    for e, k, c_out, n, s, se in cfg:
        for i in range(n):
            layers.append(MBConv(c, c_out, k, s if i == 0 else 1, e, se))
            c = c_out
    return nn.Sequential(*layers, nn.AdaptiveAvgPool2d(1), nn.Flatten(),
                         nn.Dropout(0.2), nn.Linear(c, num_classes))   # Dropout 0.2 on the last layer


model = mnasnet_a1()
model.eval()                                     # disable Dropout; BN uses the stored mean and variance
with torch.no_grad():
    print(model(torch.randn(1, 3, 224, 224)).shape)   # torch.Size([1, 1000])

# torchvision built-in (MnasNet-B1 architecture, width 1.0)
tv = mnasnet1_0(weights=MNASNet1_0_Weights.IMAGENET1K_V1)
tv.eval()

FAQ

Q. How is latency measured in the MnasNet search?
A.

Each model sampled during the search is run on one big core of the CPU of a real smartphone (Pixel 1), and the latency per image is measured. Rather than estimating latency from computation (FLOPs), the measured value is plugged into the reward ACC(m)×[LAT(m)/T]w\mathrm{ACC}(m) \times [\mathrm{LAT}(m)/T]^{w}. The paper notes that hardware and software quirks made latency hard to approximate with an estimate.

Q. What is the difference between MnasNet-A1 and MnasNet-B1?
A.

The difference is whether SE was included in the search space. A1 was searched with SE and reaches 75.2% ImageNet accuracy (78 ms). B1 was searched without SE and reaches 74.5% (77 ms). torchvision's mnasnet1_0 and related models use the B1 architecture.

Q. How are MnasNet and MobileNetV3 related?
A.

MobileNetV3 searches its block structure with the same method as MnasNet (reinforcement-learning search with measured latency in the reward), then trims the channels per layer with NetAdapt and adds manual changes such as h-swish. MobileNetV3-Large has the same accuracy as MnasNet-A1 (75.2%), and in the MobileNetV3 paper's measurements on a Pixel 1 its latency is 51 ms versus 71 ms for MnasNet-A1.

References

  1. Tan, M., Chen, B., Pang, R., Vasudevan, V., Sandler, M., Howard, A., & Le, Q. V. (2019). MnasNet: Platform-Aware Neural Architecture Search for Mobile. Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2820–2828. arXiv:1807.11626.
  2. Zoph, B., Vasudevan, V., Shlens, J., & Le, Q. V. (2018). Learning Transferable Architectures for Scalable Image Recognition. CVPR 2018. arXiv:1707.07012.
  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.mnasnet1_0.