Conv-Transformer Mobile Hybrids

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.

Place the attention

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

A Phone, a Frame, a Deadline

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.

Fit four backbones into one frame

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.

processor
frame rate

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.

The road

  1. Receptive field: how far one output sees, for a convolution and for attention.
  2. The quadratic bill: why attention cost grows with the square of the token count. This is the hero.
  3. MobileViT: attention inside a convolutional network, through unfold and fold.
  4. The hybrid block: local, global and channel mixing, and which one costs most.
  5. Reparameterization: train with three branches, run with one convolution.
  6. Cascaded group attention: give each head a slice of the channels.
  7. Latency: why fewer multiply-adds can run slower.
  8. Build a backbone: every lever in one device, against a budget.
  9. Choose: when a hybrid is right, with the papers' numbers.
  10. Field guide: numbers, terms, code and links.
On the iPhone 12 CPU at 60 fps, which statement is true?

Chapter 1

Receptive Field: How Far One Output Sees

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.

Say it aloud

R equals one plus L times, k minus one.

R
R the receptive field width, in input pixels, for stride-1 layers.
L
L the number of stacked convolution layers.
k
k the kernel width: 3 for a 3×3 filter.
In plain words

Start from one pixel. Each of the L layers widens the view by k minus one pixels. The total is R.

With numbers

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.

Grow the view of one output pixel

The warm cell is one output. Teal is the input it can see. Add layers, change the kernel, or switch to one attention layer.

3
kernel k

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.

How many stacked stride-1 3×3 layers does one output need to see 41 pixels across?

Chapter 2

The Quadratic Bill of Attention

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.

Say it aloud

A equals two times N squared times C.

A
A the multiply-adds to mix tokens in one attention layer: the score table plus the weighted sum.
N2
N squared the number of token pairs. N is the token count, s times s.
C
C the channels per token: the length of each dot product.
2
two one pass to score the pairs, one pass to sum the values.
In plain words

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 numbers

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.

Find where attention overtakes convolution

Purple is attention, teal is a 3×3 convolution. Drag the grid side. Change the channel count and watch the crossover move.

28
channels C

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.

One attention layer runs at 28×28 (784 tokens) early and 7×7 (49 tokens) late, with the same C. How much more do the early token-mixing multiply-adds cost?

Chapter 3

MobileViT: Attention Inside a Convolutional Network

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.

Step a feature map through the block

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:

  1. Local: a 3×3 convolution, then a 1×1 convolution to d channels. Shape H×W×d.
  2. Unfold: cut the map into 2×2 patches. Group the pixels by their position in the patch: P = 4 groups of N patches each.
  3. Transformer: within each group, every patch attends to every patch. Top-left pixels talk to top-left pixels across the whole map.
  4. Fold: put every pixel back in its place.
  5. Fuse: a 1×1 convolution back to C channels, concatenate with the block input, and a 3×3 convolution mixes them.

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.

Say it aloud

M equals N squared, times P, times d.

M
M the multiply-adds of one score table pass in the MobileViT block.
N2
N squared the patch pairs. N is the number of patches, H times W divided by P.
P
P the pixels per patch: 4 for a 2×2 patch. One attention runs per position.
d
d the transformer width: the length of each dot product.
In plain words

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.

With numbers

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.

What does the unfold step buy in the MobileViT block?

Chapter 4

The Hybrid Block: Local, Global, Channel

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.

SlotWhat it mixesUsual operatorMultiply-adds
1. Localeach token with its neighboursdepthwise 3×3 convolution (one filter per channel)9·N·C
2. Globaleach token with every tokenattention, or a cheaper stand-in4·N·C² + 2·N²·C
3. Channelthe channels of one tokenMLP: 1×1 to 4C, then back to C8·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.

Say it aloud

G equals four N C squared, plus two N squared C.

G
G the multiply-adds of the whole global slot.
4·N·C2
four N C squared the query, key, value and output projections: four C-by-C matrices applied to N tokens.
2·N2·C
two N squared C the token mixing: scores plus weighted sum, from Chapter 2.
In plain words

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 numbers

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.

Price the three slots of one block

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.

14
channels C

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.

A block runs at 14×14 with C = 128 and an MLP ratio of 4. Which slot costs the most multiply-adds?

Chapter 5

Reparameterization: Train Wide, Run Narrow

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.

Say it aloud

W-fused equals W-three plus W-one plus I.

Wfused
W-fused the single 3×3 kernel used at inference.
W3
W-three the trained 3×3 branch kernel.
W1
W-one the 1×1 branch weight, placed in the centre of a 3×3 grid of zeros.
I
I the skip as a kernel: a 1 in the centre, zeros elsewhere.
In plain words

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 numbers

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.

Fold three branches into one kernel

Set the branch weights. The check runs three branches and the fused kernel on one patch.

2.0
0.50

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.

Say it aloud

W-prime equals gamma times W over sigma, and b-prime equals beta minus gamma times mu over sigma.

W′
W-prime the kernel with the batch norm folded in.
γ
gamma the learned scale of the batch norm.
σ
sigma the stored spread of the output.
b′
b-prime the bias the folded convolution adds.
β
beta the learned shift of the batch norm.
μ
mu the stored mean of the output.
In plain words

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 numbers

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.

Why can a 1×1 branch and a skip both fold into only the centre cell of a 3×3 kernel?

Chapter 6

Cascaded Group Attention: Cheaper Heads

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.

  1. Split: cut the C channels into h groups. Head j reads only group j. The heads see different inputs, so they cannot all learn the same map.
  2. Cascade: add head j−1's output to head j's input. Later heads build on earlier ones, so the block gains depth without new weights.

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.

Say it aloud

X-prime-j equals X-j plus Y-j-minus-one.

X′j
X-prime-j what head j projects to its query, key and value. N tokens by C/h channels.
Xj
X-j group j of the input channels: C/h of the C channels.
Yj−1
Y-j-minus-one the output of the head before. For the first head there is none, so X′1 = X1.
In plain words

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 numbers

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.

Wire the heads two ways

The strip on top is the C channels. Lines show what each head reads. Switch the wiring and the head count.

heads h

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.

What two ideas make up cascaded group attention?

Chapter 7

Why Fewer Multiply-Adds Can Run Slower

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

Say it aloud

t equals the max of F over capital pi, and B over beta.

t
t the layer's time, if arithmetic and memory overlap perfectly.
F
F the layer's multiply-adds.
Π
capital pi the chip's peak multiply-adds per second.
B
B the bytes the layer reads and writes: inputs, outputs, weights.
β
beta the memory bandwidth, in bytes per second.
max
the max of the larger of the two times. The slower job sets the pace.
In plain words

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.

With numbers

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.

Put a layer on the roofline

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.

On a chip with a ridge of 100 multiply-adds per byte, a layer does 1M multiply-adds and moves 40,000 bytes. You rewrite it to 0.5M multiply-adds with the same bytes. What happens to its time?

Chapter 8

Build a Backbone Under Budget

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.

Fit global mixing into 2.5 ms

Toggle attention per stage. Turn on folding and split heads. Watch the two bars: they do not move together.

attention at

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:

  1. Pure conv runs in 0.72 ms folded. Global mixing happens only through stacked 3×3 layers.
  2. MobileViT style puts attention at 32, 16 and 8. Unfolded it takes 2.72 ms and misses. Fold the branches: 2.18 ms, inside the budget, with 0.001 GMAC less.
  3. Add attention at 64×64. The time jumps to about 20 ms: the score tables at 4,096 tokens are memory traffic.
  4. Split the heads. The multiply-adds fall by up to 0.03 GMAC, but the time barely moves, because the score tables, not the projections, are the bytes.

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.

In the toy, folding the branches changes the multiply-adds by about 0.001 GMAC but cuts 0.54 ms. Why?

Chapter 9

When a Hybrid Is the Right Choice

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.

RegimePickWhy
Phone or robot, real time, need contexta hybridconvolutions keep it fast; a little low-resolution attention adds accuracy
Tiny chip, easy local taska folded CNN (MobileOne, MobileNet)attention costs time and buys little when the signal is local
Data centre, huge data, no latency limita large ViT or a large hybridwith 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.

Pick a size cap, find the best model

Each dot is a published model. Drag the parameter cap. Models over the cap fade. A ring marks the best one under it.

6.0M

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:

ModelTop-1Latency, device
MobileOne (best under 1 ms)75.9%under 1 ms, iPhone 12
EfficientFormer-L179.2%1.6 ms, iPhone 12
FastViT-S1279.8%1.4 ms, iPhone 12 Pro
FastViT-SA1280.6%1.6 ms, iPhone 12 Pro
FastViT-MA3683.9%4.5 ms, iPhone 12 Pro
MobileViT-XS74.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.

You have a data centre, a billion pretraining images and no latency limit. What is most likely to give the top accuracy?

Chapter 10

Field Guide

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.

The numbers

WhatNumberWhy it matters
Frame at 60 fps16.7 msthe whole app shares it
Receptive field, 3×3R = 1 + 2L; 112 layers for 224 pxconvolutions climb slowly
Score table, 56×56 vs 7×74,096 timesattention cost is N²
Attention vs 3×3 convcrossover at N = 4.5C24×24 for C = 128
Attention slot vs MLPequal at N = 2CMLP wins below a 16×16 grid at C = 128
MobileViT unfoldP = 4 times less score work2×2 patches
MobileViT XXS / XS / S69.0 / 74.8 / 78.4%; 1.3 / 2.3 / 5.6Maccuracy from attention
MobileViT-XS vs MobileNetv2, iPhone 127.28 vs 0.92 ms (Neural Engine)the latency gap the later papers closed
CGA projectionsh times fewer49,152 to 12,288 weights at C = 128, h = 4
EfficientViT-M577.1%, 522M FLOPs, +40% V100 speed vs MobileNetV3-Lmore FLOPs, faster anyway
FastViT-S1279.8% at 1.4 ms, iPhone 12 Profolded blocks, attention late

The terms

TermMeaning
Receptive fieldThe input patch that can change one output.
Multiply-addOne multiplication plus one addition; papers count FLOPs as one or two of these.
Hybrid blockLocal mixing, global mixing and channel mixing, each with a residual.
Unfold / foldMobileViT's regrouping of pixels by patch position, and its inverse.
ReparameterizationRewriting trained parallel branches as one equal convolution.
Cascaded group attentionHeads that read separate channel slices, each fed the previous head's output.
Arithmetic intensityMultiply-adds per byte moved.
Memory-boundA layer whose time the bytes set, not the arithmetic.

The checklist

  1. Set the budget: frame time minus everything that is not the backbone.
  2. Run convolutions at high resolution. Put attention only where the grid is 16×16 or smaller.
  3. Count each slot's multiply-adds. Do not optimise attention if the MLP costs more.
  4. Fold every multi-branch block and batch norm before export. Check outputs match.
  5. Profile per layer on the target chip. Fix memory-bound layers by cutting bytes and launches.
  6. Report the time with the device, processor and input size named.

The core as code

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)

Keep going

The takeaway. Spend convolution where the grid is large and attention where it is small. Fold what you trained wide. Then trust the clock on the chip, not the multiply-add count.
Which plan fits the design of a modern mobile hybrid?

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.

Sources

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.

Conv-Transformer Mobile Hybrids: Locality and Globality on a Phone
MobileViT · FastViT · EfficientViT · Back to Gleams