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 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 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 time7.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 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 disjoint groups, restricting each output group to its matching input group and dividing both weights and multiply-adds by . As Figure 7.5.1 illustrates, grouping turns the dense channel-connectivity matrix into a block-diagonal pattern.
Input channels read by each output channel, for 8 input and 8 output channels. Each shaded cell is one kernel; groups keep of them.
Now push grouping all the way to its limit: , so every group contains a single channel. This depthwise convolution applies one spatial filter independently to each input channel with zero cross-channel mixing—the exact complement of a convolution (Section 6.4.3), which mixes all channels at each pixel with zero spatial interaction. Chaining a depthwise convolution and a pointwise 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.
Three input and three output channels with 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 kernel stack per output channel.
Let us quantify the savings. For an output and a kernel, a dense convolution requires multiply-adds, whereas the depthwise-separable pair requires for spatial filtering plus for pointwise mixing. Their ratio is
and the exact same ratio holds for parameter counts. In Figure 7.5.2 (), the dense layer uses weights versus for the separable pair (ratio ). Adding one more output channel costs 27 new weights in the dense layer versus only 3 in the separable layer. Once is large and , the ratio approaches : 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 to input channel and then linearly combines those filtered maps with scalar pointwise weights , it is equivalent to a dense convolution whose kernels are forced into the factored form . Every output channel must share the same spatial filter on input channel (up to a scalar multiple), whereas a dense convolution can learn an arbitrary independent filter for every 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 layer mapping 128 channels to 128 channels, where (7.5.1) predicts a reduction factor of .
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 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 convolution followed by a pointwise 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— less arithmetic and fewer parameters.
A depthwise-separable block from to channels. The depthwise convolution filters each input channel separately; the pointwise 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 layer squeezes a wide representation into a narrow subspace so that the expensive dense convolution stays affordable, and a second layer expands back out. When the 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 expansion lifts it sixfold to 144 channels, a depthwise convolution filters that expanded space, and a linear 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.
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 convolution and widens them again. The inverted bottleneck widens 24 channels to 144 for a depthwise 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 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 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 minibatchLet 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 convolution between the
same widths would require
weights in the
seven blocks alone— the 530,528 weights of our separable layers,
approaching the asymptotic 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 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 minibatchBefore launching training, let us tally the exact multiply-add counts on inputs. With "same" padding and stride , an input maps to side , and a grouped convolution with groups costs 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—
less arithmetic. That gap reflects where each model places its weights:
VGGSmall applies dense filters across high-resolution to
feature maps, whereas nearly three-quarters of MiniMobileNet's
weights sit in its final two pointwise layers acting on tiny
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
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 , 10 epochs; validation accuracy and forward-pass time ratio over repeated runs).
| Model | Parameters | Multiply-adds | Validation accuracy | Forward time |
|---|---|---|---|---|
| Mini-MobileNet | 542,474 | 50.3 million | 91–92% | 1 |
| VGG-style | 583,594 | 384.9 million | 93.5–94% | 2–3.5 |
| VGG-style, narrow | 75,854 | 49.1 million | 93% | 0.5–0.8 |
Three lessons jump out of Table 7.5.1:
- Matching parameters is not matching compute: At ~550K parameters,
VGGSmallbeatsMiniMobileNetby ~2 percentage points while performing more multiply-adds (keeping full resolution in its opening stage and learning unrestricted dense kernels). - At matched arithmetic on a small dataset, narrowing beats factorizing: Shrinking
VGGSmallto 50M multiply-adds (VGG-style, narrow, 76K parameters) beatsMiniMobileNetby ~1 point and runs faster. By (7.5.1), depthwise factorization pays off most at wide channel counts (saving at vs. nearly at ); 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. - Multiply-adds are a weak proxy for GPU wall-clock latency: A arithmetic reduction yields only a speedup because a dense layer performs multiply-adds per input read (high arithmetic intensity), whereas a depthwise 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 ), and quadratically with input resolution (via ). 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 (). A single integer knob now generates an entire family: three steps produce a network deeper and wider on larger images at roughly the compute.
7.5.2.2 Architecture Search#
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 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 channels to a single scalar via global average pooling, passes that -dimensional summary through a tiny two-layer bottleneck MLP (hidden width with ReLU, output width with sigmoid, the excitation), and scales every channel of the feature map by its predicted gate in . With reduction ratio , the MLP adds only ~ 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)).shapetorch.Size([2, 32, 16, 16])
With and , the SE module adds just 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 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 convolution, a 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 convolution that computes the exact same function. We train a multi-branch residual network and deploy a fast plain VGG stack.
Structural re-parameterization. At training time each RepVGG layer sums three branches, a convolution, a convolution, and an identity, each with batch normalization. For inference the branches are folded into one 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 , dividing by , multiplying by , and adding . Absorbing this affine map directly into a preceding convolution with kernel and bias (indexed by output channel ) gives an equivalent fused kernel and bias:
Each output channel's kernel simply scales by its normalization factor while
the fused bias absorbs all input-independent offsets (for instance,
, , , , and
give and
). Since RepVGGBlock's convolutions carry no
biases, fuse_bn below implements the 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 convolutions: a kernel is simply a kernel zero-padded by one pixel around its center, and the identity mapping is a convolution whose kernel equals 1 at the center tap when 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).
The kernels of one output channel applied to the input channel , after batch normalization has been folded into each branch (illustrative values; after folding, the identity's center entry is rather than 1). The padded kernel and the identity kernel are nonzero only at the center, so the fused kernel differs from the branch only there. For 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 fusedBecause 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 and 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 (pure single-precision floating-point roundoff), confirming exact functional equivalence. While weight count drops by only a tenth (from to ), 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
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 fewer multiply-adds, yet runs only
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#
-
Channel permutation between groups (ShuffleNet). ● Grouped convolutions can be mixed without dense weights (Zhang et al., 2018). Follow a grouped convolution ( channels, groups) with a fixed permutation of the intermediate channels and a second grouped convolution (, groups). Find the condition on and under which a permutation allows every output channel of the second layer to depend on all input channels, and construct that permutation explicitly.
-
[code] Width multiplier. Add a width multiplier to
MiniMobileNetthat scales every stage's channel count by (Howard et al., 2017). Predict how the parameter count and multiply-adds scale with , and verify your prediction at usingnum_paramsandmobilenet_macs. -
[code] Folding batch normalization with bias. Extend
fuse_bnto a preceding convolution that carries a nonzero bias using (7.5.2), and verify numerically that theConv + BNpair in inference mode agrees with the single folded convolution to within . Why can no fixed kernel and bias reproduce the output ofConv + BNwhen batch normalization runs in training mode? -
[code] The MobileNetV2 inverted bottleneck. ● MobileNetV2 (Sandler et al., 2018) replaces the block of Figure 7.5.3 with an inverted bottleneck: a expansion by factor , a depthwise convolution, a linear projection (no ReLU), and a residual shortcut whenever input and output shapes match.
- Implement the inverted-bottleneck block with and replace the blocks of
MiniMobileNetwith 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 againstMiniMobileNet. - Add a ReLU after the final projection, train both the linear and ReLU variants three times each, and check whether the linear projection outperforms the ReLU projection at this scale.
- For a 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.
- Implement the inverted-bottleneck block with and replace the blocks of
-
[code] Arithmetic intensity and batch size. ●
MiniMobileNetperforms fewer multiply-adds thanVGGSmall, yet its GPU forward pass in Table 7.5.1 is only faster.- 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 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? - Measure
forward_msforMiniMobileNetandVGGSmallacross batch sizes and plot latency per image versus . How does their speed ratio change with , and why?
- 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 convolution for every stage of
-
[code] Training and quantizing RepVGG blocks. ● Why train a three-branch
RepVGGBlockif it fuses into a single convolution at inference time?- Extend
RepVGGBlockandfuse_blockto support stride-2 downsampling blocks that change channel width (keeping only the and branches when input and output shapes differ (Ding et al., 2021)). Build a small convnet fromRepVGGBlocks and a matched plain convnet that keeps only the single branch during training. Train both on Fashion-MNIST, compare their convergence, and verify that fusing the trained RepVGG network leaves its validation accuracy unchanged. - 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 ( with ). 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).
- Extend