MobileViT & FastViT

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.

Compare four designs

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

Three Numbers, One Phone

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.

NumberWhat it countsWhat it misses
Parametersthe learned weights; it sets the file sizehow often each weight runs
FLOPsmultiply and add operations for one imagememory traffic, parallelism, the chip
Latencymeasured time for one image on one devicenothing, 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.

Time four models on three chips

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.

Failure: the GPU winner

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.

  1. Local and global: what one convolution sees, what one attention layer sees.
  2. The MobileViT block: the hero’s MobileViT stop, step by step.
  3. Unfold, attend, fold: the reshape, with real tensor shapes and code.
  4. The full MobileViT: three sizes, their wins, and the speed they lose.
  5. Train with branches: fold BatchNorm and branches into one kernel.
  6. RepMixer: the hero’s fold switch, and why a skip costs time.
  7. Results and ablations: what each design choice bought.
  8. Latency explorer: a time budget on each paper’s phone.
  9. Field guide: numbers, terms, a checklist, the core code.
PiT has about half the FLOPs of DeIT. What happens to latency on the iPhone 12?

Chapter 1

Local and Global

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.

Grow a receptive field

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.

3

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).

Failure: a small ViT without heavy augmentation

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.

How many 3 × 3 layers does a pixel at the centre of a 31 × 31 map need to see the whole map?

Chapter 2

The MobileViT Block

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).

Step through the block

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.

  1. A 3 × 3 convolution mixes each pixel with its neighbours. A 1 × 1 convolution lifts C channels to d.
  2. Unfold cuts the map into 2 × 2 patches and groups pixels by their place in the patch.
  3. L transformer layers attend across patches, once for each place p.
  4. Fold puts every pixel back where it came from.
  5. A 1 × 1 convolution returns to C channels. The block concatenates its input and fuses both with a 3 × 3 convolution.
XU(p)
The pixels at place p of every patch: N vectors of size d.
Transformer
L layers of attention and a feed-forward net with hidden size 2d (Appendix A).
XG(p)
The same N pixels after global mixing, same shape.
P
Pixels in one patch, h × w = 4.

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.

Failure: a patch wider than the kernel

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.

The top-left pixel of one patch attends only to top-left pixels of other patches. Why can it still use information from the whole map?

Chapter 3

Unfold, Attend, Fold

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.

Unfold an 8 × 8 map

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.

0

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.

A worked shape example

Take the 32 × 32 stage of MobileViT-S after the 1 × 1 convolution: a tensor of 32 × 32 × 144.

  1. Patches are 2 × 2, so P = 4 and N = 1,024 ÷ 4 = 256.
  2. Unfold: 32 × 32 × 144 becomes 4 × 256 × 144.
  3. Attend: 4 sequences of 256 tokens, so 4 × 256 × 256 = 262,144 scores per head and layer.
  4. Fold: back to 32 × 32 × 144, every value in its old place.

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.

Failure: a patch that does not divide the map

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.

A 16 × 16 × 192 tensor is unfolded with 2 × 2 patches. What shape comes out?

Chapter 4

The Full MobileViT

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.

SizeParametersd at 32, 16, 8ImageNet top-1
XXS1.3 M64, 80, 9669.0%
XS2.3 M96, 120, 14474.8%
S5.6 M144, 192, 24078.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).

Read four benchmarks

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).

Failure: accurate but slow

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.

Which statement matches MobileViT Table 3?

Chapter 5

Train With Branches, Run One Convolution

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.

BN(z)
The output for one value z of one channel.
μ
The channel mean stored during training.
σ
The square root of the stored variance plus a tiny ε.
γ
A learned scale.
β
A learned shift.

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.

Fold three branches

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.

The worked fold

  1. Branch A: a 3 × 3 kernel with 1 above, below, left and right of a centre of −2. BN: γ 1.5, β 0.2, μ 0.5, σ² 4. Scale 1.5 ÷ 2 = 0.75. Bias 0.2 − 0.75 × 0.5 = −0.175.
  2. Branch B: a 1 × 1 weight of 0.5, BN γ 1, β 0.1, μ 0, σ² 1. Centre 0.5, bias 0.1.
  3. Branch C: identity, BN γ 0.8, β 0, μ 0.25, σ² 1. Centre 0.8, bias −0.2.
  4. Sum: edges 0.75, centre −1.5 + 0.5 + 0.8 = −0.2, bias −0.275.

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).

Failure: the folded model disagrees

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.

A BN has γ = 2, β = 1, μ = 3, σ = 4. It follows a convolution with weight 0.5. What single convolution replaces both?

Chapter 6

RepMixer: Fold the Skip Away

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.

DWConv
A depthwise convolution: one 3 × 3 kernel per channel, no mixing across channels.
σ
A non-linear activation. RepMixer removes it, so every piece stays linear.
+ X
The skip. In the folded kernel it becomes a 1 added at the centre.
ConvMixer
FastViT Equation 1.
Training form
FastViT Equation 2.
Inference form
FastViT Equation 3: one layer, no branch.

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.

Count the traffic

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.

384

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.

Failure: the edge pixels drift

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).

Why can RepMixer fold into one depthwise convolution while the ConvMixer block cannot?

Chapter 7

Results and Ablations

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.

Read an ablation

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).

Failure: attention everywhere

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.

In FastViT Table 1, what did RepMixer do to the 256-pixel model?

Chapter 8

Latency Explorer

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.

Spend a latency budget

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.

1.5 ms

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.

Failure: the table and your phone disagree

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.

Why does the explorer keep the two papers on separate benches?

Chapter 9

Field Guide

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.

The numbers

NumberWhat it isWhere
78.4%, 5.6 MMobileViT-S on ImageNet, basic augmentationMobileViT Figure 3c
74.8% against 67.4%MobileViT-XS against MobileNetv3 at about 2.5 M parametersMobileViT Figure 6b
7.28 ms against 0.92 msMobileViT-XS against MobileNetv2, iPhone 12MobileViT Table 3
10.99 ms against 10.56 msDeIT against PiT at 1.3 and 0.7 GFLOPsMobileViT Table 3
2.25 ms to 1.58 msskip kept against RepMixer folded, same 11.9 M and 2.4 GFLOPsFastViT Table 1
25.1% and 43.9%latency cut of RepMixer over Pooling at 384 and 1024 pixelsFastViT Figure 3
75.6% at 0.8 msFastViT-T8, iPhone 12 ProFastViT Table 16
83.9% at 4.5 msFastViT-MA36; ConvNeXt-B needs 8.4 ms for 83.8%FastViT Table 5

The terms

TermPlain meaning
Latencymeasured time for one image on one device
Receptive fieldthe input pixels that can change one output pixel
Inductive biasa belief built into the layer, such as “near pixels belong together”
Unfold, foldreshapes between H × W × d and P × N × d, exact inverses
Structural reparameterizationtrain with linear branches, merge them into one layer to ship
RepMixerdepthwise conv on BN of X, plus X; folds to one depthwise conv
Memory access costtime spent moving tensors, which a skip connection adds

A checklist before you ship a backbone

The core as code

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.

Where to go next

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.

Credit and sources

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.

Design for the graph the phone runs. Parameters and FLOPs describe the model. Latency describes the model on a chip. Fold what is linear, and attend only where the map is small.
Go back to the hero. Pick the FastViT block and switch the fold off and on: the parameter and FLOP bars stay still, and only the latency bar moves. Then try to explain why in Teach mode.
MobileViT & FastViT
Based on “MobileViT” by Mehta and Rastegari (2022), arXiv 2110.02178, and “FastViT” by Vasu, Gabriel, Zhu, Tuzel and Ranjan (2023), arXiv 2303.14189 · Back to Veanors