Efficient Convnets

Dive into Deep Learning · §7.5

Efficient Convnets
depthwise-separable factorization · inverted bottlenecks · FLOPs vs. latency · compound scaling · RepVGG fusion

Hard Edge Budgets: Why 15B Multiply-Adds Cannot Ship

Motivation & Deployment Constraints

  • Datacenter vs. edge: VGG-16 demands 15.3\textrm{B} MACs/frame and 550\textrm{ MB} of fp32 weights; MobileNetV1 hits 70.6\% ImageNet top-1 (-0.9\%) with 27\times fewer MACs (0.57\textrm{B}) and 33\times fewer weights (4.2\textrm{M}).
  • Three pillars: Depthwise-separable factorization, compound scaling + SE gates, and RepVGG train-to-eval branch fusion.

From Grouped Convolutions to the Depthwise Limit

Channel Connectivity Matrix

A standard k \times k convolution scales quadratically with width (c_{\textrm{i}} c_{\textrm{o}} k^2) because every output channel convolves every input channel with an independent spatial filter:

  • Grouped convolution (g groups): Partitions channels into g disjoint blocks of c_{\textrm{i}}/g \to c_{\textrm{o}}/g, turning the connectivity matrix block-diagonal and cutting weights and MACs to c_{\textrm{i}} c_{\textrm{o}} k^2 / g.
  • The depthwise limit (g = c_{\textrm{i}} = c_{\textrm{o}}): Every group holds a single channel. Each of the c_{\textrm{i}} channels is filtered by its own dedicated k \times k kernel (c_{\textrm{i}} k^2 weights) with zero cross-channel mixing.

Depthwise-Separable Convs: Factoring Space and Channels

Two-Step Factorization

Chaining a depthwise k \times k spatial filter with a pointwise 1 \times 1 channel mixer factors one dense convolution into two lightweight steps:

  • Step 1 — Depthwise (k \times k, g = c_{\textrm{i}}): Filters spatial neighborhoods independently within each input channel: h w c_{\textrm{i}} k^2 multiply-adds.
  • Step 2 — Pointwise (1 \times 1, c_{\textrm{i}} \to c_{\textrm{o}}): Linearly combines the c_{\textrm{i}} filtered channels at each pixel: h w c_{\textrm{i}} c_{\textrm{o}} multiply-adds.
  • Expressive restriction (rank-1 kernel factorization): Equivalent to restricting each (o, c) dense k\times k filter to the factored form \mathbf{K}_{o,c} = P_{o,c}\,\mathbf{D}_c.

The Depthwise-Separable FLOP and Parameter Ratio

Quantitative Savings

Dividing the two-step separable cost by the standard dense cost yields the exact reduction ratio for both parameters and multiply-adds:

\frac{\text{Depthwise} + \text{Pointwise}}{\text{Dense}} = \frac{h w \cdot c_{\textrm{i}} k^2 + h w \cdot c_{\textrm{i}} c_{\textrm{o}}}{h w \cdot c_{\textrm{i}} c_{\textrm{o}} k^2} = \frac{1}{c_{\textrm{o}}} + \frac{1}{k^2}

  • Asymptotic k^2 speedup: When c_{\textrm{o}} \gg k^2, the 1/c_{\textrm{o}} term becomes negligible and a 3\times 3 separable layer costs \approx 1/9 (8\text{--}9\times cheaper) of a dense 3\times 3 layer; a 7\times 7 separable layer (ConvNeXt) costs \approx 1/49.
  • Verifying at c_{\textrm{i}} = c_{\textrm{o}} = 128, k = 3: (1/128 + 1/9)^{-1} = 147{,}456 / 17{,}536 \approx \mathbf{8.41\times} fewer weights:
(147456, 17536, 8.408759124087592)

MobileNetV1 and the Depthwise-Separable Block

MobileNet Architecture

MobileNetV1 replaces every standard convolutional layer after the stem with a Depthwise 3×3 -> BN -> ReLU -> Pointwise 1×1 -> BN -> ReLU block:

  • Strided depthwise downsampling: Setting stride=2 on the depthwise 3\times 3 convolution halves resolution without separate pooling layers.
  • Mini-MobileNet on 96\times 96 Fashion-MNIST: A stride-2 32-channel 3\times 3 stem followed by 7 separable blocks climbing to 512 channels uses 542{,}474 parameters (vs. 4.66\text{M} weights if those 7 blocks were dense 3\times 3 convolutions—an 8.8\times reduction).

Implementing a Depthwise-Separable Block in Code

Mini-MobileNet Block

A depthwise 3\times 3 conv (one filter per channel), then a 1\times 1 pointwise channel mixer:

def dws_block(in_channels, out_channels, stride=1):
    """Depthwise 3x3 and pointwise 1x1 convolutions, each with BN and ReLU."""
    return nn.Sequential(
        nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride,
                  padding=1, groups=in_channels, bias=False),
        nn.BatchNorm2d(in_channels), nn.ReLU(),
        nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
        nn.BatchNorm2d(out_channels), nn.ReLU())

def he_init(module):
    """Normal weights with variance 2/n_in and zero biases."""
    if isinstance(module, (nn.Conv2d, nn.Linear)):
        nn.init.kaiming_normal_(module.weight)
        if module.bias is not None:
            nn.init.zeros_(module.bias)

Assembling Mini-MobileNet and Counting Parameters

Mini-MobileNet Backbone

def num_params(model):
    """The number of trainable parameters."""
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

model = MiniMobileNet()
assert model(torch.zeros(1, 1, 96, 96)).shape == (1, 10)
num_params(model)
542474

MobileNetV2: The Inverted Bottleneck & Linear Projection

Inverted Bottlenecks

When the 3\times 3 filter is depthwise rather than dense, it is already cheap—and because it learns only one filter per channel, it needs a wide channel space to be expressive:

  • Classic ResNet bottleneck (left): Compresses 256 \xrightarrow{1\times 1} 64 \to \text{dense } 3\times 3 \to 64 \xrightarrow{1\times 1} 256 so the expensive dense 3\times 3 runs at narrow width.
  • Inverted bottleneck (right, MobileNetV2): Keeps the residual stream thin (24 ch), expands 6\times via 1\times 1 (24 \to 144), runs depthwise 3\times 3 at 144 ch, and projects 144 \to 24.
  • Why the final 1\times 1 projection omits ReLU: Applying ReLU to a low-dimensional 24-channel bottleneck destroys negative coordinates; keeping the narrow projection linear preserves information while thin shortcuts minimize inter-block SRAM traffic.

Controlled Benchmark: Parameter-Matched vs. FLOP-Matched

Three-Way Comparison

We compare MiniMobileNet (542\text{K} params, 50.3\text{M} MACs) against two dense VGG-style baselines on 96\times 96 Fashion-MNIST: VGGSmall matched in parameters (584\text{K} params, width up to 128) and VGG-style, narrow matched in multiply-adds (49.1\text{M} MACs, width \div 2.8, 76\text{K} params):

({'Mini-MobileNet': 50259968,
  'VGG-style': 384861440,
  'VGG-style, narrow': 49103308},
 7.657415142007253)
Mini-MobileNet: 542,474 parameters, 50.3M multiply-adds, accuracy 0.917, 1.8 ms/batch
VGG-style: 583,594 parameters, 384.9M multiply-adds, accuracy 0.938, 4.9 ms/batch
VGG-style, narrow: 75,854 parameters, 49.1M multiply-adds, accuracy 0.933, 1.3 ms/batch

Why 7.7× Fewer FLOPs Yield Only 2–3.5× Faster GPUs

Systems Analysis: Arithmetic Intensity

  • Parameter-matched (VGGSmall, 385M MACs): 7.7\times more MACs than MiniMobileNet (50.3\textrm{M}), yet only 2\text{--}3.5\times slower on GPU (93.8\% vs. 91.5\% acc).
  • FLOP-matched (VGG-style, narrow, 49.1M MACs): Beats MiniMobileNet in accuracy (93\%) and runs faster (0.5\text{--}0.8\times time).
  • Roofline bottleneck: Depthwise 3 \times 3 does only 9 MACs/read vs. 9c_\textrm{o} for dense 3 \times 3.

Squeeze-and-Excitation (SE): Global Channel Attention

Squeeze-and-Excitation Gates

class SE(nn.Module):
    def __init__(self, num_channels, ratio=4):
        super().__init__()
        self.fc = nn.Sequential(
            nn.LazyLinear(num_channels // ratio), nn.ReLU(),
            nn.LazyLinear(num_channels), nn.Sigmoid())

    def forward(self, X):
        s = self.fc(X.mean(dim=(2, 3)))
        return X * s[:, :, None, None]

SE(32)(d2l.randn(2, 32, 16, 16)).shape
torch.Size([2, 32, 16, 16])
  • Squeeze \to Excite \to Rescale: Pools (C, H, W) \to (C, 1, 1) and runs a C \to C/r \to C gating MLP (\sigma) for <0.03\% extra MACs.

RepVGG: Multi-Branch Training, Single-Path Inference

Structural Re-parameterization

Multi-branch residual topologies are easy to optimize during training, whereas plain single-path 3\times 3 stacks achieve peak memory and compute efficiency at inference. RepVGG (Ding et al., 2021) bridges both worlds via algebraic fusion:

  • Train-time block: Sums three parallel batch-normalized branches before ReLU: \mathbf{Y} = \textrm{ReLU}\bigl(\textrm{BN}_3(\textrm{Conv}_{3\times 3}(\mathbf{X})) + \textrm{BN}_1(\textrm{Conv}_{1\times 1}(\mathbf{X})) + \textrm{BN}_0(\mathbf{X})\bigr)
  • Deploy-time fusion: Because all three branches inside \textrm{ReLU}(\cdot) are linear operators at inference time, they fold algebraically into a single 3\times 3 convolution with bias, eliminating two branches and two live activation buffers.

The Three Linear-Algebra Steps of Branch Fusion

Algebraic BN Folding & Kernel Addition

Collapsing a trained RepVGGBlock into one 3\times 3 layer (\hat{\mathbf{W}}, \hat{\mathbf{b}}) requires three exact transformations per output channel o:

  • 1. Fold inference-mode BatchNorm into each branch: With frozen running stats (\mu_o, \sigma_o^2) and parameters (\gamma_o, \beta_o): \hat{\mathbf{W}}_o = \frac{\gamma_o}{\sqrt{\sigma_o^2 + \epsilon}}\,\mathbf{W}_o, \qquad \hat{b}_o = \beta_o + \frac{\gamma_o(b_o - \mu_o)}{\sqrt{\sigma_o^2 + \epsilon}}
  • 2. Embed 1\times 1 and identity as 3\times 3 kernels: Zero-pad the 1\times 1 kernel by 1 pixel on all sides; write the identity on channel o as a 3\times 3 kernel with 1 at center tap (i=o, 1, 1) and 0 elsewhere.
  • 3. Sum by linearity: \hat{\mathbf{W}}_{\text{fused}} = \hat{\mathbf{W}}^{(3)} + \hat{\mathbf{W}}^{(1)} + \hat{\mathbf{W}}^{(0)} and \hat{\mathbf{b}}_{\text{fused}} = \hat{\mathbf{b}}^{(3)} + \hat{\mathbf{b}}^{(1)} + \hat{\mathbf{b}}^{(0)}.

Implementing Branch Fusion (fuse_bn and fuse_block)

RepVGG Fusion Code

Fold each branch’s BatchNorm into a 3\times 3 kernel, then sum all three into one conv:

def fuse_bn(W, bn):
    """Fold inference-mode batch normalization into a bias-free conv."""
    scale = bn.weight / torch.sqrt(bn.running_var + bn.eps)
    return W * scale.reshape(-1, 1, 1, 1), bn.bias - bn.running_mean * scale

@torch.no_grad()
def fuse_block(blk):
    c = blk.conv3.weight.shape[0]
    W3, b3 = fuse_bn(blk.conv3.weight, blk.bn3)
    W1, b1 = fuse_bn(F.pad(blk.conv1.weight, (1, 1, 1, 1)), blk.bn1)
    I = torch.zeros_like(W3)  # On the device of the block
    I[torch.arange(c), torch.arange(c), 1, 1] = 1.0
    W0, b0 = fuse_bn(I, blk.bn0)
    fused = nn.Conv2d(c, c, kernel_size=3, padding=1, device=W3.device)
    fused.weight.copy_(W3 + W1 + W0)
    fused.bias.copy_(b3 + b1 + b0)
    return fused

Exact FP32 Equivalence vs. The INT8 Quantization Pitfall

Code Verification & Deployment Pitfall

We implement fuse_bn and fuse_block, verify exact equivalence in float32, and highlight a critical post-training quantization hazard:

  • Exact to FP32 roundoff (\sim 10^{-6}): After updating running stats and randomizing (\gamma, \beta), the fused 3\times 3 layer matches the 3-branch block to within 10^{-6}.
  • Pitfall — FP32 equivalence \neq INT8 equivalence (Chu et al., 2024): Because the center tap of \hat{\mathbf{W}}_{\text{fused}} sums three independently normalized branches of wildly different scales (\gamma_o / \sqrt{\sigma_o^2 + \epsilon}), fused weights develop heavy-tailed outliers. Naive 8-bit uniform quantization (256 bins) crashes fused RepVGG-B0 on ImageNet from 75.1\% to 40.2\% (recoverable via QAT or branch-scale regularization).
5.7220458984375e-06

Concept Check: Separable Savings, SE Cost & BN Folding

Concept Check

Work out these three quantitative efficiency checks:

  1. Separable 7\times 7 savings: In ConvNeXt (§7.7), a block uses a 7\times 7 depthwise convolution followed by a 1\times 1 convolution at width c_{\textrm{i}} = c_{\textrm{o}} = 96. By what factor is this depthwise-separable pair cheaper than a dense 7\times 7 convolution at c = 96?
  2. Squeeze-and-Excitation overhead: On a stage with c = 256 channels at 14\times 14 resolution, compare the multiply-adds of an SE gate (r = 4) against one dense 3\times 3 convolution (256 \to 256).
  3. BN folding by hand: A bias-free conv channel (b_o = 0) has kernel \mathbf{W}_o followed by BatchNorm with running mean \mu_o = 0.5, running variance \sigma_o^2 + \epsilon = 0.25, scale \gamma_o = 1, and shift \beta_o = 0. What are the folded kernel \hat{\mathbf{W}}_o and bias \hat{b}_o?

Answers:

  1. Reduction ratio: 1/c_{\textrm{o}} + 1/k^2 = 1/96 + 1/49 \approx 0.0308, so it is 32.4\times cheaper (approaching 49\times as c_{\textrm{o}} grows).
  2. SE gate: 2 c^2 / r = 2(256^2)/4 = 32{,}768 MACs (acting on a 1\times 1 pooled vector). Dense 3\times 3 conv: 14^2 \cdot 9 \cdot 256^2 \approx 115.6\text{M} MACs. The SE gate adds just 0.028\% arithmetic overhead.
  3. Scale factor \gamma_o / \sqrt{\sigma_o^2 + \epsilon} = 1 / \sqrt{0.25} = 2. Thus \hat{\mathbf{W}}_o = 2\mathbf{W}_o and \hat{b}_o = 0 + 2(0 - 0.5) = -1.

Summary: Key Takeaways on Efficient Convnets

Summary

Technique Mathematical / Structural Form Efficiency Gain & Practical Caveat
Depthwise-Separable Conv Depthwise k\times k (g=c_{\textrm{i}}) + Pointwise 1\times 1 (c_{\textrm{i}}\to c_{\textrm{o}}) Cuts weights & MACs to 1/c_{\textrm{o}} + 1/k^2 (\approx 1/9 for 3\times 3), but depthwise step has low arithmetic intensity (9 MACs/read)
Inverted Bottleneck (MBConv) Thin residual (c) \to 1\times 1 (tc) \to \text{DW } 3\times 3 (tc) \to linear 1\times 1 (c) Keeps inter-block tensors thin in SRAM; omits final ReLU to prevent rank collapse in narrow bottleneck
Compound Scaling Scale (d, w, r) \leftarrow (\alpha^\phi d, \beta^\phi w, \gamma^\phi r) with \alpha\beta^2\gamma^2 \approx 2 Balances receptive field, feature capacity, and image detail simultaneously (EfficientNet)
Squeeze-and-Excitation (SE) \mathbf{X} \odot \sigma(\mathbf{W}_2\,\textrm{ReLU}(\mathbf{W}_1\,\textrm{GAP}(\mathbf{X}))) Global channel attention for 2c^2/r weights and <0.1\% FLOPs
RepVGG Re-parameterization Fold \textrm{BN} into 3\times 3, 1\times 1, \mathbf{I} branches and sum into one 3\times 3 conv Multi-branch trainability + single-path FP32 inference speed; requires branch-scale control for INT8 quantization