Efficient ConvNets
Depthwise separable convolutions, inverted bottlenecks and compound scaling.
A phone cannot spend 15 billion multiply–adds on every photo. The networks that run there were built from a handful of ideas: split a convolution into a spatial part and a channel part, expand before filtering and project linearly after, let channels gate one another, and scale depth, width and resolution together. Then came the surprise that the operation count, the quantity all these designs minimized, is a poor predictor of speed.
What you’ll learn
- Derive the cost ratio of a depthwise separable convolution and show that the pointwise part then dominates.
- Explain MobileNetV2's inverted residuals and linear bottlenecks, including the argument that ReLU destroys information in low-dimensional spaces, and count a block's cost.
- Describe pointwise group convolutions with channel shuffle, and squeeze-and-excitation, with their costs.
- Derive EfficientNet's compound scaling rule from FLOPs .
- Explain why FLOPs are not latency, using memory-access costs, ShuffleNetV2's guidelines and the evidence from GPUs.
Factorizing the convolution
A standard convolution does two jobs at once: it filters space and mixes channels. A depthwise separable convolution does them one after the other: a depthwise convolution filters each input channel on its own (groups ), and a pointwise convolution mixes the channels. Laurent Sifre developed it during a 2013 internship at Google Brain and studied it in his thesis on rigid-motion scattering (Sifre, 2014); Xception (Chollet, 2017) read an Inception module as a step from ordinary toward depthwise separable convolution, and MobileNets (Howard et al., 2017) built whole networks from it.
On an output of positions, a standard layer computes dot products of length per position:
The depthwise step costs per input channel and position; the pointwise step is an ordinary matrix product per position:
Divide. For kernels and hundreds of channels the separable layer is 8 to 9 times cheaper, approaching as grows; parameters shrink by the same ratio:
The cost has moved. Within one separable layer the pointwise part takes the fraction below, so after factorization almost all multiply–adds sit in convolutions; in MobileNet they hold 94.9% of the multiply–adds and 74.6% of the parameters. Every later design in this lesson is, in part, a way to make that part cheaper.
In a depthwise separable layer with kernels and , what percentage of the multiply–adds does the pointwise () part take?
Show the answer
96.6 %
. The depthwise filtering that does all the spatial work costs under 4%. A convolution is a plain matrix product, which runs efficiently without the im2col reshuffling, one reason MobileNet's designers wanted the cost there.
MobileNet adds two knobs. A width multiplier thins every layer, cutting the cost by about ; a resolution multiplier shrinks the input, cutting it by . At full size, a MobileNet of depthwise separable layers reached 70.6% ImageNet top-1 with 569 million multiply–adds and 4.2 million parameters; the same architecture with full convolutions reached 71.7% with 4.9 billion and 29.3 million. Against VGG-16 (71.5%) it was 27 times cheaper in compute and 32 times smaller.
Inverted residuals and linear bottlenecks
A ResNet bottleneck is wide–narrow–wide, with the shortcut joining the wide ends. MobileNetV2 (Sandler et al., 2018) inverts it: narrow–wide–narrow. A convolution expands channels by a factor (6 in their networks), a depthwise convolution filters in the wide space, and a convolution projects back to channels, with no activation after the projection. The shortcut joins the narrow ends, so only the thin tensors between blocks need to be kept in memory. Per positions a block costs
multiply–adds: two pointwise products with the wide layer plus a cheap depthwise filter.
Why no ReLU after the projection? Sandler et al. argue from the "manifold of interest", the set of activations that real images produce, assumed to lie near a low-dimensional subspace. Where a ReLU keeps a region of nonzero volume it acts linearly, and where it zeros coordinates it destroys information unless the manifold has room to spare in other channels. They embedded a 2-D spiral into dimensions with a random matrix, applied a ReLU and mapped back: for or parts of the spiral collapsed onto each other, while for to it survived. So the nonlinearity belongs in the expanded space, and the narrow bottleneck should be linear; in their experiments, putting a ReLU in the bottleneck cost several percent of accuracy.
import torch.nn as nn
class InvertedResidual(nn.Module):
"""MobileNetV2 block: 1x1 expand (ReLU6), 3x3 depthwise (ReLU6), 1x1 linear projection."""
def __init__(self, c_in, c_out, t=6, stride=1):
super().__init__()
h = t * c_in # expanded width
self.use_res = stride == 1 and c_in == c_out
self.block = nn.Sequential(
nn.Conv2d(c_in, h, 1, bias=False), nn.BatchNorm2d(h), nn.ReLU6(inplace=True),
nn.Conv2d(h, h, 3, stride=stride, padding=1, groups=h, bias=False), # depthwise
nn.BatchNorm2d(h), nn.ReLU6(inplace=True),
nn.Conv2d(h, c_out, 1, bias=False), nn.BatchNorm2d(c_out)) # linear: no activation
def forward(self, x):
y = self.block(x)
return x + y if self.use_res else y
block = InvertedResidual(24, 24) # 8,832 parameters: 8,208 conv weights + 624 BatchNormOn a map with 24 channels in and out and , the block costs million multiply–adds, while its widest tensor, 144 channels, exists only inside the block. ReLU6, , was chosen for robustness in low-precision arithmetic.
MobileNetV2 reached 72.0% top-1 with 300 million multiply–adds and 3.4 million parameters, against 70.6% with 575 million for the first MobileNet, and ran in 75 ms instead of 113 ms on one core of a Pixel phone. Its inverted residual block, called "MBConv" in later work and often given squeeze-and-excitation, is the building block of MnasNet, MobileNetV3 and EfficientNet.
Groups, shuffles and channel attention
ShuffleNet (Zhang et al., 2018) attacks the dominant cost directly. In a ResNeXt unit, where only the layer is grouped, the pointwise convolutions take 93.4% of the multiply–adds. Grouping them too divides their cost by the number of groups , but then each output group sees only its own input group, and stacked grouped layers never exchange information. A channel shuffle fixes this at no arithmetic cost: reshape the channels into a grid, transpose and flatten, so the next layer's groups each receive channels from every previous group.
Squeeze-and-excitation (Hu, Shen & Sun, 2018) lets channels reweight one another. Squeeze global-average-pools each channel to one number, ; excite computes gates through a bottleneck of width ; the block rescales channel of its input by . Inserted into every ResNet-50 block with , it adds million parameters (about 10%) but only 0.26% more FLOPs (3.87 vs. 3.86 billion), and brings SE-ResNet-50's accuracy close to ResNet-101's at half the FLOPs. An ensemble of SE networks won the final ILSVRC in 2017 with 2.251% top-5 error.
import torch.nn as nn
def channel_shuffle(x, groups):
b, c, h, w = x.shape # channels (0..5), groups=2 -> order 0, 3, 1, 4, 2, 5
return x.view(b, groups, c // groups, h, w).transpose(1, 2).reshape(b, c, h, w)
class SqueezeExcite(nn.Module):
def __init__(self, c, r=16):
super().__init__()
self.fc = nn.Sequential(nn.Linear(c, c // r), nn.ReLU(inplace=True), nn.Linear(c // r, c), nn.Sigmoid())
def forward(self, x):
s = self.fc(x.mean(dim=(2, 3))) # squeeze: global average pool, (B, C)
return x * s[:, :, None, None] # excite: rescale every channelBoth are cheap in arithmetic: the shuffle is a memory permutation and SE is two tiny matrix products per image. Their costs show up instead in memory traffic and extra kernel launches, which the last step weighs.
MobileNetV3 (Howard et al., 2019) combined these pieces, MBConv blocks with squeeze-and-excitation and a cheap "hard-swish" activation, and chose the arrangement with a hardware-aware architecture search tuned to phone CPUs. Neural Architecture Search covers how such searches work and what they cost.
Compound scaling
Given a good small network, how should you spend twice the compute: more layers, wider layers or larger images? Tan & Le (2019) found that scaling any one dimension alone saturates quickly (a very deep network on small images cannot use its depth), and that the three should grow together. EfficientNet makes this a one-parameter rule.
A convolutional layer's cost is proportional to . Multiply the number of layers by , every channel count by and the image side by :
Tie the three to one compound coefficient , with constants that decide how a doubling of resources is split:
Constrain , so each unit of about doubles the cost. A small grid search at on the base network gave , , , and the same constants were then reused for every larger :
The base network, EfficientNet-B0, came from a search in MnasNet's space of MBConv blocks with squeeze-and-excitation, maximizing with a target of million FLOPs and . It reached 77.1% top-1 with 5.3 million parameters and 0.39 billion FLOPs. Scaling it up gave B1 to B7; B7 reached 84.3% with 66 million parameters and 37 billion FLOPs, matching the previous best model (GPipe) while being 8.4 times smaller and 6.1 times faster at inference.
With , , , you scale a base network with . By about how much do its FLOPs grow, and which dimension grows the most?
- About ; all three dimensions grow equally
- About ; depth grows the most (), then resolution (), then width ()
- About ; only resolution changes
- About ; FLOPs grow like
Show the answer
B. About ; depth grows the most (), then resolution (), then width ()
, close to the nominal . Width and resolution enter the cost squared, so their smaller per-step factors still contribute: and , times for depth.
FLOPs are not latency
Every design so far minimized multiply–adds. ShuffleNetV2 (Ma et al., 2018) measured what actually takes time on a GPU and on an ARM phone CPU, and found that data movement, element-wise operations, shuffles and the number of separate operators take a considerable share, invisible to a FLOP count. Their first guideline follows from one inequality.
A convolution from to channels on an map does multiply–adds. With a cache large enough for the whole layer, it reads the input once, writes the output once and reads the weights once:
By the arithmetic–geometric mean inequality, , and :
At fixed FLOPs the memory traffic is smallest when . Their benchmark confirmed it: at equal FLOPs, a stack with ran at about half the GPU throughput of one with .
The same lesson recurs at larger scale. Depthwise convolutions do very little arithmetic per byte they move, so on accelerators they are limited by memory bandwidth rather than compute: EfficientNetV2 (Tan & Le, 2021) found them slow in the early, high-resolution layers and replaced the expansion and depthwise pair there by one ordinary convolution ("Fused-MBConv"). Dollár, Singh & Girshick (2021) found that across scaling strategies a network's GPU runtime correlates much more strongly with its number of activations than with its FLOPs, and proposed scaling mostly width, which grows activations like rather than for an -fold increase in FLOPs. The Roofline Model & Compute Efficiency explains why, in terms of arithmetic intensity and memory bandwidth.
The practical conclusion is to measure: benchmark latency on the target hardware, batch size and precision, or put measured latency into the search objective, as MnasNet did with measured on real phones (Tan et al., 2019).
Key takeaways
- A depthwise separable convolution costs of a standard one, 8–9 times less for , after which the part holds about 95% of the multiply–adds.
- MobileNetV2's inverted residual expands, filters depthwise and projects linearly, multiply–adds; keeping the bottleneck linear avoids destroying information with ReLU in a low-dimensional space.
- Pointwise group convolutions with channel shuffle cut the cost; squeeze-and-excitation gates channels for about 10% more parameters and 0.26% more FLOPs in ResNet-50.
- Compound scaling sets , , with , so FLOPs grow about ; EfficientNet-B7 matched GPipe with 8.4 times fewer parameters.
- FLOPs are not latency: memory access (), fragmentation, element-wise operations and activations decide speed, so efficient design must be measured on the target hardware.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A convolution with is replaced by a depthwise separable one. By about what factor do its multiply–adds fall?
- About
- About
- About
- About
Show the answer
C. About
The ratio is , so about fewer. The term is the pointwise layer's cost relative to the original; the term, the depthwise layer's, keeps the saving below the limit .
Why does MobileNetV2 leave its narrow bottleneck layers linear (no ReLU after the projection)?
- ReLUs are too slow on mobile hardware
- A ReLU in a low-dimensional space zeros coordinates and destroys information about the manifold of interest; the nonlinearity is kept in the expanded space instead
- Linear layers have fewer parameters than ReLU layers
- The shortcut connection would otherwise double-count the activation
Show the answer
B. A ReLU in a low-dimensional space zeros coordinates and destroys information about the manifold of interest; the nonlinearity is kept in the expanded space instead
In the narrow space there is no spare dimension to hold what the ReLU zeros out, as the spiral experiment showed for . In the expanded space, ReLU can add nonlinearity while preserving information; empirically, nonlinear bottlenecks cost several percent of accuracy.
Under EfficientNet's rule with , you increase the compound coefficient from to . About how much more compute does the network need?
Show the answer
B.
FLOPs scale like , so two more units of cost about times as much (with the published constants, ).
Model A has 20% fewer FLOPs than model B, yet runs slower on a GPU. Which explanation is most plausible?
- A has more layers with very unequal input and output widths, many depthwise and element-wise operations, and more activations to move through memory
- GPUs execute multiply–adds at different speeds for different models
- FLOP counts are random and cannot be computed exactly
- A must have more parameters, and parameters alone determine speed
Show the answer
A. A has more layers with very unequal input and output widths, many depthwise and element-wise operations, and more activations to move through memory
Runtime depends on memory traffic, parallelism and the number of operators, not only on arithmetic: unequal widths raise memory access per FLOP, depthwise layers are bandwidth-bound, and activations correlate with GPU runtime better than FLOPs do.
Further reading
- A. G. Howard, M. Zhu, B. Chen, D. Kalenichenko, W. Wang, T. Weyand, M. Andreetto & H. Adam, "MobileNets: Efficient convolutional neural networks for mobile vision applications," arXiv:1704.04861 (2017).
- M. Sandler, A. Howard, M. Zhu, A. Zhmoginov & L.-C. Chen, "MobileNetV2: Inverted residuals and linear bottlenecks," CVPR (2018).
- J. Hu, L. Shen & G. Sun, "Squeeze-and-excitation networks," CVPR (2018).
- N. Ma, X. Zhang, H.-T. Zheng & J. Sun, "ShuffleNet V2: Practical guidelines for efficient CNN architecture design," ECCV (2018).
- M. Tan & Q. V. Le, "EfficientNet: Rethinking model scaling for convolutional neural networks," ICML (2019).