A phone pays for time, not for parameters. MobileViT-XS has 2.3 M parameters and still takes 7.28 ms, 8 times MobileNetv2. FastViT folds its skip into one convolution: same parameters, same FLOPs, 2.25 ms down to 1.58 ms.
Pick a design and compare its four numbers. Then pick the FastViT block and switch the fold off and on. Then we build both ideas piece by piece: the unfold, the attention, the fold back, and the branch merge.
You need what a convolution does and a little PyTorch. We teach attention and BatchNorm where we use them.
Based on MobileViT by Sachin Mehta and Mohammad Rastegari (ICLR 2022) and FastViT by Pavan Kumar Anasosalu Vasu, James Gabriel, Jeff Zhu, Oncel Tuzel and Anurag Ranjan (ICCV 2023), both from Apple. Re-taught in our own words and devices.
MobileNetv2, DeIT and MobileViT-XS: MobileViT Table 3, iPhone 12. FastViT block: FastViT Table 1, iPhone 12 Pro, PoolFormer-S12 at 256 (skip kept) against RepMixer (folded). Two phones, so compare designs within one paper.
Chapter 0
See why parameters, FLOPs and latency rank the same models in different orders
You want a camera app to name objects. The model must answer within one frame, on a phone chip. MobileViT calls a model real-time when it runs under 33 ms, which is 30 frames per second (Figure 8). Three numbers describe what a model costs, and they disagree.
| Number | What it counts | What it misses |
|---|---|---|
| Parameters | the learned weights; it sets the file size | how often each weight runs |
| FLOPs | multiply and add operations for one image | memory traffic, parallelism, the chip |
| Latency | measured time for one image on one device | nothing, but it holds for that device only |
The MobileViT paper names the gap: FLOPs ignore memory access, parallelism and the platform (Section 1). The authors timed four models on three chips (Table 11). Switch the chip and watch the order change.
Bars are latency, fastest on top. Parameters and FLOPs stay fixed at the right.
MobileViT Table 11. MobileViT runs at 256 × 256, the others at 224 × 224. Phones use batch 1.
Worked number. PiT has 0.7 GFLOPs and DeIT has 1.3, a ratio of 1.3 ÷ 0.7 = 1.9. On the iPhone 12 they take 10.56 ms and 10.99 ms, a ratio of 1.04. Half the arithmetic bought 4% of speed.
Symptom: a model that wins on a server GPU is slow on the phone. DeIT is the fastest transformer here on the V100 (0.43 ms) and the slowest on both iPhone chips. Measure on the target: the authors convert to Core ML and average 100 runs on an iPhone 12. Fix: choose models by that number.
Two Apple papers attack this. MobileViT (ICLR 2022) mixes convolution and attention in one block, for accuracy at a small size. FastViT (ICCV 2023) reshapes the network so the phone runs fewer, simpler operations.
Chapter 1
Compare what one convolution layer sees with what one attention layer sees
Look at a photo of a dog. To find an eye, you check a few pixels. To tell a dog from a wolf, you compare the ears with the tail across the image. Vision needs both views.
A convolution slides a small window of weights over the image. A 3 × 3 convolution builds each output pixel from its 3 × 3 neighbours, so it is local. After L such layers, one output pixel sees a window of (2L + 1) × (2L + 1) pixels, its receptive field.
Self-attention scores every token against every other token and mixes them by those scores. One layer is global. For N tokens it computes N × N scores.
Tap a pixel to move it. Add 3 × 3 layers and watch the teal window grow. Switch on attention to see one layer reach everything.
Illustrative 16 × 16 map, stride 1, no dilation.
Worked number. A 16 × 16 map has 256 pixels. Three 3 × 3 layers give a 7 × 7 window: 49 pixels, 19% of the map. One attention layer reaches all 256 with 256 × 256 = 65,536 scores. Double the side to 32 and the scores grow 16 times, to 1,048,576.
A convolution also brings an inductive bias: a built-in belief that near pixels belong together. A ViT must learn that from data, so it needs more weights. ViT-B/16 has 86 M parameters against 7.5 M for MobileNetv3. Shrunk to 5 to 6 M parameters, DeIT is 3% less accurate than MobileNetv3 (MobileViT, Section 1).
Symptom: a small ViT falls behind when you train it with plain crops and flips. Measure: train it twice, with basic and with heavy augmentation. PiT scores 72.4% with basic and 78.1% with advanced (MobileViT Figure 7b). Fix: give the model the convolution’s bias. MobileViT-S reaches 78.4% with basic augmentation.
Chapter 2
Follow one feature map through local convolution, global attention and fusion
MobileViT keeps a CNN body and puts a MobileViT block at three of its stages. The block takes an H × W × C map and returns the same shape, so it drops into any CNN. Step through it on the 32 × 32 stage of MobileViT-S, where C = 96 and d = 144 (Table 4).
Press Next. The lit box is the step; the tensor below shows its shape.
Shapes from MobileViT Table 4: n = 3, h = w = 2, L = 2 at this stage.
How does every pixel see every pixel? A pixel attends only to pixels at its own place in other patches. But each of those already mixed its 3 × 3 neighbourhood in step 1. Two hops cover the map (Figure 4).
Why is the block light? A ViT mixes the pixels of each patch into one vector and loses the image bias. So it must be deep and wide: DeIT uses L = 12 and d = 192. MobileViT-XS uses L = 2, 4, 3 and d = 96, 120, 144. It is 1.85 times faster, 2 times smaller and 1.8 points better than DeIT (Section 3.1).
The paper reads a convolution as three steps: unfold, a matrix multiply, fold. The block keeps unfold and fold and swaps the matrix multiply for transformers. The authors call this transformers as convolutions.
Symptom: a larger patch loses accuracy at the same parameter count. With h = w = 4 and a 3 × 3 kernel, some pixels never reach others (Figure 13). Measure on ImageNet: patches 4, 4, 4 give 77.6% against 78.4% for 2, 2, 2 (Table 6). Fix: keep h and w at or below the kernel size n.
Chapter 3
Track real tensor shapes through the reshape at the centre of MobileViT
Unfold is a reshape. It has no weights and does no arithmetic. It decides which pixels talk to each other in attention.
Each colour is a place inside a patch. Slide the place p: the lit pixels form one sequence. The table is the unfolded tensor, P rows by N columns.
Illustrative 8 × 8 map with one channel. The order of places matches the code below.
In the toy, place 0 holds pixels 0, 2, 4, 6, 16 and so on: one pixel from each patch. With 4 × 4 patches the picture flips: 16 places, each with only 4 pixels.
Take the 32 × 32 stage of MobileViT-S after the 1 × 1 convolution: a tensor of 32 × 32 × 144.
A ViT with one token per 2 × 2 patch would score 256 × 256 = 65,536 pairs, 4 times fewer. The paper says so: in theory MobileViT costs O(N²Pd) against O(N²d). In practice it is shallow and narrow, with 0.7 GFLOPs against 1.3 for DeIT (Table 3).
import torch
def unfold(x, h=2, w=2): # x: [B, d, H, W]
B, d, H, W = x.shape
x = x.reshape(B, d, H // h, h, W // w, w) # (patch row, place row, patch col, place col)
x = x.permute(0, 3, 5, 2, 4, 1) # [B, h, w, H/h, W/w, d]
return x.reshape(B, h * w, (H // h) * (W // w), d) # [B, P, N, d]
def fold(x, H, W, h=2, w=2): # x: [B, P, N, d]
B, P, N, d = x.shape
x = x.reshape(B, h, w, H // h, W // w, d)
x = x.permute(0, 5, 3, 1, 4, 2) # [B, d, H/h, h, W/w, w]
return x.reshape(B, d, H, W)
x = torch.randn(1, 144, 32, 32) # MobileViT-S, 32 x 32 stage
u = unfold(x) # (1, 4, 256, 144)
# attention runs on u.reshape(4, 256, 144): 4 sequences, 256 tokens each
assert torch.equal(fold(u, 32, 32), x) # the round trip is exact
We ran it: unfold gives (1, 4, 256, 144), and the round trip is exact.
Symptom: the model gets slow for no gain. With 3 × 3 patches on maps of 32, 16 and 8, the unfold and fold need bilinear resizing. Latency rises from 9.85 ms to 14.69 ms for 0.1 points of accuracy (Table 6). Measure latency, not FLOPs. Fix: pick h and w that divide every map size.
Chapter 4
Stack the blocks into three sizes and read what they win and what they lose
The network starts with a strided 3 × 3 convolution. MobileNetv2 blocks (MV2) then shrink the map. MobileViT blocks sit at the 32 × 32, 16 × 16 and 8 × 8 stages, with L = 2, 4 and 3 transformer layers.
| Size | Parameters | d at 32, 16, 8 | ImageNet top-1 |
|---|---|---|---|
| XXS | 1.3 M | 64, 80, 96 | 69.0% |
| XS | 2.3 M | 96, 120, 144 | 74.8% |
| S | 5.6 M | 144, 192, 240 | 78.4% |
Training is plain: 300 epochs, batch 1,024, random crops and flips. A multi-scale sampler picks a new image size from 160 to 320 pixels per GPU per step, with bigger batches for smaller images. It cuts updates per epoch from 375 k to 232 k and epoch time from 380 s to 270 s (Figure 5b).
Pick a benchmark. Warm bars are MobileViT, teal are CNNs, purple are ViTs. The label is the parameter count.
MobileViT Figure 6b, Figure 7b, Table 1a (SSDLite, 320 × 320) and Table 2 (DeepLabv3). Bars start at the printed floor, not at zero.
Worked number. At about 2.5 M parameters, MobileViT-XS scores 74.8% and MobileNetv3 67.4% (Figure 6b): 7.4 points more. As a detection backbone, MobileViT-XS has 2.7 M parameters and 24.8 mAP; MNASNet has 4.9 M and 23.0 mAP (Table 1a).
Symptom: MobileViT-XS takes 7.28 ms where MobileNetv2 takes 0.92 ms on the iPhone 12 (Table 3). The authors name two causes. Phones have no fused kernels for transformers. CNNs get device tricks, such as merging BatchNorm into the convolution. Larger patches (8, 4, 2) help a little: 5.93 ms for 73.8% (Table 9). The full fix needs a different graph, and that is FastViT.
Chapter 5
Fold BatchNorm and parallel branches into a single kernel, and check the numbers
A wide block learns better. A narrow block runs faster. Structural reparameterization gets both: train with parallel branches, then merge them into one convolution before you ship.
BatchNorm (BN) normalizes each channel with a stored mean μ and variance σ², then scales by γ and shifts by β. At inference all four are constants, so BN is one multiply and one add.
So a convolution W followed by BN is one convolution with weights W′ = (γ / σ) W and bias b′ = β − γμ / σ. Convolution is linear, so parallel branches add. Pad a 1 × 1 kernel to 3 × 3 with zeros. Write an identity branch as a 3 × 3 kernel with a 1 in the centre.
Each column is a branch with its kernel and BN. Switch branches on and off, then press Fold. Watch the output at pixel (1, 1).
Illustrative weights, one channel. The fold is exact; our PyTorch run of the same numbers matches all 16 pixels to within 0.000001.
At pixel (1, 1) the centre is 3 and its four neighbours sum to 4. Branches: −1.675 + 1.600 + 2.200 = 2.125. Folded: 0.75 × 4 − 0.2 × 3 − 0.275 = 2.125.
import torch, torch.nn.functional as F
def fuse(kernel, bn): # conv (no bias), then BN: one conv
std = (bn.running_var + bn.eps).sqrt()
s = bn.weight / std # per-channel scale gamma / sigma
return kernel * s.reshape(-1, 1, 1, 1), bn.bias - bn.running_mean * s
def fold_branches(w3, bn3, w1, bn1, bn_id): # w3: [C, C, 3, 3], w1: [C, C, 1, 1]
k3, b3 = fuse(w3, bn3) # 3 x 3 branch
k1, b1 = fuse(F.pad(w1, [1, 1, 1, 1]), bn1) # 1 x 1 branch, padded to 3 x 3
eye = torch.zeros_like(w3) # identity branch as a 3 x 3 kernel
for c in range(w3.shape[0]):
eye[c, c, 1, 1] = 1.0
ki, bi = fuse(eye, bn_id)
return k3 + k1 + ki, b3 + b1 + bi # one kernel, one bias
# with every BN in eval mode:
# y_train = bn3(conv(x, w3, pad=1)) + bn1(conv(x, w1)) + bn_id(x)
# K, b = fold_branches(w3, bn3, w1, bn1, bn_id)
# y_fold = F.conv2d(x, K, b, padding=1) # max |y_train - y_fold| = 7e-7
FastViT uses this in its stem and patch embeddings, in the style of MobileOne. Factorized convolutions alone cost accuracy: 78.5% fell to 78.0%. The train-time branches brought it to 78.9% at the same 1.26 ms (Table 1). The cost moves to training: FastViT-SA12 took 33.4 hours instead of 31.3 (Table 3).
Symptom: the folded model gives different answers from the trained one. Measure the largest absolute gap between the two outputs on a few images. A common cause is a fold done while BN is in training mode, so it uses batch statistics. Fix: call model.eval() before you fold.
Chapter 6
Remove a skip connection at inference and see why that saves time
A skip connection adds a block’s input to its output: Y = f(X) + X. It helps training. On a phone it costs memory traffic: the chip keeps X, reads it a second time, and writes the sum.
Most hybrids follow the MetaFormer layout: a token mixer with a skip, then a feed-forward net with another skip. FastViT’s mixer, RepMixer, starts from the ConvMixer block. It moves BN first and drops the activation.
Worked number, one channel. BN scale 0.75 and shift −0.175. Kernel 1, 1, 1, 1 around −2, so its weights sum to 2. Folded: edges 0.75, centre 0.75 × (−2) + 1 = −0.5, bias −0.175 × 2 = −0.35. At a pixel with centre 3 and neighbours summing to 4: 3 − 1.5 − 0.35 = 1.15. The training form gives −1.85 + 3 = 1.15.
Slide the input size. Each box is one full read or write of the stage 1 map. The skip version moves five; the folded version moves two.
Traffic is our illustrative count: stage 1 of S12 (1/4 scale, 64 channels), 16-bit values. The two latency cuts come from FastViT Figure 3 (iPhone 12 Pro).
The paper times the whole S12 network on an iPhone 12 Pro at equal FLOPs. RepMixer beats Pooling, which keeps its skip, by 25.1% at 384 × 384 and by 43.9% at 1024 × 1024 (Figure 3). Bigger maps mean more traffic, so the saving grows.
Symptom: the folded RepMixer matches inside the image and drifts at the border. Cause: BN sits before a zero-padded convolution, so the trained block saw padded zeros after BN. Our check: the interior differs by 0.000001, the border by 1.12. Fix: put BN after the convolution, which folds exactly (0.0000014 in our check).
Chapter 7
Read which design choices bought accuracy and which cost time, in both papers
An ablation changes one part of a model and measures the effect. Both papers report them on ImageNet. Pick one table and tap a row.
Each row has a blue latency bar and a green accuracy bar. Tap a row to compare it with the row above.
FastViT tables: iPhone 12 Pro, S12 models. MobileViT Table 6: iPhone 12, MobileViT-S. Accuracy bars start at 76%.
Worked number. Table 1 starts at PoolFormer-S12: 1.50 ms, 77.2%. It ends at FastViT-S12: 1.40 ms, 79.8%. That is 2.6 points more for 0.10 ms less. The step from 224 to 256 pixels cost 0.75 ms; RepMixer won back 0.67 ms of it.
The FastViT layout that comes out of these tests (Figure 2, Table 2):
Full models on the iPhone 12 Pro (Table 5): FastViT-SA12 takes 1.6 ms for 80.6%. FastViT-MA36 takes 4.5 ms for 83.9%, where ConvNeXt-B needs 8.4 ms for 83.8%. In MobileViT, removing the skip inside the block costs 0.5 points: 77.9% against 78.4% (Figure 12). MobileViT-S also tolerates weight decay from 0.01 down to 0.0001, at 78.4% and 77.4% (Figure 11).
Symptom: attention in every stage buys little accuracy for a lot of time. In Table 11, attention in all four stages costs 11.7 ms for 82.0%. Attention in stage 4 only costs 1.6 ms for 80.6%. Measure each stage’s share of latency. Fix: attend only where the map is small, as both papers do.
Chapter 8
Set a time budget and find the most accurate model under it, on each paper’s phone
Each paper times its models on its own phone. MobileViT uses an iPhone 12. FastViT uses an iPhone 12 Pro with iOS 16 and Core ML Tools 6. The same DeiT model takes 10.99 ms in one paper and 4.8 ms in the other. So keep the two benches on separate axes.
Pick a paper’s bench. Drag the budget: models to the right of the line are too slow. Rings mark the best model of each family under budget. Tap a dot for its numbers.
FastViT bench: Tables 5 and 16 (mobile latency, each model at its own input size). MobileViT bench: Tables 3, 6 and 9. Family labels are ours.
Worked number. With a 1.5 ms budget on the iPhone 12 Pro, FastViT-S12 takes 1.4 ms for 79.8%. The best CNN is MobileOne-S3: 1.5 ms for 78.1%. No ViT fits, because DeiT-Ti needs 4.8 ms (Table 16). On the iPhone 12 bench, every transformer needs more than 5 ms.
Two patterns stand out on the FastViT bench. Below 2 ms, the only hybrids are FastViT and EdgeViT models. FastViT-MA36 matches ConvNeXt-B (83.9% against 83.8%) at about half the latency.
Symptom: a model ranks well in a paper and badly on your phone. The tables mix input sizes (FastViT runs at 256, most others at 224) and use other chips and OS versions. Measure your shortlist yourself: batch 1, the median of 100 runs, as FastViT does. Fix: treat the explorer as a shortlist, not a verdict.
Chapter 9
Keep the numbers, the terms, a checklist, the core code, and where to read next
MobileViT adds global attention to a mobile CNN with an unfold and fold that keep the pixel grid. It wins accuracy per parameter and loses latency. FastViT keeps attention for the last stage and makes everything else foldable, so the phone runs one convolution where training saw branches and skips.
| Number | What it is | Where |
|---|---|---|
| 78.4%, 5.6 M | MobileViT-S on ImageNet, basic augmentation | MobileViT Figure 3c |
| 74.8% against 67.4% | MobileViT-XS against MobileNetv3 at about 2.5 M parameters | MobileViT Figure 6b |
| 7.28 ms against 0.92 ms | MobileViT-XS against MobileNetv2, iPhone 12 | MobileViT Table 3 |
| 10.99 ms against 10.56 ms | DeIT against PiT at 1.3 and 0.7 GFLOPs | MobileViT Table 3 |
| 2.25 ms to 1.58 ms | skip kept against RepMixer folded, same 11.9 M and 2.4 GFLOPs | FastViT Table 1 |
| 25.1% and 43.9% | latency cut of RepMixer over Pooling at 384 and 1024 pixels | FastViT Figure 3 |
| 75.6% at 0.8 ms | FastViT-T8, iPhone 12 Pro | FastViT Table 16 |
| 83.9% at 4.5 ms | FastViT-MA36; ConvNeXt-B needs 8.4 ms for 83.8% | FastViT Table 5 |
| Term | Plain meaning |
|---|---|
| Latency | measured time for one image on one device |
| Receptive field | the input pixels that can change one output pixel |
| Inductive bias | a belief built into the layer, such as “near pixels belong together” |
| Unfold, fold | reshapes between H × W × d and P × N × d, exact inverses |
| Structural reparameterization | train with linear branches, merge them into one layer to ship |
| RepMixer | depthwise conv on BN of X, plus X; folds to one depthwise conv |
| Memory access cost | time spent moving tensors, which a skip connection adds |
The whole MobileViT block in PyTorch. We ran it: a 1 × 96 × 32 × 32 input returns the same shape.
import torch, torch.nn as nn
class MobileViTBlock(nn.Module): # x: [B, C, H, W] in and out
def __init__(self, C, d, L, n=3, h=2, w=2, heads=4):
super().__init__()
self.h, self.w = h, w
self.local = nn.Sequential(nn.Conv2d(C, C, n, padding=n // 2), nn.Conv2d(C, d, 1))
layer = nn.TransformerEncoderLayer(d, heads, 2 * d, batch_first=True)
self.glob = nn.TransformerEncoder(layer, L)
self.proj = nn.Conv2d(d, C, 1)
self.fuse = nn.Conv2d(2 * C, C, n, padding=n // 2)
def forward(self, x):
B, C, H, W = x.shape
h, w = self.h, self.w
y = self.local(x) # [B, d, H, W]
d = y.shape[1]
u = y.reshape(B, d, H // h, h, W // w, w).permute(0, 3, 5, 2, 4, 1)
u = u.reshape(B * h * w, (H // h) * (W // w), d) # unfold: [B*P, N, d]
g = self.glob(u) # attend over N, per place p
g = g.reshape(B, h, w, H // h, W // w, d).permute(0, 5, 3, 1, 4, 2)
y = self.proj(g.reshape(B, d, H, W)) # fold, then [B, C, H, W]
return self.fuse(torch.cat([x, y], dim=1)) # [B, 2C, H, W] to [B, C, H, W]
blk = MobileViTBlock(C=96, d=144, L=2) # MobileViT-S, 32 x 32 stage
print(blk(torch.randn(1, 96, 32, 32)).shape) # torch.Size([1, 96, 32, 32])
Our sketch, not the authors’ code: four heads and no Swish are our choices. The reparameterization fold is in Chapter 5.
For the ViT itself, see the Vision Transformer lesson. For a wider tour of hybrids, see conv-transformer mobile hybrids. Two later mobile papers: MobileNetV4 and EfficientViT. Both papers here appear as related reading in our MIT 6.5940 lesson on vision transformers.
MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer by Sachin Mehta and Mohammad Rastegari, ICLR 2022, arxiv.org/abs/2110.02178. FastViT: A Fast Hybrid Vision Transformer using Structural Reparameterization by Pavan Kumar Anasosalu Vasu, James Gabriel, Jeff Zhu, Oncel Tuzel and Anurag Ranjan, ICCV 2023, arxiv.org/abs/2303.14189. Every number comes from these papers, except where a device says it is illustrative.