Simple Algorithm
Deep Learning · Emergence · 26 min

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 1/Cout+1/k21/C_{\text{out}}+1/k^2 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 ∝d w2r2\propto d\,w^2r^2.
  • Explain why FLOPs are not latency, using memory-access costs, ShuffleNetV2's guidelines and the evidence from GPUs.

Factorizing the convolution

A standard k×kk\times k convolution does two jobs at once: it filters space and mixes channels. A depthwise separable convolution does them one after the other: a depthwise k×kk\times k convolution filters each input channel on its own (groups =Cin=C_{\text{in}}), and a pointwise 1×11\times1 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.

DerivationThe cost ratio
  1. standard=k2 Cin Cout HW\text{standard}=k^2\,C_{\text{in}}\,C_{\text{out}}\,HW

    On an output of H×WH\times W positions, a standard layer computes CoutC_{\text{out}} dot products of length k2Cink^2C_{\text{in}} per position:

  2. separable=k2 Cin HW⏟depthwise+Cin Cout HW⏟pointwise\text{separable}=\underbrace{k^2\,C_{\text{in}}\,HW}_{\text{depthwise}}+\underbrace{C_{\text{in}}\,C_{\text{out}}\,HW}_{\text{pointwise}}

    The depthwise step costs k2k^2 per input channel and position; the pointwise step is an ordinary Cin→CoutC_{\text{in}}\to C_{\text{out}} matrix product per position:

  3. separablestandard=1Cout+1k2,k=3, Cout=256:  0.115≈18.7\frac{\text{separable}}{\text{standard}}=\frac1{C_{\text{out}}}+\frac1{k^2},\qquad k=3,\ C_{\text{out}}=256:\ \ 0.115\approx\frac1{8.7}

    Divide. For 3×33\times3 kernels and hundreds of channels the separable layer is 8 to 9 times cheaper, approaching k2=9k^2=9 as CoutC_{\text{out}} grows; parameters shrink by the same ratio:

  4. CinCoutHWk2CinHW+CinCoutHW=Coutk2+Cout\frac{C_{\text{in}}C_{\text{out}}HW}{k^2C_{\text{in}}HW+C_{\text{in}}C_{\text{out}}HW}=\frac{C_{\text{out}}}{k^2+C_{\text{out}}}

    The cost has moved. Within one separable layer the pointwise part takes the fraction below, so after factorization almost all multiply–adds sit in 1×11\times1 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 1×11\times1 part cheaper.

Predict before you look

In a depthwise separable layer with 3×33\times3 kernels and Cout=256C_{\text{out}}=256, what percentage of the multiply–adds does the pointwise (1×11\times1) part take?

Show the answer

96.6 %

Cout/(k2+Cout)=256/265≈96.6%C_{\text{out}}/(k^2+C_{\text{out}})=256/265\approx96.6\%. The depthwise filtering that does all the spatial work costs under 4%. A 1×11\times1 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 α\alpha thins every layer, cutting the cost by about α2\alpha^2; a resolution multiplier ρ\rho shrinks the input, cutting it by ρ2\rho^2. 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 1×11\times1 convolution expands d′d' channels by a factor tt (6 in their networks), a 3×33\times3 depthwise convolution filters in the wide space, and a 1×11\times1 convolution projects back to d′′d'' 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 h×wh\times w positions a block costs

h w d′ t (d′+k2+d′′)h\,w\,d'\,t\,\big(d'+k^2+d''\big)

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 nn dimensions with a random matrix, applied a ReLU and mapped back: for n=2n=2 or 33 parts of the spiral collapsed onto each other, while for n=15n=15 to 3030 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.

python
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 BatchNorm

On a 56×5656\times56 map with 24 channels in and out and t=6t=6, the block costs 3136⋅24⋅6⋅(24+9+24)≈25.73136\cdot24\cdot6\cdot(24+9+24)\approx25.7 million multiply–adds, while its widest tensor, 144 channels, exists only inside the block. ReLU6, min⁡(max⁡(x,0),6)\min(\max(x,0),6), 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 1×11\times1 cost directly. In a ResNeXt unit, where only the 3×33\times3 layer is grouped, the pointwise convolutions take 93.4% of the multiply–adds. Grouping them too divides their cost by the number of groups gg, 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 g⋅ng\cdot n channels into a g×ng\times n 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, z∈RC\mathbf z\in\R^C; excite computes gates s=σ(W2 ReLU⁡(W1z))\mathbf s=\sigma\big(W_2\,\operatorname{ReLU}(W_1\mathbf z)\big) through a bottleneck of width C/rC/r; the block rescales channel cc of its input by scs_c. Inserted into every ResNet-50 block with r=16r=16, it adds 2r∑sNsCs2≈2.5\frac2r\sum_sN_sC_s^2\approx2.5 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.

python
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 channel

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

DerivationFrom FLOPs ∝ d·w²·r² to the compound rule
  1. FLOPs ∝ d⋅w2⋅r2\text{FLOPs}\ \propto\ d\cdot w^2\cdot r^2

    A convolutional layer's cost is proportional to CinCoutHWC_{\text{in}}C_{\text{out}}HW. Multiply the number of layers by dd, every channel count by ww and the image side by rr:

  2. d=αϕ,w=βϕ,r=γϕ⟹FLOPs∝(α β2γ2)ϕd=\alpha^\phi,\qquad w=\beta^\phi,\qquad r=\gamma^\phi\qquad\Longrightarrow\qquad\text{FLOPs}\propto\big(\alpha\,\beta^2\gamma^2\big)^\phi

    Tie the three to one compound coefficient ϕ\phi, with constants α,β,γ≥1\alpha,\beta,\gamma\ge1 that decide how a doubling of resources is split:

  3. 1.2×1.12×1.152≈1.92,FLOPs(ϕ)≈1.92ϕ≈2ϕ1.2\times1.1^2\times1.15^2\approx1.92,\qquad\text{FLOPs}(\phi)\approx1.92^{\phi}\approx2^\phi

    Constrain αβ2γ2≈2\alpha\beta^2\gamma^2\approx2, so each unit of ϕ\phi about doubles the cost. A small grid search at ϕ=1\phi=1 on the base network gave α=1.2\alpha=1.2, β=1.1\beta=1.1, γ=1.15\gamma=1.15, and the same constants were then reused for every larger ϕ\phi:

The base network, EfficientNet-B0, came from a search in MnasNet's space of MBConv blocks with squeeze-and-excitation, maximizing ACC(m)×[FLOPS(m)/T]w\mathrm{ACC}(m)\times[\mathrm{FLOPS}(m)/T]^{w} with a target of T=400T=400 million FLOPs and w=−0.07w=-0.07. 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.

Check your understanding

With α=1.2\alpha=1.2, β=1.1\beta=1.1, γ=1.15\gamma=1.15, you scale a base network with ϕ=3\phi=3. By about how much do its FLOPs grow, and which dimension grows the most?

  1. About 3×3\times; all three dimensions grow equally
  2. About 7×7\times; depth grows the most (1.23≈1.731.2^3\approx1.73), then resolution (1.153≈1.521.15^3\approx1.52), then width (1.13≈1.331.1^3\approx1.33)
  3. About 1.92×1.92\times; only resolution changes
  4. About 27×27\times; FLOPs grow like ϕ3\phi^3
Show the answer

B. About 7×7\times; depth grows the most (1.23≈1.731.2^3\approx1.73), then resolution (1.153≈1.521.15^3\approx1.52), then width (1.13≈1.331.1^3\approx1.33)

(αβ2γ2)3=1.923≈7.1(\alpha\beta^2\gamma^2)^3=1.92^3\approx7.1, close to the nominal 23=82^3=8. Width and resolution enter the cost squared, so their smaller per-step factors still contribute: 1.332≈1.771.33^2\approx1.77 and 1.522≈2.311.52^2\approx2.31, times 1.731.73 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.

DerivationMemory access of a 1×1 convolution
  1. MAC=hw (c1+c2)+c1c2\mathrm{MAC}=hw\,(c_1+c_2)+c_1c_2

    A 1×11\times1 convolution from c1c_1 to c2c_2 channels on an h×wh\times w map does B=hwc1c2B=hwc_1c_2 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:

  2. MAC ≥ 2 hwc1c2+c1c2=2hw B+Bhw\mathrm{MAC}\ \ge\ 2\,hw\sqrt{c_1c_2}+c_1c_2=2\sqrt{hw\,B}+\frac{B}{hw}

    By the arithmetic–geometric mean inequality, c1+c2≥2c1c2c_1+c_2\ge2\sqrt{c_1c_2}, and c1c2=B/(hw)c_1c_2=B/(hw):

  3. equality  ⟺  c1=c2\text{equality}\iff c_1=c_2

    At fixed FLOPs the memory traffic is smallest when c1=c2c_1=c_2. Their benchmark confirmed it: at equal FLOPs, a stack with c1:c2=1:12c_1:c_2=1:12 ran at about half the GPU throughput of one with 1:11:1.

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 3×33\times3 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 s\sqrt s rather than ss for an ss-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 ACC(m)×[LAT(m)/T]w\mathrm{ACC}(m)\times[\mathrm{LAT}(m)/T]^{w} measured on real phones (Tan et al., 2019).

Key takeaways

  • A depthwise separable convolution costs 1/Cout+1/k21/C_{\text{out}}+1/k^2 of a standard one, 8–9 times less for 3×33\times3, after which the 1×11\times1 part holds about 95% of the multiply–adds.
  • MobileNetV2's inverted residual expands, filters depthwise and projects linearly, hwd′t(d′+k2+d′′)hwd't(d'+k^2+d'') multiply–adds; keeping the bottleneck linear avoids destroying information with ReLU in a low-dimensional space.
  • Pointwise group convolutions with channel shuffle cut the 1×11\times1 cost; squeeze-and-excitation gates channels for about 10% more parameters and 0.26% more FLOPs in ResNet-50.
  • Compound scaling sets d=αϕd=\alpha^\phi, w=βϕw=\beta^\phi, r=γϕr=\gamma^\phi with αβ2γ2≈2\alpha\beta^2\gamma^2\approx2, so FLOPs ∝dw2r2\propto dw^2r^2 grow about 2ϕ2^\phi; EfficientNet-B7 matched GPipe with 8.4 times fewer parameters.
  • FLOPs are not latency: memory access (MAC≥2hwB+B/hw\mathrm{MAC}\ge2\sqrt{hwB}+B/hw), 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.

Question 1

A 5×55\times5 convolution with Cout=128C_{\text{out}}=128 is replaced by a depthwise separable one. By about what factor do its multiply–adds fall?

  1. About 5×5\times
  2. About 25×25\times
  3. About 21×21\times
  4. About 128×128\times
Show the answer

C. About 21×21\times

The ratio is 1/Cout+1/k2=1/128+1/25≈0.0481/C_{\text{out}}+1/k^2=1/128+1/25\approx0.048, so about 21×21\times fewer. The 1/k21/k^2 term is the pointwise layer's cost relative to the original; the 1/Cout1/C_{\text{out}} term, the depthwise layer's, keeps the saving below the limit k2=25k^2=25.

Question 2

Why does MobileNetV2 leave its narrow bottleneck layers linear (no ReLU after the projection)?

  1. ReLUs are too slow on mobile hardware
  2. 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
  3. Linear layers have fewer parameters than ReLU layers
  4. 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 n=2,3n=2,3. In the expanded space, ReLU can add nonlinearity while preserving information; empirically, nonlinear bottlenecks cost several percent of accuracy.

Question 3

Under EfficientNet's rule with αβ2γ2≈2\alpha\beta^2\gamma^2\approx2, you increase the compound coefficient from ϕ\phi to ϕ+2\phi+2. About how much more compute does the network need?

  1. 2×2\times
  2. 4×4\times
  3. 8×8\times
  4. 16×16\times
Show the answer

B. 4×4\times

FLOPs scale like (αβ2γ2)ϕ≈2ϕ(\alpha\beta^2\gamma^2)^\phi\approx2^\phi, so two more units of ϕ\phi cost about 22=42^2=4 times as much (with the published constants, 1.922≈3.71.92^2\approx3.7).

Question 4

Model A has 20% fewer FLOPs than model B, yet runs slower on a GPU. Which explanation is most plausible?

  1. A has more layers with very unequal input and output widths, many depthwise and element-wise operations, and more activations to move through memory
  2. GPUs execute multiply–adds at different speeds for different models
  3. FLOP counts are random and cannot be computed exactly
  4. 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).