At a 56×56 grid, one attention layer fills a score table 4,096 times bigger than at a 7×7 grid. So a phone backbone runs cheap convolutions at high resolution and spends attention only where the grid is small.
Pick the grid where attention runs. Watch the score table grow with the square of the token count. Then we build, piece by piece, the receptive field, MobileViT, the hybrid block, reparameterization, cheaper attention heads and the latency budget.
You need a rough idea of a convolution: a small filter that slides over an image. You need a rough idea of attention: every token takes a weighted average of every token. And a little Python. We build the rest from zero.
The numbers come from the papers: Mehta and Rastegari, MobileViT (ICLR 2022); Vasu et al., FastViT (2023) and MobileOne (2022); Liu et al., EfficientViT (CVPR 2023); Li et al., EfficientFormer; Maaz et al., EdgeNeXt; Dai et al., CoAtNet. Each device labels its toy numbers.
The grids are the four stages of a typical backbone on a 224×224 image (strides 4, 8, 16 and 32). Each square's area is the count of attention scores, N×N, for one head. The counts are exact arithmetic.
Chapter 0
See why a phone camera model must be fast and see far at once, and why neither a plain CNN nor a plain ViT gives both
You build the feature that blurs the background in a video call. At 60 frames per second, each frame has 1000 / 60 = 16.7 ms. The backbone gets only part of that. The camera, the mask head and the screen need time too.
The backbone is the network that turns pixels into features. Two families compete. A CNN (convolutional network) slides small filters over the image. It is fast, but each filter sees only a small patch.
A ViT (vision transformer) cuts the image into patches and lets every patch attend to every other patch. It sees the whole image, but it is slow. Below are real phone timings for both, and for the first hybrid.
Each bar is one backbone's measured time for one image. Pick the processor and the frame rate. The line is the whole frame budget.
Times are from the MobileViT paper, Table 11, on an iPhone 12. MobileViT (the XS model, 2.3M parameters) runs at 256×256; the others at 224×224. The budget line is the full frame time, so a real app has less.
Read the CPU bars at 60 fps. DeiT, a small ViT, needs 28.15 ms and misses the frame. MobileNetv2, a CNN, needs 7.50 ms and fits. MobileViT-XS, an early popular conv-transformer hybrid (a network that mixes convolution and attention), sits between them at 17.86 ms and also misses.
Why build the hybrid at all? Accuracy. MobileViT reaches 78.4% top-1 on ImageNet with 5.6M parameters, 3.2 points above MobileNetv3 at a similar size. The CNN is fast but misses context far from each pixel. The ViT has the context but not the speed.
The failure to watch for: a model that wins on a GPU leaderboard and drops frames on the phone. Measure it on the target chip, per frame, with the processor named. The fix is the subject of this lesson. Use convolution for local work and spend attention only where it is cheap.
Chapter 1
Grow a convolution's view layer by layer, and compare it with one attention layer that sees everything at once
To mask a person, the model must know that a strand of hair belongs to a head 100 pixels away. One output pixel can use only the input pixels that connect to it. That region is its receptive field: the patch of the input that can change one output.
A 3×3 convolution connects each output to a 3×3 patch. Stack a second one and the output reaches a 5×5 patch, because each neighbour already saw one pixel further. Each layer adds the kernel width minus one. Call the number of stacked layers L, the kernel width k, and the receptive field width R.
R equals one plus L times, k minus one.
Start from one pixel. Each of the L layers widens the view by k minus one pixels. The total is R.
With k = 3 and L = 6, R = 1 + 6 × 2 = 13 pixels. To span a 224-pixel image you need 1 + 2L ≥ 224, so L = 112 layers.
The warm cell is one output. Teal is the input it can see. Add layers, change the kernel, or switch to one attention layer.
A 25×25 input grid, stride 1, no downsampling. The cost per layer is the kernel area, k×k multiply-adds per input and output channel pair.
A bigger kernel climbs faster but costs more. A 7×7 kernel adds 6 pixels per layer, so 38 layers reach 224 pixels. Each of those layers costs 49 / 9 = 5.4 times a 3×3 layer. Real CNNs also downsample: a stride-2 layer halves the grid, so every later layer covers twice the image.
Attention has no climb. In one layer, every token reads every token, so the receptive field is the whole image at depth one. The price is in the next chapter.
The failure: a mask that cuts off the top of a head. To measure it, compare errors on large objects with errors on small ones. If large objects fail far more, the model lacks reach. The fix is more downsampling before the deep layers, or one global layer.
Chapter 2
Count the multiply-adds of one attention layer, and find the grid size where it costs more than a convolution
Attention compares every token with every token. Double the tokens and you double the rows and the columns of the comparison table, so the work goes up four times. That one fact decides where a phone backbone puts attention.
We count cost in multiply-adds: one multiplication followed by one addition, the unit a chip executes. Papers quote FLOPs. Some mean multiply-adds, some mean twice that, so check which.
Name the parts. A grid of side s holds N = s × s tokens. Each token is a vector of C channels. One attention layer scores every pair of tokens with a dot product of length C, then takes a weighted sum of C-long vectors. Call the multiply-adds of those two steps A.
A equals two times N squared times C.
Count the pairs, N times N. Each pair costs C multiply-adds to score and C more to sum. Multiply them out to get A.
With made-up C = 128 at a 14×14 grid, N = 196 and A = 2 × 196² × 128 = 9.8 million. At 28×28, N = 784 and A = 157.4 million: 16 times more for 4 times the tokens.
A 3×3 convolution with C channels in and out costs 9 · N · C² multiply-adds. It grows with N, not N². So there is a grid size where attention overtakes it: 2N²C = 9NC² when N = 4.5C.
Purple is attention, teal is a 3×3 convolution. Drag the grid side. Change the channel count and watch the crossover move.
Exact counts from the two formulas. The attention count leaves out the query, key, value and output projections; Chapter 4 adds them.
With C = 128 the crossover is N = 576 tokens, a 24×24 grid. Early stages have big grids and few channels, so attention there is costly. Late stages have small grids and many channels, so attention there is cheap.
The failure: attention placed at stage 1 to "see more". The symptom is a memory spike and a slow first stage. Profile per stage. Move the attention down to 16×16 or smaller.
Chapter 3
Step one feature map through MobileViT's block: local convolution, unfold, transformer, fold, fuse
MobileViT (Mehta and Rastegari, Apple, ICLR 2022) starts as a MobileNet: cheap convolutions shrink a 256×256 image. At three stages, with grids of 32×32, 16×16 and 8×8, it inserts a MobileViT block with 2, 4 and 3 transformer layers. Step through one block below.
Each colour is one position inside a 2×2 patch. Press Next. At the transformer step, one position attends to the same position in every other patch.
Shapes follow the paper's block (Section 3.1) at the 32×32 stage of MobileViT-XS: d = 96, patches of 2×2. The input channel count C = 48 and the 8×8 drawing grid are illustrative.
The five steps:
Why unfold? Attention over every pixel would compare all H·W pixels with each other. Unfolding runs P smaller attentions over N = H·W / P patches each. Call the transformer width d.
M equals N squared, times P, times d.
Count the patch pairs, N times N. Run that once for each of the P positions. Each pair costs d multiply-adds. Per-pixel attention would cost (P·N)²·d, so the unfold saves a factor of P.
At 32×32 with P = 4, N = 256 and d = 96: M = 256² × 4 × 96 = 25.2 million. Per-pixel attention over 1,024 pixels: 1,024² × 96 = 100.7 million, 4 times more.
The trade worked on accuracy. MobileViT-XXS, XS and S reach 69.0%, 74.8% and 78.4% top-1 with 1.3M, 2.3M and 5.6M parameters. It did not work on speed: Chapter 0 showed the XS model at 7.28 ms on the Neural Engine, against 0.92 ms for MobileNetv2. The paper says mobile chips have tuned kernels for convolutions and not yet for transformers.
The failure: an input size that is not a multiple of the patch size. Unfold then needs padding or a resize, which costs time. The paper picks 2×2 because its feature maps are multiples of 2.
Chapter 4
Fill the three slots of a hybrid block and find which one costs the most
Open MobileViT, FastViT, EfficientViT or EdgeNeXt and you find the same three slots in each block. Each slot adds its output back to its input, a residual connection, so a slot can learn to do nothing.
| Slot | What it mixes | Usual operator | Multiply-adds |
|---|---|---|---|
| 1. Local | each token with its neighbours | depthwise 3×3 convolution (one filter per channel) | 9·N·C |
| 2. Global | each token with every token | attention, or a cheaper stand-in | 4·N·C² + 2·N²·C |
| 3. Channel | the channels of one token | MLP: 1×1 to 4C, then back to C | 8·N·C² |
The global slot needs a full count now. Four C-by-C matrices act on each of the N tokens: they make the query, key and value, and project the result. Those four projections cost 4·N·C². The mixing from Chapter 2 adds 2·N²·C. Call the total G.
G equals four N C squared, plus two N squared C.
Add the projection cost, which grows with N, to the mixing cost, which grows with N squared. Compare G with the MLP's 8·N·C². They are equal when 2·N²·C = 4·N·C², that is when N = 2C.
With made-up N = 196 (14×14) and C = 128: projections 12.8 million plus mixing 9.8 million gives G = 22.7 million. The MLP costs 25.7 million and the local slot 0.23 million. The MLP is the biggest slot.
Each bar is one slot. Purple has two shades: projections and mixing. Drag the grid side and pick C to find where attention takes over.
Exact counts from the table's formulas for one block with MLP ratio 4. Normalisation and activations are left out; they add bytes more than multiply-adds.
Order matters too. The local slot runs first, so attention reads tokens that already hold clean local structure. This local bias also helps the network learn from ImageNet-sized data without the huge pretraining a plain ViT needs.
The failure: shrinking attention to save time while the MLP is the real cost. Count each slot before you optimise. At small grids, cut the MLP ratio first.
Chapter 5
Fold three parallel branches into one convolution, exactly, and see why it saves time but almost no multiply-adds
Three parallel paths train better than one 3×3 convolution: a 3×3 branch, a 1×1 branch and a skip. On a phone, each path costs a kernel launch and a memory trip. Structural reparameterization trains the three paths, then rewrites them as one convolution with the same output. RepVGG made it popular.
Convolution is linear: convolving with A and with B, then adding, equals convolving once with A + B. A 1×1 kernel and the skip touch only the pixel under them, so as 3×3 kernels they are zeros with one centre value. Call the 3×3 kernel W3, the 1×1 kernel padded to 3×3 W1, and the skip as a kernel I.
W-fused equals W-three plus W-one plus I.
Write all three branches as 3×3 kernels. Add them cell by cell. Only the centre cell gets help from W-one and I.
With made-up W3 = [[0,1,0],[1,2,1],[0,1,0]] and a 1×1 weight of 0.5, the centre becomes 2 + 0.5 + 1 = 3.5. So Wfused = [[0,1,0],[1,3.5,1],[0,1,0]], and the outputs match to 10−15.
Set the branch weights. The check runs three branches and the fused kernel on one patch.
A single-channel toy with a fixed, illustrative test patch. Real branches also carry a batch norm, which folds in first (below).
Each real branch ends in a batch norm. At inference it subtracts a stored mean μ and divides by a stored spread σ. Then it scales by a learned γ and shifts by a learned β. That is linear too, so it folds into the kernel W and a bias.
W-prime equals gamma times W over sigma, and b-prime equals beta minus gamma times mu over sigma.
Scale every weight of W by gamma over sigma. Move the mean and the shift into one bias b-prime. The convolution alone now does both jobs.
With made-up W = 2, γ = 1.5, μ = 0.4, σ = 0.5, β = 0.1: W′ = 6 and b′ = 0.1 − 1.2 = −1.1. For input 0.8, the two-step path gives 1.5 × (1.6 − 0.4) / 0.5 + 0.1 = 3.7, and 6 × 0.8 − 1.1 = 3.7.
The fold saves launches and memory trips, not multiply-adds (Chapter 7). FastViT's token mixer, RepMixer, trains as batch norm, depthwise convolution and a skip, and runs as one depthwise convolution. MobileOne, built on folded blocks, reaches 75.9% top-1 in under 1 ms on an iPhone 12.
The failure: a fused model that disagrees with the trained one. Run both on one batch in evaluation mode. A gap above about 10−4 usually means the batch norm used batch statistics, or the 1×1 weight missed the centre.
Chapter 6
Give each attention head its own slice of the channels, then chain the heads so later ones build on earlier ones
Reparameterization made the convolutions cheaper. EfficientViT (Liu et al., CVPR 2023) goes after the attention slot. In multi-head attention, h heads each compute their own score table. In the standard form, every head projects its query, key and value from all C input channels. The EfficientViT authors measured high similarity between heads, most of all in the last blocks: several heads computed nearly the same map.
Cascaded group attention (CGA) makes two changes.
Call head j's slice of the input Xj, the previous head's output Yj−1, and the input head j attends over X′j.
X-prime-j equals X-j plus Y-j-minus-one.
Give head j its own slice X-j. Add what head j−1 found, Y-j-minus-one. Head j attends over the sum X-prime-j. Concatenate all head outputs and project.
With made-up C = 128 and h = 4, each head reads 32 channels. Standard projections for query, key and value need 3 × 128 × 128 = 49,152 weights. CGA needs 3 × 128 × 128 / 4 = 12,288: a factor of h fewer.
The strip on top is the C channels. Lines show what each head reads. Switch the wiring and the head count.
C = 128 is illustrative. The weight counts are exact for query, key and value projections of width C/h per head. EfficientViT also shrinks the query and key width; that is left out here.
EfficientViT also uses a sandwich layout: one attention layer between feed-forward layers, because attention is the slot with the most memory-bound steps. EfficientViT-M5 reaches 77.1% top-1 against 75.2% for MobileNetV3-Large, with 40% more images per second on a V100 GPU.
The failure: splitting heads without the cascade, and losing accuracy because each head sees less. Check by ablation: train both and compare. The paper's fix is the cascade, plus a depthwise convolution on each head's query.
Chapter 7
Put each layer on a roofline and see when arithmetic sets the time and when memory does
Look at two published pairs. EfficientViT-M5 has 522M FLOPs, 2.4 times MobileNetV3-Large's 217M, yet it runs 40% faster on a V100 GPU. On an iPhone 12, MobileViT-XS takes 7.9 times as long as MobileNetv2 on the Neural Engine. The multiply-add count did not predict either result.
A chip does two jobs: arithmetic and moving bytes between memory and the arithmetic units. Whichever takes longer sets the time. Call a layer's multiply-adds F, the bytes it moves B, the chip's peak multiply-adds per second Π, and its memory bandwidth in bytes per second β.
t equals the max of F over capital pi, and B over beta.
Work out the arithmetic time, F over capital pi, and the memory time, B over beta. The layer takes the longer one. Their ratio F / B is the arithmetic intensity: multiply-adds per byte.
A made-up chip has Π = 1012 per second and β = 1010 bytes per second, a ridge of 100 per byte. Layer A: F = 1 million, B = 4,000 bytes, t = max(1 µs, 0.4 µs) = 1 µs. Layer B: same F, B = 40,000 bytes, t = max(1, 4) = 4 µs. Same multiply-adds, 4 times the time.
Left of the ridge, memory sets the time. Right of it, arithmetic does. Pick a layer, then halve its multiply-adds and see if the time moves.
Intensities in fp16 for a 14×14×128 feature map. Depthwise 225,792 multiply-adds over 102,656 bytes; 1×1 conv 3.2M over 133,120 bytes; softmax over 4 heads of 196×196 scores; matmul 1024³. The chip is the made-up one above.
Three costs hide outside F. Depthwise convolutions read a whole feature map for 9 multiply-adds per value. Attention adds reshapes, transposes and a softmax: bytes with almost no arithmetic. Every kernel also pays a fixed launch cost. EfficientViT names these memory-bound steps as the main thing that slows attention down.
Phones add one more trap. The fast accelerator may run convolutions well and some attention steps poorly, so those steps fall back to the CPU or GPU. MobileViT's own paper names this as the reason it trails MobileNetv2 on device.
The failure: you halve a model's multiply-adds and latency does not move. Profile per layer on the target chip and plot each on the roofline. If it sits left of the ridge, cut bytes or launches: fuse layers, fold branches (Chapter 5), drop reshapes.
Chapter 8
Place attention, fold the branches and split the heads in a four-stage backbone, then read its multiply-adds and its time
Every lever from Chapters 2 to 7 is in one device. A 256×256 image goes through a stem and four stages. Their grids are 64, 32, 16 and 8; their channels are 32, 64, 96 and 128. Each stage has conv blocks: a depthwise token mixer plus an MLP. You can add one attention block per stage. You also choose to fold the token mixers and to split the heads.
Your goal: global mixing at as high a resolution as you can, under a budget of 2.5 ms on a made-up chip.
Toggle attention per stage. Turn on folding and split heads. Watch the two bars: they do not move together.
An illustrative toy. Multiply-adds are exact for this made-up backbone. Time uses Chapter 7's roofline per kernel on a toy chip (1012 multiply-adds/s, 3 × 1010 bytes/s, fp16) plus 5 µs per kernel launch. Unfolded mixers run three branches and two adds. Not a measurement of any real chip or model.
Try these in order:
The pattern matches the papers. FastViT puts attention only in stage 4. RepMixer and MobileOne fold their conv blocks. The number that ships is the time on the chip.
Chapter 9
Compare published mobile backbones on accuracy and size, and match the design to your data, budget and chip
A hybrid is not always the answer. Three regimes decide it.
| Regime | Pick | Why |
|---|---|---|
| Phone or robot, real time, need context | a hybrid | convolutions keep it fast; a little low-resolution attention adds accuracy |
| Tiny chip, easy local task | a folded CNN (MobileOne, MobileNet) | attention costs time and buys little when the signal is local |
| Data centre, huge data, no latency limit | a large ViT or a large hybrid | with enough data the convolution prior matters less |
Hybrids also win at the large end when data is limited. CoAtNet (Dai et al., 2021) stacks convolution stages before attention stages and reaches 86.0% top-1 on ImageNet with no extra data, and 88.56% with ImageNet-21K pretraining. The convolution prior helps most when data or compute is short.
Each dot is a published model. Drag the parameter cap. Models over the cap fade. A ring marks the best one under it.
ImageNet-1k top-1 and parameters: MobileViT XXS, XS, S (MobileViT, Table 4); EdgeNeXt XXS and S (EdgeNeXt abstract); EfficientViT-M5 and MobileNetV3-Large (EfficientViT, Table 2). Parameter count is not latency; see the table below.
Latency only compares on the same device. These are each paper's own claims:
| Model | Top-1 | Latency, device |
|---|---|---|
| MobileOne (best under 1 ms) | 75.9% | under 1 ms, iPhone 12 |
| EfficientFormer-L1 | 79.2% | 1.6 ms, iPhone 12 |
| FastViT-S12 | 79.8% | 1.4 ms, iPhone 12 Pro |
| FastViT-SA12 | 80.6% | 1.6 ms, iPhone 12 Pro |
| FastViT-MA36 | 83.9% | 4.5 ms, iPhone 12 Pro |
| MobileViT-XS | 74.8% | 7.28 ms, iPhone 12 Neural Engine |
Read the gap. MobileViT-XS (2021) took 7.28 ms for 74.8%. Two years later FastViT-S12 claims 79.8% in 1.4 ms. Three ideas closed the gap: folded blocks, attention only at the end, and design by measured time.
The failure: picking the newest model off a leaderboard. If your chip runs attention poorly, a folded CNN may beat it. Measure two or three candidates on your own device at your input size.
Chapter 10
Keep the numbers, the terms, the checklist and the code in one place
A mobile hybrid is a budget plan. Convolutions do the local work at high resolution. Attention runs only on small grids, where N² is small. Inference folds the branches. And the time on the target chip is the only score that counts.
| What | Number | Why it matters |
|---|---|---|
| Frame at 60 fps | 16.7 ms | the whole app shares it |
| Receptive field, 3×3 | R = 1 + 2L; 112 layers for 224 px | convolutions climb slowly |
| Score table, 56×56 vs 7×7 | 4,096 times | attention cost is N² |
| Attention vs 3×3 conv | crossover at N = 4.5C | 24×24 for C = 128 |
| Attention slot vs MLP | equal at N = 2C | MLP wins below a 16×16 grid at C = 128 |
| MobileViT unfold | P = 4 times less score work | 2×2 patches |
| MobileViT XXS / XS / S | 69.0 / 74.8 / 78.4%; 1.3 / 2.3 / 5.6M | accuracy from attention |
| MobileViT-XS vs MobileNetv2, iPhone 12 | 7.28 vs 0.92 ms (Neural Engine) | the latency gap the later papers closed |
| CGA projections | h times fewer | 49,152 to 12,288 weights at C = 128, h = 4 |
| EfficientViT-M5 | 77.1%, 522M FLOPs, +40% V100 speed vs MobileNetV3-L | more FLOPs, faster anyway |
| FastViT-S12 | 79.8% at 1.4 ms, iPhone 12 Pro | folded blocks, attention late |
| Term | Meaning |
|---|---|
| Receptive field | The input patch that can change one output. |
| Multiply-add | One multiplication plus one addition; papers count FLOPs as one or two of these. |
| Hybrid block | Local mixing, global mixing and channel mixing, each with a residual. |
| Unfold / fold | MobileViT's regrouping of pixels by patch position, and its inverse. |
| Reparameterization | Rewriting trained parallel branches as one equal convolution. |
| Cascaded group attention | Heads that read separate channel slices, each fed the previous head's output. |
| Arithmetic intensity | Multiply-adds per byte moved. |
| Memory-bound | A layer whose time the bytes set, not the arithmetic. |
pythonimport numpy as np def block_cost(s, C, mlp_ratio=4): N = s * s # tokens on an s x s grid local = 9 * N * C # depthwise 3x3 glob = 4 * N * C**2 + 2 * N**2 * C # projections + mixing channel = 2 * mlp_ratio * N * C**2 # 1x1 up, 1x1 down return local, glob, channel def fold_bn(W, gamma, beta, mu, var, eps=1e-5): # W: [Cout, Cin, k, k] sd = np.sqrt(var + eps) return W * (gamma / sd)[:, None, None, None], beta - gamma * mu / sd def fuse_branches(W3, b3, W1, b1, Wid, bid): # each branch already BN-folded W = W3.copy() W[:, :, 1, 1] += W1[:, :, 0, 0] + Wid[:, :, 0, 0] # 1x1 and skip land on the centre return W, b3 + b1 + bid def roofline_time(F, B, peak=1e12, bw=1e10): return max(F / peak, B / bw) # seconds: the slower job sets the pace print(block_cost(14, 128)) # (225792, 22679552, 25690112)
Now press Present or Teach and explain five things from memory. Why attention cost grows with N². How MobileViT unfolds. Which slot of a block costs most. How three branches fold into one. Why a memory-bound layer ignores its FLOPs. Then go back to the hero and place the attention again. Say the score table size before you press.
Mehta and Rastegari, MobileViT, ICLR 2022. Vasu et al., FastViT, 2023, and MobileOne, 2022. Liu et al., EfficientViT, CVPR 2023. Li et al., EfficientFormer, 2022. Maaz et al., EdgeNeXt, 2022. Dai et al., CoAtNet, 2021. Ding et al., RepVGG, 2021. Luo et al., Understanding the Effective Receptive Field, 2016.