M OBILE V I T: L IGHT - WEIGHT , G ENERAL - PURPOSE , AND M OBILE - FRIENDLY V ISION T RANSFORMER
Sachin Mehta Apple Mohammad Rastegari
Apple
A BSTRACT
Light-weight convolutional neural networks (CNNs) are the de-facto for mobile vision tasks.
Their spatial inductive biases allow them to learn representations with fewer parameters across different vision tasks.
However, these networks are spatially local.
To learn global representations, self-attention-based vision transformers (ViTs) have been adopted.
Unlike CNNs, ViTs are heavyweight.
In this paper, we ask the following question: is it possible to combine the strengths of CNNs and ViTs to build a light-weight and low latency network for mobile vision tasks?
Towards this end, we introduce MobileViT, a light-weight and general-purpose vision transformer for mobile devices.
MobileViT presents a different perspective for the global processing of information with transformers.
Our results show that MobileViT signiﬁcantly outperforms CNNand ViT-based networks across different tasks and datasets.
On the ImageNet-1k dataset, MobileViT achieves top-1 accuracy of 78.4% with about 6 million parameters, which is 3.2% and 6.2% more accurate than MobileNetv3 (CNN-based) and DeIT (ViT-based) for a similar number of parameters.
On the MS-COCO object detection task, MobileViT is 5.7% more accurate than MobileNetv3 for a similar number of parameters.
Our source code is open-source and available at: https://github.com/apple/ml-cvnets .
I NTRODUCTION
Self-attention-based models, especially vision transformers (ViTs; Figure 1a;
Dosovitskiy et al., 2021), are an alternative to convolutional neural networks (CNNs) to learn visual representations.
Brieﬂy, ViT divides an image into a sequence of non-overlapping patches and then learns interpatch representations using multi-headed self-attention in transformers (Vaswani et al., 2017).
The general trend is to increase the number of parameters in ViT networks to improve the performance (e.g., Touvron et al., 2021a; Graham et al., 2021; Wu et al., 2021).
However, these performance improvements come at the cost of model size (network parameters) and latency.
Many real-world applications (e.g., augmented reality and autonomous wheelchairs) require visual recognition tasks (e.g., object detection and semantic segmentation) to run on resource-constrained mobile devices in a timely fashion.
To be effective, ViT models for such tasks should be light-weight and fast.
Even if the model size of ViT models is reduced to match the resource constraints of mobile devices, their performance is signiﬁcantly worse than light-weight CNNs.
For instance, for a parameter budget of about 5-6 million, DeIT (Touvron et al., 2021a) is 3% less accurate than MobileNetv3 (Howard et al., 2019).
Therefore, the need to design light-weight ViT models is imperative.
Light-weight CNNs have powered many mobile vision tasks.
However, ViT-based networks are still far from being used on such devices.
Unlike light-weight CNNs that are easy to optimize and integrate with task-speciﬁc networks, ViTs are heavy-weight (e.g., ViT-B/16 vs. MobileNetv3:vs. 7.5 million parameters), harder to optimize (Xiao et al., 2021), need extensive data augmentation and L2 regularization to prevent over-ﬁtting (Touvron et al., 2021a; Wang et al., 2021), and require expensive decoders for down-stream tasks, especially for dense prediction tasks.
For instance, a ViT-based segmentation network (Ranftl et al., 2021) learns about 345 million parameters and achieves similar performance as the CNN-based network, DeepLabv3 (Chen et al., 2017), with 59 million parameters.
The need for more parameters in ViT-based models is likely because they lack image-speciﬁc inductive bias, which is inherent in CNNs (Xiao et al., 2021).
To build robust and high-performing ViT models, hybrid approaches that combine convolutions and transformers
[Figure]
3 P
[Figure]
Linear N d ⊕
Positional encoding
Transformer
L ×
Linear
Logits
[Figure] [Figure]
MobileViT block
[Figure]
representations
TransformersasConvolutions (globalrepresentations)
Fusion
W H
C X
Conv- n × n (cid:121) Conv-1x
W H d
P
N d
Transformer L ×
P
N d
W H d
Conv-1x
W H
C W H 2 C
Conv- n × n
W H
C Y
Unfold
Fold
[Figure] [Figure]
MV
MV2 ↓
MV 2 ×
MV2 ↓
MobileViTblock
L = h = w =
MV2 ↓
MobileViTblock
L = h = w =
MV2 ↓
MobileViTblock
L = h = w =
Conv- 1 ×
Globalpool → Linear
Logits
[Figure]
{+dimensions 
+}
×64 ×32 ×16 ×8 ×1 ×(cid:126)(cid:119)
[Figure] [Figure]
are gaining interest (Xiao et al., 2021; d’Ascoli et
., 2021; Chen et al., 2021b).
However, these hybrid models are still heavy-weight and are sensitive to data augmentation.
For example, removing CutMix (Zhong et al., 2020) and DeIT-style (Touvron et al., 2021a) data augmentation causes a signiﬁcant drop in ImageNet accuracy (78.1% to 72.4%) of Heo et al.
It remains an open question to combine the strengths of CNNs and transformers to build ViT models for mobile vision tasks.
Mobile vision tasks require light-weight, low latency, and accurate models that satisfy the device’s resource constraints, and are general-purpose so that they can be applied to different tasks (e.g., segmentation and detection).
Note that ﬂoating-point operations (FLOPs) are not sufﬁcient for low latency on mobile devices because FLOPs ignore several important inferencerelated factors such as memory access, degree of parallelism, and platform characteristics (Ma et al., 2018).
For example, the ViT-based method of Heo et al.
(2021), PiT, has 3 × fewer FLOPs than
DeIT (Touvron et al., 2021a)
but has a similar inference speed on a mobile device (DeIT vs. PiT on iPhone-12: 10.99 ms vs. 10.56 ms).
Therefore, instead of optimizing for FLOPs 1 , this paper focuses on designing a light-weight (§3), general-purpose (§4.1 & §4.2), and low latency (§4.3) network for mobile vision tasks.
We achieve this goal with MobileViT that combines the beneﬁts of CNNs (e.g., spatial inductive biases and less sensitivity to data augmentation) and ViTs (e.g., input-adaptive weighting and global processing).
Speciﬁcally, we introduce the MobileViT block that encodes both local and global information in a tensor effectively (Figure 1b).
Unlike ViT and its variants (with and without convolutions), MobileViT presents a different perspective to learn global representations.
Standard convolution involves three operations: unfolding, local processing, and folding.
MobileViT block replaces local processing in convolutions with global processing using transformers.
This allows MobileViT block to have CNN- and ViT-like properties, which helps it learn better representations with fewer parameters and simple training recipes (e.g., basic augmentation).
To the best of our knowledge, this is the ﬁrst work that shows that light-weight ViTs can achieve light-weight CNN-level performance with simple training recipes across different mobile vision tasks.
For a parameter budget of about 5-6 million, MobileViT achieves a top-1 accuracy of 78.4% on the ImageNet-1k dataset (Russakovsky et al., 2015), which is 3.2% more accurate than
MobileNetv3 and has a simple training recipe (MobileViT vs. MobileNetv3: 300 vs. 600 epochs; 1024 vs. 4096 batch size).
We also observe signiﬁcant gains in performance when MobileViT is used as a feature backbone in highly optimized mobile vision task-speciﬁc architectures.
Replacing
MNASNet (Tan et al., 2019) with MobileViT as a feature backbone in SSDLite (Sandler et al., 2018) resulted in a better (+1.8% mAP) and smaller ( 1 . 8 × ) detection network (Figure 2).
R ELATED W ORK
Light-weight CNNs.
The basic building layer in CNNs is a standard convolutional layer.
Because this layer is computationally expensive, several factorization-based methods have been proposed to make it light-weight and mobile-friendly (e.g., Jin et al., 2014; Chollet, 2017; Mehta et al., 2020).
Of these, separable convolutions of Chollet (2017) have gained interest, and are widely used across state-of-the-art light-weight CNNs for mobile vision tasks, including MobileNets (Howard et al., 2017; Sandler et al., 2018; Howard et al., 2019), ShufﬂeNetv2 (Ma et al., 2018), ESPNetv2 (Mehta et al., 2019), MixNet (Tan & Le, 2019b), and MNASNet (Tan et al., 2019).
These light-weight
CNNs are versatile and easy to train.
For example, these networks can easily replace the heavyweight backbones (e.g., ResNet (He et al., 2016)) in existing task-speciﬁc models (e.g., DeepLabv3) to reduce the network size and improve latency.
Despite these beneﬁts, one major drawback of these methods is that they are spatially local.
This work views transformers as convolutions; allowing to leverage the merits of both convolutions (e.g., versatile and simple training) and transformers (e.g., global processing) to build light-weight (§3) and general-purpose (§4.1 and §4.2) ViTs.
Vision transformers.
Dosovitskiy et al.
(2021) apply transformers of Vaswani et al.
(2017) for large-scale image recognition and showed that with extremely large-scale datasets (e.g., JFT-300M),
ViTs can achieve CNN-level accuracy without image-speciﬁc inductive bias.
With extensive data augmentation, heavy L2 regularization, and distillation, ViTs can be trained on the ImageNet dataset to achieve CNN-level performance (Touvron et al., 2021a;b; Zhou et al., 2021).
However, unlike
CNNs, ViTs show substandard optimizability and are difﬁcult to train.
Subsequent works (e.g.,
Graham et al., 2021; Dai et al., 2021; Liu et al., 2021; Wang et al., 2021; Yuan et al., 2021b;
Chen et al., 2021b) shows that this substandard optimizability is due to the lack of spatial inductive biases in ViTs.
Incorporating such biases using convolutions in ViTs improves their stability and performance.
Different designs have been explored to reap the beneﬁts of convolutions and transformers.
For instance, ViT-C of Xiao et al.
(2021) adds an early convolutional stem to ViT. CvT (Wu et al., 2021) modiﬁes the multi-head attention in transformers and uses depth-wise separable convolutions instead of linear projections.
BoTNet (Srinivas et al., 2021)
replaces the standard 3 × 3 convolution in the bottleneck unit of ResNet with multi-head attention.
ConViT (d’Ascoli et al., 2021) incorporates soft convolutional inductive biases using a gated positional self-attention.
PiT (Heo et al., 2021) extends ViT with depth-wise convolution-based pooling layer.
Though these models can achieve competitive performance to CNNs with extensive augmentation, the majority of these models are heavy-weight.
For instance, PiT and CvT learns 6 .
1 × and 1 .
7 × more parameters than EfﬁcientNet (Tan & Le, 2019a) and achieves similar performance (top-1 accuracy of about 81.6%) on ImageNet1k dataset, respectively.
Also, when these models are scaled down to build light-weight ViT models, their performance is signiﬁcantly worse than light-weight CNNs.
For a parameter budget of aboutmillion, ImageNet-1k accuracy of PiT is 2.2% less than MobileNetv3.
Discussion.
Combining convolutions and transformers results in robust and high-performing ViTs as compared to vanilla ViTs.
However, an open question here is: how to combine the strengths of convolutions and transformers to build light-weight networks for mobile vision tasks?
This paper focuses on designing light-weight ViT models that outperform state-of-the-art models with simple training recipes.
Towards this end, we introduce MobileViT that combines the strengths of CNNs and ViTs to build a light-weight, general-purpose, and mobile-friendly network.
MobileViT brings several novel observations.
(i) Better performance: For a given parameter budget, MobileViT mod-
[Figure]
els achieve better performance as compared to existing light-weight CNNs across different mobile vision tasks (§4.1 and §4.2).
(ii) Generalization capability: Generalization capability refers to the gap between training and evaluation metrics.
For two models with similar training metrics, the model with better evaluation metrics is more generalizable because it can predict better on an unseen dataset.
Unlike previous ViT variants (with and without convolutions) which show poor generalization capability even with extensive data augmentation as compared to CNNs (Dai et al., 2021), MobileViT shows better generalization capability (Figure 3).
(iii)
Robust:
A good model should be robust to hyper-parameters (e.g., data augmentation and L2 regularization) because tuning these hyper-parameters is time- and resource-consuming.
Unlike most ViT-based models, MobileViT models train with basic augmentation and are less sensitive to L2 regularization (§C).
M OBILE V I T: A L IGHT - WEIGHT T RANSFORMER
A standard ViT model, shown in Figure 1a, reshapes the input
X ∈ R
H
× W × C into a sequence of ﬂattened patches X f ∈ R N × PC , projects it into a ﬁxed d -dimensional space X p ∈ R N × d , and then learn inter-patch representations using a stack of L transformer blocks.
The computational cost of self-attention in vision transformers is O ( N 2 d ) .
Here, C , H , and W represent the channels, height, and width of the tensor respectively, and P = wh is number of pixels in the patch with height h and width w , and N is the number of patches.
Because these models ignore the spatial inductive bias that is inherent in CNNs, they require more parameters to learn visual representations.
For instance,
DPT (Dosovitskiy et al., 2021), a ViT-based network, learns 6 × more parameters as compared to
DeepLabv3 (Chen et al., 2017), a CNN-based network, to deliver similar segmentation performance (DPT vs. DeepLabv3: 345 M vs. 59 M).
Also, in comparison to CNNs, these models exhibit substandard optimizability.
These models are sensitive to L2 regularization and require extensive data augmentation to prevent overﬁtting (Touvron et al., 2021a;
Xiao et al., 2021).
This paper introduces a light-weight ViT model,
MobileViT.
The core idea is to learn global representations with transformers as convolutions.
This allows us to implicitly incorporate convolutionlike properties (e.g., spatial bias) in the network, learn representations with simple training recipes (e.g., basic augmentation), and easily integrate MobileViT with downstream architectures (e.g.,
DeepLabv3 for segmentation).
3. M OBILE V I T A RCHITECTURE
MobileViT block.
The MobileViT block, shown in Figure 1b, aims to model the local and global information in an input tensor with fewer parameters.
Formally, for a given input tensor X ∈ R H × W × C , MobileViT applies a n × n standard convolutional layer followed by a point-wise (or 1 × 1 ) convolutional layer to produce X L ∈ R
H × W × d .
The n × n convolutional layer encodes local spatial information while the point-wise convolution projects the tensor to a high-dimensional space (or d -dimensional, where d > C ) by learning linear combinations of the input channels.
With MobileViT, we want to model long-range non-local dependencies while having an effective receptive ﬁeld of H × W .
One of the widely studied methods to model long-range dependencies is dilated convolutions.
However, such approaches require careful selection of dilation rates.
Otherwise, weights are applied to padded zeros instead of the valid spatial region (Yu & Koltun, 2016;
Chen et al., 2017; Mehta et al., 2018).
Another promising solution is self-attention (Wang et al., 2018; Ramachandran et al., 2019; Bello et al., 2019; Dosovitskiy et al., 2021).
Among self-attention methods, vision transformers (ViTs) with multi-head self-attention are shown to be effective for visual recognition tasks.
However, ViTs are heavy-weight and exhibit sub-standard optimizability.
This is because ViTs lack spatial inductive bias (Xiao et al., 2021; Graham et al., 2021).
To enable MobileViT to learn global representations with spatial inductive bias, we unfold X L into N non-overlapping ﬂattened patches X U ∈ R P × N × d .
Here, P = wh , N = HWP is the number of patches, and h ≤ n and w ≤ n are height and width of a patch respectively.
For each p ∈ { 1 , · · · , P } , inter-patch relationships are encoded by applying transformers to obtain
X G ∈ R P
×
N × d as:
[Equation]
Unlike ViTs that lose the spatial order of pixels, MobileViT neither loses the patch order nor the spatial order of pixels within each patch (Figure 1b).
Therefore, we can fold X G ∈ R P × N × d to obtain X F ∈ R
H
× W × d .
X F is then projected to low C -dimensional space using a point-wise convolution and combined with X via concatenation operation.
Another n × n convolutional layer is then used to fuse these concatenated features.
Note that because X U ( p ) encodes local information from n × n region using convolutions and X G ( p ) encodes global information across P patches for the p -th location, each pixel in X G can encode information from all pixels in X , as shown in Figure 4.
Thus, the overall effective receptive ﬁeld of MobileViT is H × W .
Relationship to convolutions.
Standard convolutions can be viewed as a stack of three sequential operations: (1) unfolding, (2) matrix multiplication (to learn local representations), and (3) folding.
MobileViT block is similar to convolutions in the sense that it also leverages the same building blocks.
MobileViT block replaces the local processing (matrix multiplication) in convolutions with deeper global processing (a stack of transformer layers).
As a consequence, MobileViT has convolution-like properties (e.g., spatial bias).
Hence, the MobileViT block can be viewed as transformers as convolutions .
An advantage of our intentionally simple design is that low-level efﬁcient implementations of convolutions and transformers can be used out-of-the-box; allowing us to use
MobileViT on different devices without any extra effort.
Light-weight.
MobileViT block uses standard convolutions and transformers to learn local and global representations respectively.
Because previous works (e.g., Howard et al., 2017; Mehta et al., 2021a) have shown that networks designed using these layers are heavy-weight, a natural question arises: Why MobileViT is light-weight?
We believe that the issues lie primarily in learning global representations with transformers.
For a given patch, previous works (e.g., Touvron et al., 2021a;
Graham et al., 2021) convert the spatial information into latent by learning a linear combination of pixels (Figure 1a).
The global information is then encoded by learning inter-patch information using transformers.
As a result, these models lose image-speciﬁc inductive bias, which is inherent in
CNNs.
Therefore, they require more capacity to learn visual representations.
Hence, they are deep and wide.
Unlike these models, MobileViT uses convolutions and transformers in a way that the resultant MobileViT block has convolution-like properties while simultaneously allowing for global processing.
This modeling capability allows us to design shallow and narrow MobileViT models, which in turn are light-weight.
Compared to the ViT-based model DeIT that uses L =12 and d =192,
GPUGPU-
GPUGPU- time
Standardsampler
GPU-4 GPUGPU-
GPUtime
Multi-scalesampler
H e i gh t B a t c h
Width
Tensor
Gradientsync.
(a) Standard vs. multi-scale sampler illustration
Sampler
[Figure] efﬁciency
[Figure] PyTorch’s DistributedDataParallel sampler.
MobileViT model uses L = { 2, 4, 3 } and d = { 96, 120, 144 } at spatial levels 32 × 32 , 16 × 16 , and 8 × 8 , respectively.
The resulting MobileViT network is faster ( 1 . 85 × ), smaller ( 2 × ), and better ( +1 . 8% ) than DeIT network (Table 3; §4.3).
Computational cost.
The computational cost of multi-headed self-attention in MobileViT and ViTs (Figure 1a) is O ( N 2 Pd ) and O ( N 2 d ) , respectively.
In theory, MobileViT is inefﬁcient as compared to ViTs.
However, in practice, MobileViT is more efﬁcient than ViTs.
MobileViT has 2 × fewer
FLOPs and delivers 1 . 8% better accuracy than DeIT on the ImageNet-1K dataset (Table 3; §4.3).
We believe that this is because of similar reasons as for the light-weight design (discussed above).
MobileViT architecture.
Our networks are inspired by the philosophy of light-weight CNNs.
We train MobileViT models at three different network sizes (S: small, XS: extra small, and XXS: extra extra small) that are typically used for mobile vision tasks (Figure 3c).
The initial layer in MobileViT is a strided 3 × 3 standard convolution, followed by MobileNetv2 (or MV2) blocks
and
MobileViT blocks (Figure 1b and §A).
We use Swish (Elfwing et al., 2018) as an activation function.
Following CNN models, we use n = 3 in the MobileViT block.
The spatial dimensions of feature maps are usually multiples of 2 and h, w ≤ n .
Therefore, we set h = w = 2 at all spatial levels (see §C for more results).
The MV2 blocks in MobileViT network are mainly responsible for down-sampling.
Therefore, these blocks are shallow and narrow in MobileViT network.
Spatiallevel-wise parameter distribution of MobileViT in Figure 3d further shows that the contribution of
MV2 blocks towards total network parameters is very small across different network conﬁgurations.
3. M ULTI - SCALE S AMPLER FOR T RAINING E FFICIENCY
A standard approach in ViT-based models to learn multi-scale representations is ﬁne-tuning .
For instance, Touvron et al.
(2021a) ﬁne-tunes the DeIT model trained at a spatial resolution of 224 ×on varying sizes independently.
Such an approach for learning multi-scale representations is preferable for ViTs because positional embeddings need to be interpolated based on the input size, and the network’s performance is subjective to interpolation methods.
Similar to CNNs, MobileViT does not require any positional embeddings and it may beneﬁt from multi-scale inputs during training.
Previous CNN-based works (e.g., Redmon & Farhadi, 2017; Mehta et al., 2021b) have shown that multi-scale training is effective.
However, most of these works sample a new spatial resolution after a ﬁxed number of iterations.
For example, YOLOv2 (Redmon & Farhadi, 2017) samples a new spatial resolution from a pre-deﬁned set at every 10-th iteration and uses the same resolution across different GPUs during training.
This leads to GPU under-utilization and slower training because the same batch size (determined using the maximum spatial resolution in the pre-deﬁned set) is used across all resolutions.
To facilitate MobileViT learn multi-scale representations without ﬁnetuning and to further improve training efﬁciency (i.e., fewer optimization updates), we extend the multi-scale training method to variably-sized batch sizes.
Given a sorted set of spatial resolutions
S =
{ ( H 1 , W 1 ) , · · · , ( H n , W n ) } and a batch size b for a maximum spatial resolution of ( H n , W n ) , we randomly sample a spatial resolution ( H t , W t ) ∈ S at t -th training iteration on each GPU and compute the batch size for t -th iteration as: b t = H n W n b H t W t .
As a result, larger batch sizes are used for smaller spatial resolutions.
This reduces optimizer updates per epoch and helps in faster training.
Figure 5 compares standard and multi-scale samplers.
Here, we refer to DistributedDataParallel in
PyTorch as the standard sampler.
Overall, the multi-scale sampler (i) reduces the training time as it requires fewer optimizer updates with variably-sized batches (Figure 5b), (ii) improves performance by about 0.5% (Figure 10; §B), and (iii) forces the network to learn better multi-scale representations (§B), i.e., the same network when evaluated at different spatial resolutions yields better performance
[Figure]
compared sampler is generic and improves the performance of
E XPERIMENTAL R ESULTS
In this section, we ﬁrst evaluate MobileViTs performance on the ImageNet-1k dataset and show that
MobileViT delivers better performance than state-of-the-art networks (§4.1).
In §4.2 and §4.3, we show MobileViTs are general-purpose and mobile-friendly, respectively.
4. I MAGE C LASSIFICATION ON THE I MAGE N ET -1 K D ATASET
Implementation details.
We train MobileViT models from scratch on the ImageNet-1k classiﬁcation dataset (Russakovsky et al., 2015).
The dataset provides 1.28 million and 50 thousand images for training and validation, respectively.
The MobileViT networks are trained using PyTorch forepochs on 8 NVIDIA GPUs with an effective batch size of 1,024 images using AdamW optimizer (Loshchilov & Hutter, 2019), label smoothing cross-entropy loss (smoothing=0.1), and multi-scale sampler ( S = { (160 , 160) , (192 , 192) , (256 , 256) , (288 , 288) , (320 , 320) } ).
The learning rate is increased from 0.0002 to 0.002 for the ﬁrst 3k iterations and then annealed to 0.0002 using a cosine schedule (Loshchilov & Hutter, 2017).
We use L2 weight decay of 0.01.
We use basic data augmentation (i.e., random resized cropping and horizontal ﬂipping) and evaluate the performance using a single crop top-1 accuracy.
For inference, an exponential moving average of model weights is used.
Comparison with CNNs.
Figure 6a shows that MobileViT outperforms light-weight CNNs across different network sizes (MobileNetv1 (Howard et al., 2017), MobileNetv2 (Sandler et al., 2018),
ShufﬂeNetv2 (Ma et al., 2018), ESPNetv2 (Mehta et al., 2019), and MobileNetv3 (Howard et al., 2019)).
For instance, for a model size of about 2.5 million parameters (Figure 6b), MobileViT outperforms MobileNetv2 by 5%, ShufﬂeNetv2 by 5.4%, and MobileNetv3 by 7.4% on the ImageNet1k validation set.
Figure 6c further shows that MobileViT delivers better performance than heavyweight CNNs (ResNet (He et al., 2016),
DenseNet (Huang et al., 2017), ResNet-SE (Hu et al., 2018), and EfﬁcientNet (Tan & Le, 2019a)).
For instance, MobileViT is 2.1% more accurate than
EfﬁcentNet for a similar number of parameters.
Comparison with ViTs.
Figure 7 compares MobileViT with ViT variants that are trained from scratch on the ImageNet-1k dataset without distillation (DeIT (Touvron et al., 2021a), T2T (Yuan et al., 2021b), PVT (Wang et al., 2021), CAIT (Touvron et al., 2021b),
DeepViT (Zhou et al., 2021),
CeiT (Yuan et al., 2021a), CrossViT (Chen et al., 2021a), LocalViT (Li et al., 2021), PiT (Heo et al., 2021), ConViT (d’Ascoli et al., 2021), ViL (Zhang et al., 2021), BoTNet (Srinivas et al., 2021), and Mobile-former (Chen et al., 2021b)).
Unlike ViT variants that beneﬁt signiﬁcantly from advanced augmentation (e.g., PiT w/ basic vs. advanced : 72.4 (R4) vs. 78.1 (R17); Figure 7b), MobileViT achieves better performance with fewer parameters and basic augmentation.
For instance,
MobileViT is 2 .
5 × smaller and 2 .
6% better than DeIT (R3 vs. R8 in Figure 7b).
Overall, these results show that, similar to CNNs, MobileViTs are easy and robust to optimize.
Therefore, they can be easily applied to new tasks and datasets.
[Figure]
means a combination of augmentation methods with basic (e.g., MixUp (Zhang et al., 2018), RandAugmentation (Cubuk et al., 2019), and CutMix (Zhong et al., 2020)).
4. M OBILE V I T AS A G ENERAL - PURPOSE B ACKBONE
To evaluate the general-purpose nature of MobileViT, we benchmark MobileViT on two widely studied mobile vision tasks: (1) object detection (§4.2.1) and (2) semantic segmentation (§4.2.2).
4.2. M OBILE O BJECT D ETECTION
[Table]
We integrate MobileViT with a single shot object detection backbone (SSD; Liu et al., 2016).
Following light-weight CNNs (e.g., MobileNets), we replace standard convolutions in the SSD head with separable convolutions and call the resultant network as SSDLite.
We ﬁnetune MobileViT, pre-trained on the ImageNet-1k dataset, at an input resolution of 320 × 320 using AdamW on the MS-COCO dataset (Lin et al., 2014) that contains 117k training and 5k validation images.
We use smooth L and cross-entropy losses for object localization and classiﬁcation, respectively.
The performance is evaluated on the validation set using mAP@IoU of 0.50:0.05:0.95.
For other hyper-parameters, see §D.
Results.
Table 1a shows that, for the same input resolution of 320 × 320 , SSDLite with MobileViT outperforms
SSDLite with other light-weight CNN models (MobileNetv1/v2/v3, MNASNet, and MixNet).
For instance, SSDLite’s performance improves by 1.8%, and its model size reduces by 1 .
8 × when MobileViT is used as a backbone instead of MNASNet.
Further, SSDLite with MobileViT outperforms standard SSD-300 with heavy-weight backbones while learning signiﬁcantly fewer parameters (Table 1b).
Also, qualitative results in §F conﬁrms MobileViT’s ability to detect variety of objects.
4.2. M OBILE S EMANTIC S EGMENTATION
[Table]
Implementation details.
We integrate MobileViT with DeepLabv3 (Chen et al., 2017).
We ﬁnetune MobileViT using AdamW with cross-entropy loss on the PASCAL VOC 2012 dataset (Everingham et al., 2015).
Following a standard training practice (e.g., Chen et al., 2017; Mehta et al., 2019), we also use extra annotations from
[Figure]
Results.
Table 2 shows that DeepLabv3 with MobileViT is smaller and better.
The performance of DeepLabv3 is improved by 1.4%, and its size is reduced by 1 .
6 × when MobileViT is used as a backbone instead of MobileNetv2.
Also, MobileViT gives competitive performance to model with
ResNet-101 while requiring 9 × fewer parameters; suggesting MobileViT is a powerful backbone.
Also, results in §G shows that MobileViT learns generalizable representations of the objects and perform well on an unseen dataset.
4. P ERFORMANCE ON M OBILE D EVICES
Light-weight and low latency networks are important for enabling mobile vision applications.
To demonstrate the effectiveness of MobileViT for such applications, pre-trained full-precision MobileViT models are converted to CoreML using publicly available CoreMLTools (2021).
Their inference time is then measured (average over 100 iterations) on a mobile device, i.e., iPhone 12.
Mobile-friendly.
Figure 8 shows the inference time of MobileViT networks with two patch size settings (Conﬁg-A: 2 , 2 , 2 and Conﬁg-B: 8 , 4 , 2 ) on three different tasks.
Here p 1 , p 2 , p 3 in ConﬁgX denotes the height h (width w = h ) of a patch at an output stride 2 of 8, 16, and 32, respectively.
The models with smaller patch sizes (Conﬁg-A) are more accurate as compared to larger patches (Conﬁg-B).
This is because, unlike Conﬁg-A models, Conﬁg-B models are not able to encode the information from all pixels (Figure 13 and §C).
On the other hand, for a given parameter budget,
Conﬁg-B models are faster than Conﬁg-A even though the theoretical complexity of self-attention in both conﬁgurations is the same, i.e., O ( N 2 Pd ) .
With larger patch sizes (e.g., P = 8 2 = 64 ), we have fewer number of patches N as compared to smaller patch sizes (e.g., P = 2 2 = 4 ).
As a result, the computation cost of self-attention is relatively less.
Also, Conﬁg-B models offer a higher degree of parallelism as compared to Conﬁg-A because self-attention can be computed simultaneously for more pixels in a larger patch ( P = 64 ) as compared to a smaller patch ( P = 4 ).
Hence, Conﬁg-B models are faster than Conﬁg-A.
To further improve MobileViT’s latency, linear self-attention (Wang et al., 2020) can be used.
Regardless, all models in both conﬁgurations run in real-time (inference speed ≥ 30 FPS) on a mobile device except for MobileViT-S models for the segmentation task.
This is expected as these models process larger inputs ( 512 × 512 ) as compared to classiﬁcation ( 256 × 256 ) and detection ( 320 × 320 ) networks. [Figure]
[Table]
Results with multi-scale
Discussion.
We observe that MobileViT and other ViTbased networks (e.g., DeIT and PiT) are slower as compared to MobileNetv2 on mobile devices (Table 3).
This observation contradicts previous works which show that
ViTs are more scalable as compared to CNNs (Dosovitskiy et al., 2021).
This difference is primarily because of two reasons.
First, dedicated CUDA kernels exist for transformers on GPUs, which are used out-of-the-box in
ViTs to improve their scalability and efﬁciency on GPUs (e.g., Shoeybi et al., 2019;
Lepikhin et al., 2021).
Second, CNNs beneﬁt from several device-level optimizations, including batch normalization fusion with convolutional layers (Jacob et al., 2018).
These optimizations improve latency and memory access.
However, such dedicated and optimized operations for transformers are currently not available for mobile devices.
Hence, the resultant inference graph of MobileViT and ViT-based networks for mobile devices is sub-optimal.
We believe that similar to CNNs, the inference speed of MobileViT and ViTs will further improve with dedicated device-level operations in the future.
A CKNOWLEDGEMENTS
We are grateful to Ali Farhadi, Peter Zatloukal, Oncel Tuzel, Ashish Shrivastava, Frank Sun, Max Horton, Anurag Ranjan and anonymous reviewers for their helpful comments. We are also thankful to Apple’s infrastructure and open-source teams for their help with training infrastructure and opensource release of the code and pre-trained models.
A M OBILE V I T A RCHITECTURE
MobileViT’s are inspired by the philosophy of light-weight CNNs and the overall architecture of
MobileViT at different parameter budgets is given in Table 4.
The initial layer in MobileViT is a strided 3 × 3 standard convolution, followed by MobileNetv2 (or MV2) blocks and MobileViT blocks.
We use Swish (Elfwing et al., 2018) as an activation function.
Following CNN models, we use n = 3 in the MobileViT block.
The spatial dimensions of feature maps are usually multiples of 2 and h, w ≤ n .
Therefore, we set h = w = 2 at all spatial levels.
The MV2 blocks in MobileViT network are mainly responsible for down-sampling.
Therefore, in these blocks, we use an expansion factor of four, except for MobileViT-XXS where we use an expansion factor of 2.
The transformer layer in MobileViT takes a d -dimensional input, as shown in Figure 1b.
We set the output dimension of the ﬁrst feed-forward layer in a transformer layer as 2 d instead of 4 d , a default value in the standard transformer block of Vaswani et al.
B M ULTI - SCALE SAMPLER
Multi-scale sampler reduces generalization gap.
Generalization capability refers to the gap between training and evaluation metrics.
For two models with similar training metrics,the model with better evaluation metrics is more generalizable because it can predict better on an unseen dataset.
Figure 9a and Figure 9b compares the training and validation error of the MobileViT-S model trained with standard and multi-scale samplers.
The training error of MobileViT-S with multi-scale sampler is higher than standard sampler while validation error is lower.
Also, the gap between training error and validation error of MobileViT-S with multi-scale sampler is close to zero.
This suggests that a multi-scale sampler improves generalization capability.
Also, when MobileViT-S trained independently with standard and multi-scale sampler is evaluated at different input resolutions (Figure 9c), we observe that MobileViT-S trained with multi-scale sampler is more robust as compared to the one trained with the standard sampler.
We also observe that multi-scale sampler improves the performance of MobileViT models at different model sizes by about 0.5% (Figure 10).
These observations in conjunction with impact on training efﬁciency (Figure 5b) suggests that a multi-scale sampler is effective.
Pytorch implementation of multi-scale sampler is provided in Listing 1.
Multi-scale sampler is generic.
We train a heavy-weight (ResNet-50) and a light-weight (MobileNetv2-1.0) CNN with the multi-scale sampler to demonstrate its generic nature.
Results in Table 5 show that a multi-scale sampler improves the performance as well as training efﬁciency
[Figure]
[Table] [Figure] [Table] [Figure]
[Table]
[Figure] [Table] [Figure] [Table]
[Figure] [Table] [Figure] [Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
block (Figure 1b).
By default, in MobileViT block, we set kernel size n as three and spatial dimensions of patch (height h and width w ) in MobileViT block as two.
[Figure]
[Figure] [Figure]
[Table]
For instance, a multi-scale sampler improves the
MobileNetv2-1.0 by about 1.4% while
C A BLATIONS
Impact of weight decay.
A good model should be insensitive or less sensitive to L2 regularization (or weight decay) because tuning it for each task and dataset is time- and resource-consuming.
Unlike CNNs, ViT models are sensitive to weight decay (Dosovitskiy et al., 2021; Touvron et al., 2021a; Xiao et al., 2021).
To study if MobileViT models are sensitive to weight decay or not, we train the MobileViT-S model by varying the value of weight decay from 0 .
1 to 0 . 0001 .
Results are shown in Figure 11.
With an exception to the MobileViT model trained with a weight decay of 0 . 1 , all other models converged to a similar solution.
This shows that MobileViT models are robust to weight decay.
In our experiments, we use the value of weight decay as 0.01.
Note that 0 . 0001 is the widely used value of weight decay in most CNN-based models, such as ResNet and DenseNet.
Even at this value of weight decay, MobileViT outperforms CNNs on the ImageNet-1k dataset (e.g.,
DenseNet vs. MobileViT: 76.2 with 14 M parameters vs. 77.4 with 5.7 M parameters).
Impact of skip-connection.
Figure 12 studies the impact of skip-connection in the MobileViT block ( red arrow in Figure 1b).
With this connection, the performance of MobileViT-S improves by 0.5% on the ImageNet dataset.
Note that even without this skip-connection, MobileViT-S delivers similar or better performance than state-of-the-art CNN- (Figure 6) and ViT-based (Figure 7b) models, that too with basic data augmentation.
Impact of patch sizes.
MobileViT combines convolutions and transformers to learn local and global representations effectively.
Because convolutions are applied on n × n regions and self-attention
[Figure]
[Figure] [Figure]
[Table]
is computed over patches with spatial dimensions of h and w , it is essential to establish a good relationship between n , h , and w .
Following previous works on CNN designs, we set n =and then vary h and w .
Speciﬁcally, we study four conﬁgurations: (i) h
= w = 2 at all spatial levels (Figure 13a).
In this case, h, w < n and would allow each pixel to encode information from every other pixel using MobileViT. (ii) h
= w = 3 at all spatial levels (Figure 13b).
In this case, h = w = n .
Similar to (i), this conﬁguration would also allow each pixel to encode information from every other pixel using MobileViT. (iii) h = w = 4 at all spatial levels (Figure 13c).
In this case, h, w > n and would not allow each pixel to aggregate information from other pixels in the tensor.
(iv) h = w = 8 , h = w = 4 , and h = w = 2 at spatial level of 32 × 32 , 16 × 16 , and 8 × 8 , respectively.
Unlike (i), (ii), and (iii), the number of patches N is the same across different spatial resolutions in (iv).
Also, h, w < n only for a spatial level of 8 × 8 where h = w = 2 .
Note that all these models have the same number of network parameters and the same computational cost of self-attention, i.e., O ( N 2 Pd ) .
Here, N is the number of patches, P = hw is the number of pixels in a patch with height h and width w , and d is the model dimension.
Results are shown in Table 6.
We can see that when h, w ≤ n , MobileViT can aggregate information more effectively, which helps improve performance.
In our experiments, we used h = w =instead of h = w = 3 because spatial dimensions of feature maps are multiples of 2, and using
[Figure] [Figure]
Impact of exponential moving average and label smoothing.
Exponential moving average (EMA) and label smoothing (LS) are two standard training methods that are used to improve CNN- and
Transformer-based models performance (Sandler et al., 2018; Howard et al., 2019; Tan et al., 2019;
Touvron et al., 2021a; Dai et al., 2021; Xiao et al., 2021).
Table 7 shows that LS marginally improves the performance of MobileViT-S while EMA has little or no effect on model’s performance on the
ImageNet-1k dataset.
Because previous works have shown these methods to be effective in reducing stochastic noise and prevent network from becoming over-conﬁdent, we use these methods to train
MobileViT models.
D T RAINING D ETAILS FOR SSDL ITE AND D EEP L ABV
All SSDLite-MobileViT and DeepLabv3-MobileViT networks are trained for 200 and 50 epochs with a standard sampler on 4 NVIDIA GPUs and with an effective batch size of 128 images, respectively.
The learning rate is increased from 0.00009 to 0.0009 in the ﬁrst 500 iterations and then annealed to 0.00009 using a cosine learning rate scheduler.
We use L2 weight decay of 0.01.
We change the stride of MV2 block from two to one at an output stride of 32 in Table 4 to obtain
DeepLabv3-MobileViT models at an output stride of 16.
For these models, we do not use a multi-scale sampler.
This is because these task-speciﬁc networks are resolution-dependent.
For example, DeepLabv3 uses an atrous (or dilation) rate of 6, 12, and 18 at an output stride of 16 to learn multi-scale representations.
If we use a lower resolution (say 256 × 256 ) than 512 × 512 , then the atrous kernel weights will be applied to padded zeros; making multi-scale learning ineffective.
E E XTENDED D ISCUSSION
Memory footprint.
A light-weight network running on mobile devices should be memory efﬁcient.
Similar to MobileNetv2, we measure the memory that needs to be materialized at each spatial level (Table 8).
At lower spatial levels (i.e., an output stride of 8, 16, and 32) where MobileViT blocks are employed, required memory is lesser or comparable to light-weight CNNs.
Therefore, similar to light-weight CNNs, MobileViT networks are also memory efﬁcient.
FLOPs.
Floating point operations (FLOPs) is another metric that is widely used to measure the efﬁciency of a neural network.
Table 9 compare FLOPs of MobileViT with different ViT-based networks on the ImageNet-1k dataset.
For similar number of FLOPs, MobileViT is faster, smaller, and better.
For instance, PiT and MobileViT has the same number of FLOPs, but MobileViT is 1 .
45 × faster, 2 . 1 × smaller, and 1 .
8% better (R2 vs. R4 in Table 9).
It is important to note that FLOPs for networks in R2-R4 are the same, but their latency and performance are different.
This shows that
FLOPs is not a sufﬁcient metric for network efﬁciency as it does not account for inference-related factors such as memory access, degree of parallelism, and platform characteristics.
The ImageNet-1k pre-training helps in performance improvement in down-stream tasks such as object detection and semantic segmentation (Long et al., 2015; Chen et al., 2017; Redmon & Farhadi, 2017).
Because such tasks are used in real-world applications and often uses higher image inputs as compared to the ImageNet-1k classiﬁcation task, it is important to compare the FLOPs of a network on down-stream tasks.
Towards this end, we compare the FLOPs of MobileViT with MobileNetv on three tasks, i.e., classiﬁcation, detection, and segmentation.
Results are shown in Table 10.
We can observe that (1) the gap between MobileNetv2 and MobileViT FLOPs reduces as the input resolution increases.
For instance, MobileNetv2 has 2 × fewer FLOPs as compared to MobileViTon the ImageNet-1k classiﬁcation task, but on the semantic segmentation, they have similar FLOPs (Table 10a vs. Table 10c) and (2) MobileNetv2 models are signiﬁcantly faster but less accurate than
MobileViT models across different tasks.
The low-latency of MobileNetv2 models is likely because of dedicated and optimized hardware-level operations on iPhone.
We believe that (1) the inference speed of MobileViT will further improve with such dedicated operations and (2) our results will inspire future research in the area of hardware design and optimization.
Inference time on different devices.
Table 11 compares the inference time of different models on three different devices, i.e., iPhone12 CPU, iPhone12 neural engine, and NVIDIA V100 GPU.
MobileNetv2 is the fastest network across all devices.
On iPhone (both CPU and neural engine),
MobileViT delivers better performance as compared to DeIT and PiT.
However, on GPU, DeIT and PiT are faster than MobileViT.
This is likely because MobileViT models (1) are shallow and narrow, (2) run at higher spatial resolution ( 256 × 256 instead of 224 × 224 ), and (2) did not use
[Table]
[Table] [Table]
320 × 320 , and 512 × 512 respectively with an exception to MobileViT-XS model in (a) which uses 256 × 256 as an input resolution for measuring inference time on iPhone 12 neural engine.
Here, the performance of MobileViT-XS models is reported at two different patch-size settings.
See §A for details.
[Table]
GPU- accelerated operations for folding and unfolding as they are not supported on mobile devices.
However, when we replaced our unoptimized fold and unfold operations with PyTorch’s Unfold and
Fold operations, the latency of MobileViT model is improved from 0.62 ms to 0.47 ms.
Overall, our ﬁndings suggest that they are opportunities for optimizing ViT-based models, including MobileViT, for different accelerators.
We believe that our work will inspire future research in building more efﬁcient networks.
F Q UALITATIVE R ESULTS ON THE T ASK OF O BJECT D ETECTION
Figures 15, 14, and 16 shows that SSDLite with MobileViT-S can detect different objects under different settings, including changes in illumination and viewpoint, different backgrounds, and nonrigid deformations.
[Figure]
G S EMANTIC S EGMENTATION R ESULTS ON AN U NSEEN D ATASET
To demonstrate that MobileViT learns good generalizable representations of objects, we evaluate the DeepLabv3-MobileViT model in Section 4.2.2 on the MS-COCO validation set that contains 5k images.
Following ofﬁcial torchvision segmentation models (PyTorch, 2021), object classes in the MS-COCO dataset are mapped to the object classes in the PASCAL VOC dataset and models are evaluated in terms of mIOU.
Note that the MS-COCO validation set is an unseen test set for
DeepLabv3-MobileViT models because these images are neither part of the training nor the validation set used for training DeepLabv3-MobileViT models.
Table 12 compares the performance of DeepLabv3-MobileViT models with MobileNetv3-Large that was trained with three different segmentation backbones (LR-ASPP (Howard et al., 2019),
DeepLabv3, and FCN (Long et al., 2015)).
For the same segmentation model, i.e., DeepLabv3,
MobileViT is a more effective backbone than MobileNetv3.
DeepLabv3-MobileViT-S model is 1 .
7 × smaller and 5.1% more accurate than DeepLabv3-MobileNetv3-Large model.
Furthermore, qualitative results in Figure 17 and Figure 18 further demonstrates that MobileViT learns good generalizable representations of the objects and perform well in the wild.
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
img batch pairs = list ()base elements = base im w * base im h * base batch size for (h, w) in zip ( height dims , width dims ) : batch size = max(1 , ( base elements / (h * w) ) img batch pairs .
append ((h, w, batch size ) ) self .
img batch pairs = img batch pairs self
[Figure]
=
True else :self .
img
[Figure]
pairs =
[( base im h , base im w , base batch size ) ]self .
img indices = img indicesself .
n
[Figure]
per replica =
num
[Figure]
per replica self
[Figure]
epoch = self
[Figure]
rank = rank self
[Figure]
num replicas = num replicasdef iter ( self ) :if self
[Figure]
shuffle : random
[Figure] seed ( self . epoch)random . shuffle ( self .
img indices ) random . shuffle ( self . img batch pairs ) indices rank i = self . img indices [ self .
rank : len ( self .
img indices ) : self .
num replicas ] else : indices rank i = self .
img indices [ self .
rank : len ( self .
img indices ) : self .
num replicas ] start
[Figure]
= 0 while
[Figure]
< self .
n samples per replica :curr h , curr w , curr bsz = random
[Figure]
choice ( self . img batch pairs ) end
[Figure]
= min(
[Figure]
+
[Figure]
, self
[Figure]
n samples per replica )
[Figure]
= indices
[Figure]
i [ start index : end index ] n [Figure] len ( batch [Figure]
) if n batch
[Figure]
= curr
[Figure] [Figure] + [Figure]
indices
[Figure] [Figure]
n
[Figure]
samples ) ]
[Figure]
+=
[Figure]
if
[Figure] [Figure] [Figure] [Figure]
[Figure]
[Figure]
in batch
[Figure] [Figure] [Figure] int
[Figure]
:self
[Figure]