7.5 Efficient Convnets

The architectures we studied so far were engineered to top academic accuracy leaderboards using datacenter GPUs. In real-world deployment, however, vast numbers of convolutional networks run on smartphones, smart cameras, autonomous vehicles, and embedded boards where latency, memory footprint, and battery draw are hard budgets: a model that busts its budget simply cannot ship, regardless of its benchmark accuracy. Consider a phone classifying frames from its camera in real time. VGG-16 requires 15.3 billion multiply-adds for a single 224×224224 \times 224 frame, which at 30 frames per second translates to 460 billion multiply-adds every second, while its 138 million single-precision parameters consume 550 MB of RAM alongside every other app on the device. How can we shrink a convolutional network's cost by an order of magnitude, and what accuracy tradeoff does that entail?

In this section, we explore three major ideas behind efficient convnet design. Factorization decomposes each dense convolution into a lightweight per-channel spatial filter paired with a 1×11 \times 1 channel mixer. Scaling and search fix a strong building block and optimize stage depths, widths, and input resolution systematically. Structural re-parameterization trains a multi-branch architecture for easy optimization and then algebraically merges those branches into a single fast convolution for deployment. Along the way, we benchmark factorization directly in both accuracy and wall-clock time—and uncover a sobering lesson: theoretical multiply-add counts rarely tell the whole speed story, and whether factorization beats simply narrowing a dense model depends strongly on the scale of the task.

import time

7.5.1 Depthwise-Separable Networks#

Because dense spatial convolutions consume the lion's share of a convnet's arithmetic, the most direct path to efficiency is factorizing the convolution layer itself.

7.5.1.1 Depthwise-Separable Convolutions#

A standard dense convolution scales with cicoc_\textrm{i} c_\textrm{o} because every output channel reads every input channel through its own spatial filter. In Section 7.4.5.1, ResNeXt's grouped convolution broke that all-to-all coupling by partitioning channels into gg disjoint groups, restricting each output group to its matching input group and dividing both weights and multiply-adds by gg. As Figure 7.5.1 illustrates, grouping turns the dense channel-connectivity matrix into a block-diagonal pattern.

Figure 7.5.1:

Input channels read by each output channel, for 8 input and 8 output channels. Each shaded cell is one kh×kwk_\textrm{h}\times k_\textrm{w} kernel; gg groups keep 1/g1/g of them.

Now push grouping all the way to its limit: g=ci=cog = c_\textrm{i} = c_\textrm{o}, so every group contains a single channel. This depthwise convolution applies one k×kk\times k spatial filter independently to each input channel with zero cross-channel mixing—the exact complement of a 1×11\times 1 convolution (Section 6.4.3), which mixes all channels at each pixel with zero spatial interaction. Chaining a depthwise k×kk\times k convolution and a pointwise 1×11\times 1 convolution recovers both spatial filtering and channel mixing in two cheap steps, yielding a depthwise-separable convolution (Chollet, 2017; Howard et al., 2017). Figure 7.5.2 contrasts this two-stage factorization against the dense convolution it replaces.

Figure 7.5.2:

Three input and three output channels with 3×33\times 3 kernels. Top: a dense convolution, in which every output channel reads every input channel through a kernel stack of its own. Bottom: a depthwise convolution filters each channel separately, once for all output channels, and a pointwise convolution mixes the channels with one 1×11\times 1 kernel stack per output channel.

Let us quantify the savings. For an h×wh\times w output and a k×kk\times k kernel, a dense convolution requires hw⋅cicok2hw\cdot c_\textrm{i} c_\textrm{o} k^2 multiply-adds, whereas the depthwise-separable pair requires hw⋅cik2hw\cdot c_\textrm{i} k^2 for spatial filtering plus hw⋅cicohw\cdot c_\textrm{i} c_\textrm{o} for pointwise mixing. Their ratio is

hw⋅cik2+hw⋅cicohw⋅cicok2=1co+1k2,(7.5.1)\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}, \tag{7.5.1}

and the exact same ratio holds for parameter counts. In Figure 7.5.2 (ci=co=k=3c_\textrm{i} = c_\textrm{o} = k = 3), the dense layer uses 3⋅27=813 \cdot 27 = 81 weights versus 27+9=3627 + 9 = 36 for the separable pair (ratio 1/3+1/9=4/91/3 + 1/9 = 4/9). Adding one more output channel costs 27 new weights in the dense layer versus only 3 in the separable layer. Once coc_\textrm{o} is large and k=3k = 3, the ratio approaches 1/91/9: nearly a ninefold reduction in both weights and arithmetic.

Naturally, these savings are not free—they come from a structural constraint on the effective filter tensor. Because the separable pair applies a single spatial filter Dc\mathbf{D}_c to input channel cc and then linearly combines those filtered maps with scalar pointwise weights Po,cP_{o,c}, it is equivalent to a dense convolution whose kernels are forced into the factored form Ko,c=Po,c Dc\mathbf{K}_{o,c} = P_{o,c}\,\mathbf{D}_c. Every output channel must share the same spatial filter on input channel cc (up to a scalar multiple), whereas a dense convolution can learn an arbitrary independent k×kk\times k filter for every (o,c)(o, c) pair. Efficient networks accept this rank-1 restriction and reinvest the freed budget into deeper or wider stages.

Let us verify the parameter ratio in code for a bias-free 3×33\times 3 layer mapping 128 channels to 128 channels, where (7.5.1) predicts a reduction factor of (1/128+1/9)−1≈8.4(1/128 + 1/9)^{-1} \approx 8.4.

c_i, c_o, k = 128, 128, 3
X = d2l.normal(0, 1, (1, c_i, 32, 32))
dense = nn.LazyConv2d(c_o, kernel_size=k, padding=1, bias=False)
depthwise = nn.LazyConv2d(c_i, kernel_size=k, padding=1, groups=c_i,
                          bias=False)
pointwise = nn.LazyConv2d(c_o, kernel_size=1, bias=False)
assert dense(X).shape == pointwise(depthwise(X)).shape
p_dense = dense.weight.numel()
p_sep = depthwise.weight.numel() + pointwise.weight.numel()
p_dense, p_sep, p_dense / p_sep
(147456, 17536, 8.408759124087592)

The dense layer uses 147,456 weights versus 17,536 for the separable pair—an exact 8.4×8.4\times reduction.

In PyTorch, groups=c_i turns nn.Conv2d into a depthwise convolution; any groups that divides both channel counts gives a grouped convolution.

7.5.1.2 MobileNet#

MobileNet (Howard et al., 2017) scaled depthwise-separable convolutions into a complete mobile-grade backbone. After a single dense stem convolution, every layer uses the block in Figure 7.5.3: a depthwise 3×33 \times 3 convolution followed by a pointwise 1×11 \times 1 convolution, each paired with batch normalization and ReLU. Spatial downsampling is handled directly by stride-2 depthwise convolutions (avoiding separate pooling layers), and the model ends with NiN's global average pooling and a single linear layer (Section 7.2.2). The ImageNet payoff was striking: MobileNet came within one percentage point of VGG-16 (70.6% vs. 71.5% top-1 accuracy) using only 0.57 billion multiply-adds and 4.2 million parameters—27×27\times less arithmetic and 33×33\times fewer parameters.

Figure 7.5.3:

A depthwise-separable block from cic_\textrm{i} to coc_\textrm{o} channels. The depthwise 3×33 \times 3 convolution filters each input channel separately; the pointwise 1×11 \times 1 convolution mixes the channels at each position; batch normalization and a ReLU follow each convolution.

7.5.1.3 The Inverted Bottleneck#

Recall that a classic ResNet or ResNeXt bottleneck (Section 7.4.5.1) compresses channels before its spatial filter: a 1×11 \times 1 layer squeezes a wide representation into a narrow subspace so that the expensive dense 3×33 \times 3 convolution stays affordable, and a second 1×11 \times 1 layer expands back out. When the 3×33 \times 3 layer is depthwise, however, that logic flips completely. A depthwise convolution is inexpensive even on wide feature maps, and because it learns only one spatial filter per channel, it actually benefits from running at high width.

MobileNetV2 (Sandler et al., 2018) therefore inverts the bottleneck. The residual highway stays narrow (say, 24 channels); inside the block, a 1×11 \times 1 expansion lifts it sixfold to 144 channels, a depthwise 3×33 \times 3 convolution filters that expanded space, and a linear 1×11 \times 1 projection compresses back down to 24 channels. Crucially, the final projection omits ReLU: applying a ReLU to a very thin bottleneck zeroes out negative coordinates and permanently discards information that later layers cannot recover. Figure 7.5.4 places the standard and inverted bottlenecks side by side.

Figure 7.5.4:

A ResNet bottleneck block (left) and a MobileNetV2 inverted bottleneck (right); the input is at the bottom. The bottleneck narrows 256 channels to 64 for a dense 3×33 \times 3 convolution and widens them again. The inverted bottleneck widens 24 channels to 144 for a depthwise 3×33 \times 3 convolution, which learns one filter per channel, and projects back to 24 without a ReLU; the residual connection joins the thin ends.

Because the residual shortcut connects the thin ends rather than the wide interiors, only compact tensors persist in memory between blocks—a major win on mobile processors where activation RAM is often tighter than flash storage for weights. We will encounter this exact inverted-bottleneck geometry again (with a larger 7×77 \times 7 depthwise kernel moved to the front) in ConvNeXt (Section 7.7).

7.5.1.4 A Mini-MobileNet#

To test depthwise-separable factorization firsthand on Fashion-MNIST, we build a compact MobileNetV1-style network using the clean block of Figure 7.5.3 so the factorization itself stays front and center. Because every convolution is followed by batch normalization, all convolutions omit biases, and all convolutional and linear weights use He initialization (Section 4.4).

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)

As in VGG (Section 7.2.1), the architecture is specified cleanly as a list of (out_channels, stride) pairs. A stride-2 3×33 \times 3 stem lifts the single-channel input to 32 channels at half resolution; seven depthwise-separable blocks then double the channels and halve spatial resolution three times; and global average pooling plus a linear head emit the ten class logits.

Here we also upgrade the optimizer to SGD with momentum 0.9, which accumulates an exponentially weighted moving average of past gradients so effective step sizes can reach up to ten times a plain SGD step at the same learning rate (Section 9.4). Because of this change in optimizer, do not compare the raw accuracies here directly with the plain-SGD ResNet-18 runs of Section 7.4. As before, the learning rate anneals smoothly to zero along a half-cosine (Section 7.1) over the num_steps training steps (4,690 minibatches for 10 epochs), here using each framework's built-in cosine scheduler without warmup.

class MiniMobileNet(d2l.Classifier):
    def __init__(self, arch=((64, 1), (128, 2), (128, 1), (256, 2), (256, 1),
                             (512, 2), (512, 1)),
                 lr=0.05, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        layers = [nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1,
                            bias=False),
                  nn.BatchNorm2d(32), nn.ReLU()]
        c = 32
        for c_out, stride in arch:
            layers.append(dws_block(c, c_out, stride))
            c = c_out
        layers += [nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
                   nn.Linear(c, num_classes)]
        self.net = nn.Sequential(*layers)
        self.net.apply(he_init)

    def configure_optimizers(self):
        optim = torch.optim.SGD(self.parameters(), lr=self.lr, momentum=0.9)
        return optim, torch.optim.lr_scheduler.CosineAnnealingLR(
            optim, self.num_steps)  # Stepped after every minibatch

Let us count MiniMobileNet's trainable parameters and compare against a dense counterpart; we save num_params in d2l for reuse in later sections.

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

MiniMobileNet contains 542,474 trainable parameters. Replacing each separable block with an ordinary dense 3×33 \times 3 convolution between the same widths would require 9∑lci,l co,l=4,663,2969 \sum_l c_{\textrm{i},l}\, c_{\textrm{o},l} = 4{,}663{,}296 weights in the seven blocks alone—8.8×8.8\times the 530,528 weights of our separable layers, approaching the asymptotic 9×9\times ceiling as channel width reaches 512.

7.5.1.5 Arithmetic, Accuracy, and Time#

How much accuracy does factorization trade away, and how much wall-clock speed does it actually buy? To find out, we first build VGGSmall, a dense VGG-style network (Section 7.2.1) matched to MiniMobileNet's parameter count. Because each dense 3×33 \times 3 layer uses roughly nine times as many weights as a separable block, matching the parameter budget caps VGGSmall at 128 channels where MiniMobileNet reaches 512. Both models share batch normalization, He initialization, a global-average-pooling head, and the exact same training schedule. Keep in mind that matching parameters lets both the layer type and channel width vary together.

class VGGSmall(d2l.Classifier):
    """A dense VGG-style network with the same parameter budget."""
    def __init__(self, arch=((2, 32), (2, 64), (2, 128), (2, 128)),
                 lr=0.05, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        layers, c = [], 1
        for num_convs, c_out in arch:
            for _ in range(num_convs):
                layers += [nn.Conv2d(c, c_out, kernel_size=3, padding=1,
                                     bias=False),
                           nn.BatchNorm2d(c_out), nn.ReLU()]
                c = c_out
            layers.append(nn.MaxPool2d(2))
        layers += [nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
                   nn.Linear(c, num_classes)]
        self.net = nn.Sequential(*layers)
        self.net.apply(he_init)

    def configure_optimizers(self):
        optim = torch.optim.SGD(self.parameters(), lr=self.lr, momentum=0.9)
        return optim, torch.optim.lr_scheduler.CosineAnnealingLR(
            optim, self.num_steps)  # Stepped after every minibatch

Before launching training, let us tally the exact multiply-add counts on 96×9696 \times 96 inputs. With "same" padding and stride ss, an h×hh \times h input maps to side ⌈h/s⌉\lceil h/s \rceil, and a grouped k×kk \times k convolution with gg groups costs k2ci/gk^2 c_\textrm{i} / g multiply-adds per output element.

def conv_macs(h, c_in, c_out, k=3, stride=1, groups=1):
    """Output side and multiply-adds of a k x k convolution, 'same' padding."""
    h = -(-h // stride)  # ceil(h / stride)
    return h, h * h * k * k * c_in * c_out // groups

def mobilenet_macs(arch, h=96, num_classes=10):
    h, total = conv_macs(h, 1, 32, stride=2)  # The stem
    c = 32
    for c_out, stride in arch:
        h, depthwise = conv_macs(h, c, c, stride=stride, groups=c)
        h, pointwise = conv_macs(h, c, c_out, k=1)
        total, c = total + depthwise + pointwise, c_out
    return total + c * num_classes

def vgg_macs(arch, h=96, num_classes=10):
    total, c = 0, 1
    for num_convs, c_out in arch:
        for _ in range(num_convs):
            h, macs = conv_macs(h, c, c_out)
            total, c = total + macs, c_out
        h //= 2  # 2 x 2 max-pooling
    return total + c * num_classes

narrow = ((2, 11), (2, 23), (2, 46), (2, 46))  # VGGSmall's widths / 2.8
macs = {'Mini-MobileNet': mobilenet_macs(MiniMobileNet().arch),
        'VGG-style': vgg_macs(VGGSmall().arch),
        'VGG-style, narrow': vgg_macs(narrow)}
macs, macs['VGG-style'] / macs['Mini-MobileNet']
({'Mini-MobileNet': 50259968,
  'VGG-style': 384861440,
  'VGG-style, narrow': 49103308},
 7.657415142007253)

Despite matching in parameter count, VGGSmall executes 385 million multiply-adds per image while MiniMobileNet needs only 50 million—7.7×7.7\times less arithmetic. That gap reflects where each model places its weights: VGGSmall applies dense filters across high-resolution 96×9696 \times 96 to 24×2424 \times 24 feature maps, whereas nearly three-quarters of MiniMobileNet's weights sit in its final two pointwise layers acting on tiny 6×66 \times 6 grids.

On edge hardware, however, the decisive comparison is at equal arithmetic. To bring VGGSmall down to MiniMobileNet's 50 million multiply-adds, we shrink every channel count by a factor of ~2.8 to (11, 23, 46, 46) (narrow above), leaving just 76,000 parameters—one-seventh of MiniMobileNet's weight count. Let us train all three models for 10 epochs on 96×9696 \times 96 Fashion-MNIST.

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
num_steps = 10 * len(data.train_dataloader())  # 10 epochs of 469 steps
models = {'Mini-MobileNet': MiniMobileNet(lr=0.05, num_steps=num_steps),
          'VGG-style': VGGSmall(lr=0.05, num_steps=num_steps),
          'VGG-style, narrow': VGGSmall(narrow, lr=0.05, num_steps=num_steps)}
accuracy = {}
for name, model in models.items():
    trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
    trainer.fit(model, data)
    accuracy[name] = trainer.history['val_acc'][-1]

Operation counts measure arithmetic, not elapsed time. To see how multiply-adds translate to real latency, we benchmark inference forward passes on batches of 128 images on the GPU—warming up once and synchronizing the device before reading the wall clock (Section 5.7.2.1).

def forward_ms(model, num_reps=50):
    """Milliseconds per forward pass of a batch of 128 images."""
    X = torch.randn(128, 1, 96, 96, device=d2l.try_gpu())
    model.eval()
    with torch.inference_mode():
        sync = torch.cuda.synchronize if X.is_cuda else lambda: None
        model(X)
        sync()  # Warm up and wait
        start = time.perf_counter()
        for _ in range(num_reps):
            model(X)
        sync()
    return 1000 * (time.perf_counter() - start) / num_reps

for name, model in models.items():
    print(f'{name}: {num_params(model):,} parameters, '
          f'{macs[name] / 1e6:.1f}M multiply-adds, '
          f'accuracy {accuracy[name]:.3f}, '
          f'{forward_ms(model):.1f} ms/batch')
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

Table 7.5.1 summarizes all three models across repeated runs, reporting validation accuracy alongside each model's forward-pass latency normalized to MiniMobileNet.

:Mini-MobileNet against a dense VGG-style network with about the same number of parameters and a narrow one with about the same number of multiply-adds (Fashion-MNIST at 96×9696 \times 96, 10 epochs; validation accuracy and forward-pass time ratio over repeated runs).

ModelParametersMultiply-addsValidation accuracyForward time
Mini-MobileNet542,47450.3 million91–92%1
VGG-style583,594384.9 million93.5–94%2–3.5
VGG-style, narrow75,85449.1 million93%0.5–0.8

Three lessons jump out of Table 7.5.1:

  1. Matching parameters is not matching compute: At ~550K parameters, VGGSmall beats MiniMobileNet by ~2 percentage points while performing 7.7×7.7\times more multiply-adds (keeping full 96×9696 \times 96 resolution in its opening stage and learning unrestricted dense kernels).
  2. At matched arithmetic on a small dataset, narrowing beats factorizing: Shrinking VGGSmall to 50M multiply-adds (VGG-style, narrow, 76K parameters) beats MiniMobileNet by ~1 point and runs faster. By (7.5.1), depthwise factorization pays off most at wide channel counts (saving 5×5\times at c=11c = 11 vs. nearly 9×9\times at c=512c = 512); 10-class Fashion-MNIST fits comfortably inside narrow dense layers, whereas 1,000-class ImageNet requires wide stages where narrowing a dense convnet starves capacity.
  3. Multiply-adds are a weak proxy for GPU wall-clock latency: A 7.7×7.7\times arithmetic reduction yields only a 2–3.5×2\text{--}3.5\times speedup because a dense 3×33 \times 3 layer performs 9co9c_\textrm{o} multiply-adds per input read (high arithmetic intensity), whereas a depthwise 3×33 \times 3 layer performs only 9 multiply-adds per input read, leaving the GPU memory-bandwidth bound.

7.5.2 Scaling and Searching#

MobileNet fixes an efficient building block and selects stage widths by hand. Two natural questions follow: how should we scale a base architecture up when more compute becomes available, and can automated optimization choose the stage widths, depths, and resolutions better than human trial and error?

7.5.2.1 Compound Scaling#

Counting compute clarifies the scaling question immediately: a convnet's arithmetic grows linearly with depth, quadratically with channel width (via cicoc_\textrm{i} c_\textrm{o}), and quadratically with input resolution (via hwhw). Pushing any single dimension alone quickly hits diminishing returns—a very deep model on tiny thumbnails lacks fine detail to analyze, while high-resolution images require more layers so receptive fields can span large objects. Compound scaling (Tan and Le, 2019) scales all three dimensions in lockstep: each scaling step multiplies depth by 1.2, width by 1.1, and resolution by 1.15, roughly doubling total compute (1.2⋅1.12⋅1.152≈1.921.2 \cdot 1.1^2 \cdot 1.15^2 \approx 1.92). A single integer knob now generates an entire family: three steps produce a network 1.7×1.7\times deeper and 1.3×1.3\times wider on 1.5×1.5\times larger images at roughly 7×7\times the compute.

To design the base network itself, EfficientNet used neural architecture search (NAS) over stacks of inverted-bottleneck blocks, optimizing an objective balancing accuracy against multiply-add counts. As our GPU timing benchmark just demonstrated, optimizing theoretical multiply-adds can mislead real hardware. EfficientNetV2 (Tan and Le, 2021) replaced multiply-adds with measured training speed and parameter count in its search objective; notably, the search automatically swapped out depthwise blocks in early high-resolution stages for standard dense 3×33 \times 3 convolutions, which run faster on accelerators despite performing more arithmetic. In both generations, human engineering designed the core primitives while automated search allocated widths, depths, and resolutions across stages.

7.5.2.3 Squeeze-and-Excitation Gates#

The inverted-bottleneck blocks searched by EfficientNet include one extra lightweight module right after the depthwise convolution: a squeeze-and-excitation (SE) gate (Hu et al., 2018). Whereas a convolution aggregates information only over a local spatial window, an SE gate lets the network dynamically reweight entire feature channels using global image context. It squeezes each of the cc channels to a single scalar via global average pooling, passes that cc-dimensional summary through a tiny two-layer bottleneck MLP (hidden width c/rc/r with ReLU, output width cc with sigmoid, the excitation), and scales every channel of the feature map by its predicted gate in (0,1)(0, 1). With reduction ratio rr, the MLP adds only ~2c2/r2c^2/r parameters and operates on a single vector per image rather than every pixel, making its arithmetic cost negligible. Conceptually, SE acts as a simple channel-wise attention mechanism—foreshadowing the general attention layers of Chapter 10.

Because SE gates deliver consistent accuracy gains at almost zero compute cost, they appear throughout MobileNetV3 and RegNetY (Section 7.8, where problem 3 adds SE to RegNet). Implementing an SE block takes only a handful of lines: global pool, two linear layers, and channel-wise rescaling.

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])

With c=32c = 32 and r=4r = 4, the SE module adds just 2⋅322/4=5122 \cdot 32^2 / 4 = 512 weights and 40 biases while preserving the exact tensor shape, allowing it to drop into any block seamlessly.

7.5.3 Structural Re-parameterization#

7.5.3.1 The RepVGG Block#

ResNet (Section 7.4) established that multi-branch blocks with shortcut paths are dramatically easier to optimize than plain sequential stacks. At inference time, however, parallel branches carry real systems overhead: every branch must be launched separately and kept alive in memory until the summation point, lowering hardware utilization. A plain sequential stack of 3×33 \times 3 convolutions, by contrast, is ideal for accelerators—one dense, highly optimized kernel per layer and a single live activation buffer. RepVGG (Ding et al., 2021) achieves the best of both worlds by decoupling training topology from inference topology. During training, every layer sums three parallel branches before the ReLU: a 3×33 \times 3 convolution, a 1×11 \times 1 convolution, and an identity path, each with its own batch normalization (Figure 7.5.5). Once training finishes, every branch is purely linear in its input, so all three are algebraically fused into a single 3×33 \times 3 convolution that computes the exact same function. We train a multi-branch residual network and deploy a fast plain VGG stack.

Figure 7.5.5:

Structural re-parameterization. At training time each RepVGG layer sums three branches, a 3×33 \times 3 convolution, a 1×11 \times 1 convolution, and an identity, each with batch normalization. For inference the branches are folded into one 3×33 \times 3 convolution with a bias; the two networks compute the same function.

class RepVGGBlock(nn.Module):
    """Train-time block: 3x3, 1x1, and identity branches, each with BN."""
    def __init__(self, num_channels):
        super().__init__()
        self.conv3 = nn.Conv2d(num_channels, num_channels, kernel_size=3,
                               padding=1, bias=False)
        self.conv1 = nn.Conv2d(num_channels, num_channels, kernel_size=1,
                               bias=False)
        self.bn3, self.bn1, self.bn0 = (nn.BatchNorm2d(num_channels)
                                        for _ in range(3))

    def forward(self, X):
        return F.relu(self.bn3(self.conv3(X)) + self.bn1(self.conv1(X))
                      + self.bn0(X))

7.5.3.2 Fusing the Branches#

Collapsing all three branches into one convolution requires three simple steps of linear algebra. First, in inference mode batch normalization is a fixed per-channel affine map—subtracting the running mean μo\mu_o, dividing by σo2+ϵ\sqrt{\sigma_o^2 + \epsilon}, multiplying by γo\gamma_o, and adding βo\beta_o. Absorbing this affine map directly into a preceding convolution with kernel W\mathbf{W} and bias bob_o (indexed by output channel oo) gives an equivalent fused kernel and bias:

W^o=γoσo2+ϵ Wo,b^o=βo+γo(bo−μo)σo2+ϵ.(7.5.2)\begin{aligned} \hat{\mathbf{W}}_o &= \frac{\gamma_o}{\sqrt{\sigma_o^2 + \epsilon}}\, \mathbf{W}_o, \\ \hat{b}_o &= \beta_o + \frac{\gamma_o(b_o-\mu_o)}{\sqrt{\sigma_o^2 + \epsilon}}. \end{aligned} \tag{7.5.2}

Each output channel's kernel simply scales by its normalization factor while the fused bias absorbs all input-independent offsets (for instance, γo=2\gamma_o = 2, σo2+ϵ=16\sigma_o^2 + \epsilon = 16, μo=1\mu_o = 1, βo=1\beta_o = 1, and bo=0b_o = 0 give W^o=Wo/2\hat{\mathbf{W}}_o = \mathbf{W}_o / 2 and b^o=1−0.5=0.5\hat{b}_o = 1 - 0.5 = 0.5). Since RepVGGBlock's convolutions carry no biases, fuse_bn below implements the bo=0b_o = 0 case. Note that BN folding is completely general and is routinely applied by inference compilers to any Conv + BN pair.

Second, we express the remaining two branches as 3×33 \times 3 convolutions: a 1×11 \times 1 kernel is simply a 3×33 \times 3 kernel zero-padded by one pixel around its center, and the identity mapping is a 3×33 \times 3 convolution whose kernel Wo,iid\mathbf{W}^{\textrm{id}}_{o,i} equals 1 at the center tap when i=oi = o and 0 everywhere else. Third, by linearity of convolution, summing the outputs of three parallel convolutions on the same input is identical to a single convolution whose kernel is the sum of the three folded kernels and whose bias is the sum of the three folded biases (Figure 7.5.6).

Figure 7.5.6:

The kernels of one output channel oo applied to the input channel i=oi = o, after batch normalization has been folded into each branch (illustrative values; after folding, the identity's center entry is γo/σo2+ϵ\gamma_o/\sqrt{\sigma_o^2+\epsilon} rather than 1). The padded 1×11 \times 1 kernel and the identity kernel are nonzero only at the center, so the fused kernel differs from the 3×33 \times 3 branch only there. For i≠oi \neq o the identity kernel is zero.

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

Because fusion relies on inference-mode running statistics, we test fuse_block rigorously: we first pass several training batches (mean 1, standard deviation 2) through RepVGGBlock so its running statistics depart from 0 and 1, randomize γo\gamma_o and βo\beta_o so every term in (7.5.2) is exercised, and then compare the maximum absolute discrepancy between the multi-branch block in inference mode and the single fused convolution on fresh data.

blk = RepVGGBlock(8)
for _ in range(4):  # Move the BN running statistics
    blk(2 * torch.randn(32, 8, 16, 16) + 1)
with torch.no_grad():  # Nontrivial scales and shifts
    for bn in (blk.bn3, blk.bn1, blk.bn0):
        bn.weight.uniform_(0.5, 1.5)
        bn.bias.normal_()
blk.eval()
fused = fuse_block(blk)
X = 2 * torch.randn(32, 8, 16, 16) + 1
with torch.no_grad():
    error = (blk(X) - F.relu(fused(X))).abs().max()
float(error)
5.7220458984375e-06

The maximum discrepancy is on the order of 10−610^{-6} (pure single-precision floating-point roundoff), confirming exact functional equivalence. While weight count drops by only a tenth (from 10c210c^2 to 9c29c^2), the runtime execution simplifies dramatically: one dense convolution and one live activation tensor replace two convolutions, three normalizations, two additions, and three concurrent feature buffers.

7.5.3.3 Quantization after Fusion#

Real-world deployment introduces one subtle caveat that exact floating-point algebra misses. To save energy and memory bandwidth, edge accelerators widely quantize weights and activations down to 8-bit integers, mapping each tensor's dynamic range onto just 256 uniformly spaced levels. Because RepVGG's fused kernel sums three independently batch-normalized branches whose post-folding scales can differ by orders of magnitude, the fused weights and activations often develop heavy-tailed dynamic ranges that 256 discrete bins represent poorly. The impact can be catastrophic: naive post-training 8-bit quantization drops a fused RepVGG-B0 from 75.1% down to 40.2% ImageNet top-1 accuracy, whereas a standard ResNet loses only a fraction of a point (Chu et al., 2024). Regularizing branch scales during training resolves the issue, leaving an important engineering lesson: exact algebraic equivalence in FP32 does not guarantee equivalence under low-precision quantization.

7.5.4 Summary#

Efficient convnets elevate latency, memory, and energy to first-class design objectives alongside accuracy. Depthwise-separable convolutions factor spatial filtering from channel mixing, trimming layer cost to 1/co+1/k21/c_\textrm{o} + 1/k^2 of a dense convolution, while MobileNetV2's inverted bottleneck keeps the residual highway narrow to minimize peak activation memory. On Fashion-MNIST, MiniMobileNet trails a parameter-matched dense network by roughly two points while performing 7.7×7.7\times fewer multiply-adds, yet runs only 2–3.5×2\text{--}3.5\times faster because low-intensity depthwise layers are bottlenecked by memory bandwidth; moreover, narrowing the dense network to the same arithmetic budget beats MiniMobileNet in both accuracy and speed on this small task. Beyond layer factorization, compound scaling and latency-aware architecture search allocate depth, width, and resolution across stages, squeeze-and-excitation gates add global channel reweighting at negligible arithmetic cost, and structural re-parameterization trains multi-branch blocks that fold into fast plain convolutions at inference time (with care required for post-fusion quantization). Having examined efficiency by hand and by single-model search, we turn next to training recipes, systematic ResNet modernization, and population-level architecture design spaces.

7.5.5 Exercises#

  1. Channel permutation between groups (ShuffleNet). ● Grouped convolutions can be mixed without dense 1×11 \times 1 weights (Zhang et al., 2018). Follow a grouped k×kk \times k convolution (ci→coc_\textrm{i} \to c_\textrm{o} channels, gg groups) with a fixed permutation of the coc_\textrm{o} intermediate channels and a second grouped convolution (co→coc_\textrm{o} \to c_\textrm{o}, gg groups). Find the condition on gg and coc_\textrm{o} under which a permutation allows every output channel of the second layer to depend on all cic_\textrm{i} input channels, and construct that permutation explicitly.

  2. [code] Width multiplier. Add a width multiplier mm to MiniMobileNet that scales every stage's channel count by mm (Howard et al., 2017). Predict how the parameter count and multiply-adds scale with mm, and verify your prediction at m=0.5m = 0.5 using num_params and mobilenet_macs.

  3. [code] Folding batch normalization with bias. Extend fuse_bn to a preceding convolution that carries a nonzero bias bob_o using (7.5.2), and verify numerically that the Conv + BN pair in inference mode agrees with the single folded convolution to within 10−610^{-6}. Why can no fixed kernel and bias reproduce the output of Conv + BN when batch normalization runs in training mode?

  4. [code] The MobileNetV2 inverted bottleneck. ● MobileNetV2 (Sandler et al., 2018) replaces the block of Figure 7.5.3 with an inverted bottleneck: a 1×11 \times 1 expansion by factor t=6t = 6, a depthwise 3×33 \times 3 convolution, a linear 1×11 \times 1 projection (no ReLU), and a residual shortcut whenever input and output shapes match.

    1. Implement the inverted-bottleneck block with t=6t = 6 and replace the blocks of MiniMobileNet with it, choosing stage widths so the total parameter count stays near 542,474. Train it under the setup of Table 7.5.1 and compare validation accuracy and forward latency against MiniMobileNet.
    2. Add a ReLU after the final 1×11 \times 1 projection, train both the linear and ReLU variants three times each, and check whether the linear projection outperforms the ReLU projection at this scale.
    3. For a 96×9696 \times 96 input, tabulate the number of elements in each block's input, output, and expanded interior tensor. Explain why an inference engine that fuses or tiles the expansion and depthwise filtering channel-by-channel never needs to materialize the full expanded tensor in RAM.
  5. [code] Arithmetic intensity and batch size. ● MiniMobileNet performs 7.7×7.7\times fewer multiply-adds than VGGSmall, yet its GPU forward pass in Table 7.5.1 is only 2–3.5×2\text{--}3.5\times faster.

    1. Define the arithmetic intensity of a layer as its multiply-adds divided by the total number of tensor elements it reads and writes (weights + input activations + output activations). Compute the arithmetic intensity of the depthwise convolution, the pointwise convolution, and an equivalent dense 3×33 \times 3 convolution for every stage of MiniMobileNet. In which stages is the depthwise arithmetic intensity lowest, and how does this explain why EfficientNetV2 (Tan and Le, 2021) replaces early depthwise stages with dense convolutions?
    2. Measure forward_ms for MiniMobileNet and VGGSmall across batch sizes B∈{1,16,128,512}B \in \{1, 16, 128, 512\} and plot latency per image versus BB. How does their speed ratio change with BB, and why?
  6. [code] Training and quantizing RepVGG blocks. ● Why train a three-branch RepVGGBlock if it fuses into a single 3×33 \times 3 convolution at inference time?

    1. Extend RepVGGBlock and fuse_block to support stride-2 downsampling blocks that change channel width (keeping only the 3×33 \times 3 and 1×11 \times 1 branches when input and output shapes differ (Ding et al., 2021)). Build a small convnet from RepVGGBlocks and a matched plain convnet that keeps only the single 3×33 \times 3 branch during training. Train both on Fashion-MNIST, compare their convergence, and verify that fusing the trained RepVGG network leaves its validation accuracy unchanged.
    2. Fold the batch normalizations of the plain network with fuse_bn, then quantize the weights of both deployed networks to 8-bit integers using symmetric per-tensor scaling (w^=s⋅round(w/s)\hat{w} = s \cdot \mathrm{round}(w / s) with s=max⁡∣w∣/127s = \max |w| / 127). Compare the accuracy drop of the fused RepVGG network against the plain network and relate it to the weight-distribution analysis of Chu et al. (2024).

Discussions