7.8  Convolutional Network Design Spaces

Most of the networks we built in this chapter were designed by hand, fixing a small set of structural hyperparameters at every stage: how many blocks to stack, how many channels each stage emits, and which block topology to use. Where do those numbers come from, and are there general principles governing them? Looking back across our models offers surprisingly little guidance: ResNet-18 uses \((2, 2, 2, 2)\) blocks per stage, ResNet-50 uses \((3, 4, 6, 3)\), and ConvNeXt-T uses \((3, 3, 9, 3)\)—borrowed from Swin and validated once. Worse, these parameters interact tightly: under a fixed compute budget, making a stage deeper forces it to be narrower, and grouped convolutions free up compute for wider channels. Exhaustive search is out of the question: with four numbers per stage across four stages, even two choices per number yield \(2^{16} = 65{,}536\) distinct networks, each requiring its own training run. And even if brute force unearthed one winning network, a single point estimate cannot reveal which design choices mattered or how to adapt them to a new compute budget or building block.

Neural architecture search (NAS) (Zoph and Le 2016; Liu et al. 2018), which produced EfficientNet (Section 7.5), automates single-model selection, yet like manual engineering it returns one point solution rather than reusable scientific rules. Radosavovic et al. (2020) took a fundamentally different path: comparing entire design spaces—that is, populations of networks generated by a shared template and a small set of constraints. By sampling networks from a design space, training them briefly, and checking whether a proposed constraint improves the error distribution of the entire population, they distilled simple, generalizable design rules that define the RegNet family. Below we implement their AnyNet template, walk through their ImageNet population evidence (500 models per space), test their strongest rule ourselves on two small Fashion-MNIST populations, and train a compact RegNet head to head against ResNet-18.

7.8.1 The AnyNet Design Space

Across this chapter, modern convnets converged on the three-part stem–body–head template introduced in Section 7.2.3. The stem processes raw pixels with one or a few convolutions and usually downsamples immediately; the body performs the bulk of the computation through a sequence of stages, each repeating a uniform block at a fixed resolution while halving spatial dimensions and widening channels at every stage boundary; and the head maps the final feature tensor to class logits via global average pooling and a linear layer. ResNet’s four stages emit features at \(1/4\), \(1/8\), \(1/16\), and \(1/32\) of the input resolution—a multi-scale pyramid that endured all the way to ConvNeXt largely because downstream object detectors and segmentation heads tap all four scales simultaneously (Section 32.5).

7.8.1.1 Stage Parameters of Hand-Designed Networks

Table 7.8.1 compares four landmark architectures from this chapter side by side. Notice that while channel widths cleanly double from stage to stage in every row, stage depths follow no obvious rule.

Table 7.8.1: Stage depths and widths of four hand-designed networks (ImageNet versions).
Network Blocks per stage Output channels per stage Block
ResNet-18 (Section 7.4) 2, 2, 2, 2 64, 128, 256, 512 two \(3 \times 3\) convolutions
ResNet-50 (He et al. 2016) 3, 4, 6, 3 256, 512, 1024, 2048 \(1 \times 1\), \(3 \times 3\), \(1 \times 1\) bottleneck
ResNeXt-50 (Section 7.4.5.1) 3, 4, 6, 3 256, 512, 1024, 2048 bottleneck with 32 groups
ConvNeXt-T (Section 7.7) 3, 3, 9, 3 96, 192, 384, 768 \(7 \times 7\) depthwise, inverted bottleneck

The AnyNet design space of Radosavovic et al. (2020) locks in this macro template while leaving stage hyperparameters free (Figure 7.8.1). Its stem is a single stride-2 \(3 \times 3\) convolution emitting \(c_0 = 32\) channels, followed by batch normalization and ReLU (reading RGB images on ImageNet and a single grayscale channel on Fashion-MNIST). Its body comprises four stages, where stage \(i\) stacks \(d_i\) ResNeXt blocks (Figure 7.4.5): a \(1 \times 1\) convolution projects \(c_i\) channels to \(c_i / b_i\), a grouped \(3 \times 3\) convolution processes groups of \(g_i\) channels, and a second \(1 \times 1\) convolution restores \(c_i\) channels, with batch normalization after every convolution and a residual shortcut. (Note the paper’s notation: \(b_i\) is the bottleneck ratio, so the bottleneck width that Section 7.4.5.1 denoted \(b\) is \(c_i / b_i\) here.) The opening block of each stage halves spatial resolution with stride 2 and projects the shortcut via a stride-2 \(1 \times 1\) convolution. Global average pooling and a linear classifier form the head.

Figure 7.8.1: The AnyNet design space: a stem, a body of four stages, and a head. Stage \(\mathit{i}\) repeats a ResNeXt block \(\mathit{d_i}\) times; the first block of each stage halves the resolution. The annotations give the number of channels and the resolution after each part for an \(\mathit{r} \times \mathit{r}\) input; the head outputs \(\mathit{n}\) class scores. The free choices per stage are the depth \(\mathit{d_i}\), the width \(\mathit{c_i}\), the group width \(\mathit{g_i}\), and the bottleneck ratio \(\mathit{b_i}\).

Each stage therefore exposes four degrees of freedom: depth \(d_i\), output width \(c_i\), bottleneck ratio \(b_i \geq 1\), and group width \(g_i\) (the number of channels per group; do not confuse this with the group count \(g\) in Section 7.4.5.1, which remains the meaning of the groups argument in d2l.ResNeXtBlock). Across four stages, these 16 free numbers (sampling depths up to 16, widths up to 1024 in steps of 8, bottleneck ratios in \(\{1, 2, 4\}\), and power-of-two group widths up to 32) span roughly \((16 \cdot 128 \cdot 3 \cdot 6)^4 \approx 2 \times 10^{18}\) candidate architectures: impossible to enumerate, yet trivial to sample randomly. On \(224 \times 224\) ImageNet inputs, the stem and four stages perform five spatial halvings, ending at \(224 / 2^5 = 7 \times 7\).

7.8.1.2 Implementing AnyNet

To explore this space in code, we build a general AnyNet constructor driven by stage tuples, starting with its three-layer stem.

class AnyNet(d2l.Classifier):
    def stem(self, num_channels):
        return nn.Sequential(
            nn.LazyConv2d(num_channels, kernel_size=3, stride=2, padding=1,
                          bias=False),
            nn.LazyBatchNorm2d(), nn.ReLU())
def he_init():  # He initialization; Keras needs one instance per layer
    return tf.keras.initializers.VarianceScaling(2.0, 'fan_in',
                                                 'untruncated_normal')

class AnyNet(d2l.Classifier):
    def stem(self, num_channels):
        return tf.keras.models.Sequential([
            tf.keras.layers.ZeroPadding2D(1),  # Pad every side
            tf.keras.layers.Conv2D(num_channels, kernel_size=3, strides=2,
                                   use_bias=False,
                                   kernel_initializer=he_init()),
            tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5),
            tf.keras.layers.Activation('relu')])
he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')

class AnyNet(d2l.Classifier):
    def __init__(self, arch, stem_channels, lr=0.1, num_classes=10,
                 in_channels=1, rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
        self.net = self.create_net(in_channels, rngs)

    def stem(self, in_channels, num_channels, rngs):
        return nnx.Sequential(
            nnx.Conv(in_channels, num_channels, kernel_size=(3, 3),
                     strides=(2, 2), padding=(1, 1), use_bias=False,
                     kernel_init=he, rngs=rngs),
            nnx.BatchNorm(num_channels, momentum=0.9,
                          use_fast_variance=False, rngs=rngs), nnx.relu)
class AnyNet(d2l.Classifier):
    def stem(self, num_channels):
        net = nn.HybridSequential()
        net.add(nn.Conv2D(num_channels, kernel_size=3, padding=1, strides=2,
                          use_bias=False),
                nn.BatchNorm(), nn.Activation('relu'))
        return net

Each stage stacks depth instances of d2l.ResNeXtBlock (Section 7.4.5.1) parameterized by output width \(c_i\), number of groups, and bot_mul \(= 1/b_i\) (so group width equals \((c_i/b_i)/\text{groups}\)), with stride 2 applied only to the opening block.

@d2l.add_to_class(AnyNet)
def stage(self, depth, num_channels, groups, bot_mul):
    blk = []
    for i in range(depth):
        if i == 0:
            blk.append(d2l.ResNeXtBlock(num_channels, groups, bot_mul,
                use_1x1conv=True, strides=2))
        else:
            blk.append(d2l.ResNeXtBlock(num_channels, groups, bot_mul))
    return nn.Sequential(*blk)
@d2l.add_to_class(AnyNet)
def stage(self, depth, num_channels, groups, bot_mul):
    net = tf.keras.models.Sequential()
    for i in range(depth):
        if i == 0:
            net.add(d2l.ResNeXtBlock(num_channels, groups, bot_mul,
                use_1x1conv=True, strides=2))
        else:
            net.add(d2l.ResNeXtBlock(num_channels, groups, bot_mul))
    return net
@d2l.add_to_class(AnyNet)
def stage(self, depth, num_channels, groups, bot_mul, in_channels, rngs):
    blk = []
    for i in range(depth):
        if i == 0:
            blk.append(d2l.ResNeXtBlock(num_channels, groups, bot_mul,
                use_1x1conv=True, strides=(2, 2), in_channels=in_channels,
                rngs=rngs))
        else:
            blk.append(d2l.ResNeXtBlock(num_channels, groups, bot_mul,
                                        in_channels=num_channels, rngs=rngs))
    return nnx.Sequential(*blk)
@d2l.add_to_class(AnyNet)
def stage(self, depth, num_channels, groups, bot_mul):
    net = nn.HybridSequential()
    for i in range(depth):
        if i == 0:
            net.add(d2l.ResNeXtBlock(
                num_channels, groups, bot_mul, use_1x1conv=True, strides=2))
        else:
            net.add(d2l.ResNeXtBlock(
                num_channels, groups, bot_mul))
    return net

Assembling the stem, one stage per (depth, num_channels, groups, bot_mul) entry in arch, and the global-pooling head completes AnyNet. As in Section 7.4, all convolutional and linear weights use He initialization (Section 4.4.2.2), and convolutions omit biases before batch normalization.

@d2l.add_to_class(AnyNet)
def __init__(self, arch, stem_channels, lr=0.1, num_classes=10):
    super(AnyNet, self).__init__()
    self.save_hyperparameters()
    self.net = nn.Sequential(self.stem(stem_channels))
    for i, s in enumerate(arch):
        self.net.add_module(f'stage{i+1}', self.stage(*s))
    self.net.add_module('head', nn.Sequential(
        nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
        nn.LazyLinear(num_classes)))

@d2l.add_to_class(AnyNet)
def weight_init(self, module):
    # The Trainer calls this after the first minibatch fixed the shapes
    if type(module) in (nn.Linear, nn.Conv2d):
        nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
        if module.bias is not None:
            nn.init.zeros_(module.bias)
@d2l.add_to_class(AnyNet)
def __init__(self, arch, stem_channels, lr=0.1, num_classes=10):
    super(AnyNet, self).__init__()
    self.save_hyperparameters()
    self.net = tf.keras.models.Sequential([self.stem(stem_channels)])
    for s in arch:
        self.net.add(self.stage(*s))
    self.net.add(tf.keras.models.Sequential([
        tf.keras.layers.GlobalAvgPool2D(),
        tf.keras.layers.Dense(num_classes, kernel_initializer=he_init())]))
@d2l.add_to_class(AnyNet)
def create_net(self, in_channels, rngs):
    layers = [self.stem(in_channels, self.stem_channels, rngs)]
    stage_channels = self.stem_channels
    for s in self.arch:
        layers.append(self.stage(*s, stage_channels, rngs))
        stage_channels = s[1]
    layers.append(nnx.Sequential(
        global_avg_pool,
        nnx.Linear(stage_channels, self.num_classes, kernel_init=he,
                   rngs=rngs)))
    return nnx.Sequential(*layers)

def global_avg_pool(X):  # Average over height and width (NHWC)
    return X.mean(axis=(1, 2))
@d2l.add_to_class(AnyNet)
def __init__(self, arch, stem_channels, lr=0.1, num_classes=10):
    super(AnyNet, self).__init__()
    self.save_hyperparameters()
    self.net = nn.HybridSequential()
    self.net.add(self.stem(stem_channels))
    for s in arch:
        self.net.add(self.stage(*s))
    self.net.add(nn.GlobalAvgPool2D(), nn.Dense(num_classes))
    self.net.initialize(init.MSRAPrelu('in', 0))  # He initialization
    self.net.hybridize()  # Compile the network into one graph

Because every sampled model in a design space must be judged under the exact same training protocol, we attach the optimizer directly to AnyNet—matching the protocol used by Radosavovic et al. (2020) (and Recipe A in Section 7.6): SGD with momentum 0.9 (Section 7.5, Chapter 9), coupled weight decay (Section 2.7), and our chapter-wide d2l.cosine_warmup schedule (Section 7.1, warming up over the first 10% of num_steps to lr and decaying along a half-cosine to zero). Whereas the paper sets weight decay to \(5 \times 10^{-5}\) for 100 ImageNet epochs, for our shorter Fashion-MNIST runs we use \(10^{-3}\), which tuned best for RegNetX32 (Section 7.8.3) while performing equally well for ResNet18.

@d2l.add_to_class(AnyNet)
def configure_optimizers(self):
    optim = torch.optim.SGD(self.parameters(), lr=self.lr, momentum=0.9,
                            weight_decay=1e-3)  # Decay added to the gradient
    warmup = self.num_steps // 10
    schedule = torch.optim.lr_scheduler.LambdaLR(
        optim, lambda t: d2l.cosine_warmup(t, self.num_steps, warmup))
    return optim, schedule  # The Trainer steps it after every minibatch
class CoupledSGD(tf.keras.optimizers.SGD):
    """SGD that adds weight decay to the gradient (L2 regularization)."""
    def __init__(self, weight_decay, **kwargs):
        super().__init__(**kwargs)
        self.l2 = weight_decay

    def apply_gradients(self, grads_and_vars):
        return super().apply_gradients(
            [(g + self.l2 * v, v) for g, v in grads_and_vars])

@d2l.add_to_class(AnyNet)
def configure_optimizers(self):
    warmup = self.num_steps // 10
    schedule = lambda: self.lr * d2l.cosine_warmup(
        optim.iterations, self.num_steps, warmup)
    optim = CoupledSGD(1e-3, learning_rate=schedule, momentum=0.9)
    return optim
@d2l.add_to_class(AnyNet)
def configure_optimizers(self):
    warmup = self.num_steps // 10
    schedule = lambda t: self.lr * d2l.cosine_warmup(
        t, self.num_steps, warmup)
    return optax.chain(optax.add_decayed_weights(1e-3),  # In the gradient
                       optax.sgd(schedule, momentum=0.9))
@d2l.add_to_class(AnyNet)
def configure_optimizers(self):
    warmup = self.num_steps // 10
    schedule = lambda t: self.lr * d2l.cosine_warmup(  # MXNet counts
        t - 1, self.num_steps, warmup)  # updates from 1
    return gluon.Trainer(self.collect_params(), 'sgd', {
        'learning_rate': None, 'lr_scheduler': schedule,
        'momentum': 0.9, 'wd': 1e-3})  # wd: weight decay in the gradient

The weight_decay argument of a Keras optimizer shrinks the weights directly, outside the momentum buffer. CoupledSGD, as in Section 7.6, adds the decay to the gradient instead.

7.8.2 Comparing Design Spaces

How can we compare two massive design spaces without ever finding the single best architecture in either? Radosavovic et al. (2019) rely on four working assumptions so that a modestly sized sample of briefly trained models can faithfully represent an entire space:

  1. Good principles are abundant. Many networks satisfying sound design rules perform well (there are many good needles in the haystack), so optimizing a distribution over architectures is meaningful.
  2. Short-run ranking transfers. Validation accuracy after a brief training run correlates well with final converged accuracy (enabling 10-epoch ImageNet runs in the paper and 1-epoch Fashion-MNIST runs below).
  3. Small-scale findings extrapolate. Rules discovered at low compute budgets continue to hold when scaled up to large models (verified at scale at the end).
  4. Design factors roughly decouple. Individual structural constraints can be evaluated sequentially without severe hidden interactions.

None of these four assumptions is guaranteed a priori (the second and third are especially strong), and the exercises below test them directly at small scale.

Accepting these assumptions, we draw \(n\) random networks from a space, train each briefly, and record their validation errors \(e_1, \ldots, e_n\). The empirical cumulative distribution function (CDF) gives, at every error threshold \(e\), the fraction of sampled models achieving error at most \(e\):

\[\hat{F}(e) = \frac{1}{n}\sum_{j=1}^n \mathbf{1}(e_j \leq e). \tag{7.8.1}\]

The higher and farther left a CDF curve rises, the richer the space is in accurate networks. When one space’s CDF lies uniformly above another’s, a randomly drawn model from the first space beats any error threshold with higher probability—even if the single best model in both spaces happens to coincide.

Using this lens, Radosavovic et al. (2020) sampled 500 networks per space at ~400 million multiply-adds (400 MFLOPs), trained each for 10 ImageNet epochs, and plotted the resulting CDFs in Figure 7.8.2, tightening the unconstrained AnyNetX\(_A\) space one rule at a time. Sharing a single bottleneck ratio \(b\) across all four stages (AnyNetX\(_B\)) and then sharing a single group width \(g\) (AnyNetX\(_C\)) leaves the error distribution untouched (mean error ~49%)—a major win in its own right, eliminating 6 of the 16 free hyperparameters without accuracy loss. The dramatic breakthrough comes from constraining stage widths: requiring nondecreasing widths (\(c_{i+1} \geq c_i\)) slashes mean population error by six full points to ~43%, whereas constant or shrinking widths degrade mean error to 56% and 63%. Requiring nondecreasing depths (\(d_{i+1} \geq d_i\)) trims another half point while constant or shrinking depths fall behind.

Figure 7.8.2: Error CDFs of design spaces, reproduced from Radosavovic et al. (2020): 500 networks sampled from each space, each trained for 10 epochs on ImageNet at about 400 million multiply-adds. Legends give the minimum and mean top-1 error in percent; \(w_i\) is the paper’s symbol for the width \(c_i\). Top: one bottleneck ratio for all stages (AnyNetX\(_B\)) against none (AnyNetX\(_A\)), then one group width as well (AnyNetX\(_C\)). Bottom: widths that increase, stay equal, or decrease across stages; then depths that do the same in the space with increasing widths (AnyNetX\(_D\)).

Because empirical rules depend on the dataset, compute budget, and block type, it is instructive to apply the exact same population methodology to Fashion-MNIST for the single strongest rule: growing versus shrinking widths. We define two two-stage spaces using a 32-channel stem and ResNeXt blocks (\(b = 1\), group width 16), drawing stage depths \(d_i \in \{1, \ldots, 8\}\) and widths \(c_i \in \{16, 32, \ldots, 256\}\) subject to \(c_1 < c_2\) in one space and \(c_1 > c_2\) in the other. Just as in the paper, we match compute budgets by tallying multiply-adds across the stem, every block, and all projection shortcuts (Section 7.1).

def mult_adds(arch, r, stem_channels=32, group_width=16, num_classes=10):
    """Multiply-adds of an AnyNet with k = 1 for one r x r image; arch holds
    (depth, width) for each stage."""
    r //= 2  # The stem halves the resolution
    total, c_in = r * r * 9 * stem_channels, stem_channels  # Grayscale input
    for d, c in arch:
        total += r * r * c_in * c  # First 1 x 1 convolution, before the stride
        r //= 2
        total += r * r * c_in * c  # 1 x 1 convolution of the shortcut
        total += r * r * c * c * (2 * d - 1)  # The other 1 x 1 convolutions
        total += r * r * 9 * group_width * c * d  # Grouped 3 x 3 convolutions
        c_in = c
    return total + c_in * num_classes  # Linear head

To draw a candidate model, we sample two depths and two distinct widths, sort the widths according to the space’s constraint, and accept the draw only if its multiply-adds fall within 20% of our 112M budget per \(96 \times 96\) image (matching the RegNetX32 model we train in Section 7.8.3).

def sample_arch(rng, increasing, r=96, budget=112e6):
    """Depths and widths of two stages at about `budget` multiply-adds."""
    while True:
        depths = rng.integers(1, 9, size=2).tolist()
        widths = sorted(rng.choice(np.arange(16, 257, 16), 2, replace=False)
                        .tolist(), reverse=not increasing)
        arch = tuple(zip(depths, widths))
        if abs(mult_adds(arch, r) / budget - 1) <= 0.2:
            return arch

rng = np.random.default_rng()
for increasing in (True, False):
    arch = sample_arch(rng, increasing)
    print(arch, f'{mult_adds(arch, 96) / 1e6:.0f} million multiply-adds')
((3, 32), (6, 208)) 114 million multiply-adds
((3, 112), (6, 96)) 109 million multiply-adds
((2, 96), (8, 112)) 95 million multiply-adds
((5, 80), (8, 64)) 98 million multiply-adds
((6, 96), (2, 112)) 133 million multiply-adds
((3, 128), (6, 48)) 106 million multiply-adds
((6, 80), (1, 128)) 101 million multiply-adds
((2, 144), (4, 64)) 90 million multiply-adds

At matched compute, models with decreasing widths spend their channels on high-resolution early maps and narrow down at the top. Below we train each sampled architecture for one epoch (one-tenth of our full runs in Section 7.8.3) using AnyNet’s optimizer and record its validation error.

def population_errors(rng, increasing, data, n, num_epochs=1):
    """Validation errors of n networks sampled from one design space."""
    errors = []
    for _ in range(n):
        arch = sample_arch(rng, increasing)
        model = AnyNet(tuple((d, c, c // 16, 1) for d, c in arch), 32)
        model.num_steps = num_epochs * len(data.train_dataloader())
        trainer = d2l.Trainer(max_epochs=num_epochs, num_gpus=1)
        trainer.board.display = False  # We plot the errors ourselves
        trainer.fit(model, data)
        errors.append(1 - float(trainer.history['val_acc'][-1]))
    return np.array(errors)
def population_errors(rng, increasing, data, n, num_epochs=1):
    """Validation errors of n networks sampled from one design space."""
    errors = []
    for _ in range(n):
        arch = sample_arch(rng, increasing)
        trainer = d2l.Trainer(max_epochs=num_epochs)
        trainer.board.display = False  # We plot the errors ourselves
        with d2l.try_gpu():
            model = AnyNet(tuple((d, c, c // 16, 1) for d, c in arch), 32)
            model.num_steps = num_epochs * len(data.train_dataloader())
            trainer.fit(model, data)
        errors.append(1 - float(trainer.history['val_acc'][-1]))
    return np.array(errors)
def population_errors(rng, increasing, data, n, num_epochs=1):
    """Validation errors of n networks sampled from one design space."""
    errors = []
    for _ in range(n):
        arch = sample_arch(rng, increasing)
        model = AnyNet(tuple((d, c, c // 16, 1) for d, c in arch), 32)
        model.num_steps = num_epochs * len(data.train_dataloader())
        trainer = d2l.Trainer(max_epochs=num_epochs, num_gpus=1)
        trainer.board.display = False  # We plot the errors ourselves
        trainer.fit(model, data)
        errors.append(1 - float(trainer.history['val_acc'][-1]))
    return np.array(errors)
def population_errors(rng, increasing, data, n, num_epochs=1):
    """Validation errors of n networks sampled from one design space."""
    errors = []
    for _ in range(n):
        arch = sample_arch(rng, increasing)
        model = AnyNet(tuple((d, c, c // 16, 1) for d, c in arch), 32)
        model.num_steps = num_epochs * len(data.train_dataloader())
        trainer = d2l.Trainer(max_epochs=num_epochs, num_gpus=1)
        trainer.board.display = False  # We plot the errors ourselves
        trainer.fit(model, data)
        errors.append(1 - float(trainer.history['val_acc'][-1]))
    return np.array(errors)

We draw and train 12 models per space (24 single-epoch runs in all).

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
spaces = {'increasing widths': True, 'decreasing widths': False}
errors = {name: population_errors(rng, increasing, data, 12)
          for name, increasing in spaces.items()}

Plotting the empirical CDF Equation 7.8.1 produces a step function jumping by \(1/n\) at each sorted validation error.

def ecdf(e):
    """Corners of the step function of the empirical CDF of e."""
    e = np.sort(e)
    return np.repeat(e, 2), np.repeat(np.arange(len(e) + 1) / len(e), 2)[1:-1]

X, Y = zip(*(ecdf(e) for e in errors.values()))
d2l.plot(list(X), list(Y), xlabel='validation error',
         ylabel='fraction of networks', legend=list(errors),
         legend_loc='outside', figsize=(5, 2.5))
for name, e in errors.items():
    print(f'{name}: mean error {e.mean():.3f}, minimum {e.min():.3f}')
increasing widths: mean error 0.119, minimum 0.114
decreasing widths: mean error 0.124, minimum 0.112

increasing widths: mean error 0.115, minimum 0.111
decreasing widths: mean error 0.125, minimum 0.109

increasing widths: mean error 0.120, minimum 0.112
decreasing widths: mean error 0.125, minimum 0.114

increasing widths: mean error 0.116, minimum 0.111
decreasing widths: mean error 0.121, minimum 0.113

Here, the two CDFs largely overlap: across repeated draws, mean errors hover near 12% and differ by less than a single percentage point (usually nudging in favor of increasing widths), while the best models in both spaces land around 11%. A constraint worth twenty full points of mean error on ImageNet shrinks to under a point on Fashion-MNIST—too small for 12 samples per space to separate cleanly. That is a sobering yet illuminating finding: on an easy ten-class dataset where almost any reasonable convnet hits ~88% in a single epoch, architectural constraints have little room to separate populations. Design rules are never universal laws; their magnitude depends directly on the complexity of the task they were discovered on.

7.8.3 RegNet

7.8.3.1 Design Principles

Combining the surviving constraints from ImageNet defines the compact AnyNetX\(_E\) design space:

  • a single shared bottleneck ratio \(b\) across all stages;
  • a single shared group width \(g\) across all stages;
  • nondecreasing stage widths, \(c_{i} \leq c_{i+1}\);
  • nondecreasing stage depths, \(d_{i} \leq d_{i+1}\).

Inspecting the top-performing networks inside AnyNetX\(_E\) reveals one further striking pattern. Indexing blocks sequentially as \(j = 0, 1, \ldots\) from bottom to top, optimal block widths follow a simple linear ramp,

\[u_j = u_0 + a j, \tag{7.8.2}\]

parameterized by an initial width \(u_0\) and slope \(a > 0\). Because every block inside a stage shares one width, RegNet quantizes each \(u_j\) onto a geometric grid, much like the doubling widths of hand-crafted networks in Table 7.8.1, grouping consecutive blocks that snap to the same quantized width into a single stage to form a clean staircase. Figure 7.8.3 shows the staircase of one RegNet, and problem 2 asks you to work out another. Surprisingly, the authors also found that \(b = 1\) (no internal bottleneck compression at all) consistently outperforms the \(b = 4\) bottlenecks of ResNet-50 and ResNeXt-50. Combining quantized linear widths with \(b = 1\) defines the RegNetX family, collapsing 16 arbitrary stage numbers down to just a few interpretable parameters per compute budget.

Figure 7.8.3: Quantized linear widths for RegNetX-200MF, a network of 13 blocks. The width of each block on the linear ramp \(u_j = u_0 + a j\) (dots) snaps to the nearest level of the geometric grid \(u_0, u_0 m, u_0 m^2, \ldots\) (dashed lines), and consecutive blocks at the same level form a stage. With \(u_0 = 24\), \(a = 36.44\), and \(m = 2.49\) this gives four stages of depths 1, 1, 4, and 7, whose widths are 24, 56, 152, and 368 channels after rounding to multiples of 8.

7.8.3.2 RegNetX32 on Fashion-MNIST

Let us now construct a compact RegNet-style network obeying these rules and compare it directly with ResNet-18. Because upsampled \(96 \times 96\) Fashion-MNIST images originate from \(28 \times 28\) thumbnails, running four stages (five halvings) would shrink the final stages to tiny \(6 \times 6\) and \(3 \times 3\) grids; we therefore use two stages operating at \(24 \times 24\) and \(12 \times 12\) (problem 1 tests four stages). Behind a 32-channel stem, we hand-pick increasing depths and widths (stage 1 with \(d_1 = 4\), \(c_1 = 64\) and stage 2 with \(d_2 = 6\), \(c_2 = 160\)) together with \(b = 1\) and shared group width \(g = 16\) (giving \(64/16 = 4\) and \(160/16 = 10\) groups). One stem convolution, ten three-layer blocks, and one linear classifier total 32 layers, giving RegNetX32.

class RegNetX32(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        stem_channels, group_width, bot_mul = 32, 16, 1
        depths, channels = (4, 6), (64, 160)
        super().__init__(  # The number of groups is c_i / g
            tuple((d, c, c // group_width, bot_mul)
                  for d, c in zip(depths, channels)),
            stem_channels, lr, num_classes)
        self.num_steps = num_steps  # Length of the learning-rate schedule
class RegNetX32(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        stem_channels, group_width, bot_mul = 32, 16, 1
        depths, channels = (4, 6), (64, 160)
        super().__init__(  # The number of groups is c_i / g
            tuple((d, c, c // group_width, bot_mul)
                  for d, c in zip(depths, channels)),
            stem_channels, lr, num_classes)
        self.num_steps = num_steps  # Length of the learning-rate schedule
class RegNetX32(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None,
                 in_channels=1, rngs=None):
        stem_channels, group_width, bot_mul = 32, 16, 1
        depths, channels = (4, 6), (64, 160)
        super().__init__(  # The number of groups is c_i / g
            tuple((d, c, c // group_width, bot_mul)
                  for d, c in zip(depths, channels)),
            stem_channels, lr, num_classes, in_channels, rngs)
        self.num_steps = num_steps  # Length of the learning-rate schedule
class RegNetX32(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        stem_channels, group_width, bot_mul = 32, 16, 1
        depths, channels = (4, 6), (64, 160)
        super().__init__(  # The number of groups is c_i / g
            tuple((d, c, c // group_width, bot_mul)
                  for d, c in zip(depths, channels)),
            stem_channels, lr, num_classes)
        self.num_steps = num_steps  # Length of the learning-rate schedule

Inspecting layer_summary confirms that spatial resolution steps down cleanly from \(96 \to 48 \to 24 \to 12\) as channel depth grows.

RegNetX32().layer_summary((1, 1, 96, 96))
Sequential             (1, 32, 48, 48)
Sequential             (1, 64, 24, 24)
Sequential             (1, 160, 12, 12)
Sequential             (1, 10)
RegNetX32().layer_summary((1, 96, 96, 1))
Sequential             (1, 48, 48, 32)
Sequential             (1, 24, 24, 64)
Sequential             (1, 12, 12, 160)
Sequential             (1, 10)
RegNetX32().layer_summary((1, 96, 96, 1))
Sequential             (1, 48, 48, 32)
Sequential             (1, 24, 24, 64)
Sequential             (1, 12, 12, 160)
Sequential             (1, 10)
RegNetX32().layer_summary((1, 1, 96, 96))
HybridSequential       (1, 32, 48, 48)
HybridSequential       (1, 64, 24, 24)
HybridSequential       (1, 160, 12, 12)
GlobalAvgPool2D        (1, 160, 1, 1)
Dense                  (1, 10)

Tallying arithmetic as in Section 7.1, RegNetX32 executes 112 million multiply-adds per \(96 \times 96\) image—nearly three times fewer than ResNet-18’s 319 million.

Let us train RegNetX32 on \(96 \times 96\) Fashion-MNIST for 10 epochs with batch size 128 using AnyNet’s momentum-SGD optimizer at peak rate 0.1 (with one epoch of warmup).

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
model = RegNetX32(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
trainer = d2l.Trainer(max_epochs=10)
with d2l.try_gpu():
    model = RegNetX32(lr=0.1, num_steps=10 * len(data.train_dataloader()))
    trainer.fit(model, data)

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
model = RegNetX32(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
model = RegNetX32(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

Once the 10-epoch training run finishes, we call d2l.num_params(model) to report RegNetX32’s total parameter count alongside its final validation accuracy trainer.history["val_acc"][-1].

print(f'{d2l.num_params(model):,} parameters, validation accuracy '
      f'{trainer.history["val_acc"][-1]:.3f}')
519,658 parameters, validation accuracy 0.938
519,658 parameters, validation accuracy 0.939
519,658 parameters, validation accuracy 0.940
519,658 parameters, validation accuracy 0.940

To keep the comparison strictly controlled, we train ResNet-18 under the exact same AnyNet optimizer. Because ResNet-18 shares the same stem–body–head structure, we simply subclass AnyNet and override stem and stage using d2l.Residual (Section 7.4), passing (depth, width, stride) for each stage.

class ResNet18(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        super().__init__(((2, 64, 1), (2, 128, 2), (2, 256, 2), (2, 512, 2)),
                         64, lr, num_classes)
        self.num_steps = num_steps

    def stem(self, num_channels):
        return nn.Sequential(
            nn.LazyConv2d(num_channels, kernel_size=7, stride=2, padding=3,
                          bias=False),
            nn.LazyBatchNorm2d(), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1))

    def stage(self, depth, num_channels, stride):
        blk = [d2l.Residual(num_channels, use_1x1conv=stride > 1,
                            strides=stride)]
        blk += [d2l.Residual(num_channels) for _ in range(depth - 1)]
        return nn.Sequential(*blk)
class ResNet18(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        super().__init__(((2, 64, 1), (2, 128, 2), (2, 256, 2), (2, 512, 2)),
                         64, lr, num_classes)
        self.num_steps = num_steps

    def stem(self, num_channels):
        return tf.keras.models.Sequential([
            tf.keras.layers.ZeroPadding2D(3),  # Pad every side
            tf.keras.layers.Conv2D(num_channels, kernel_size=7, strides=2,
                                   use_bias=False,
                                   kernel_initializer=he_init()),
            tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5),
            tf.keras.layers.Activation('relu'),
            tf.keras.layers.ZeroPadding2D(1),  # Zeros are safe after a ReLU
            tf.keras.layers.MaxPool2D(pool_size=3, strides=2)])

    def stage(self, depth, num_channels, stride):
        net = tf.keras.models.Sequential()
        net.add(d2l.Residual(num_channels, use_1x1conv=stride > 1,
                             strides=stride))
        for _ in range(depth - 1):
            net.add(d2l.Residual(num_channels))
        return net
class ResNet18(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None,
                 in_channels=1, rngs=None):
        super().__init__(((2, 64, 1), (2, 128, 2), (2, 256, 2), (2, 512, 2)),
                         64, lr, num_classes, in_channels, rngs)
        self.num_steps = num_steps

    def stem(self, in_channels, num_channels, rngs):
        return nnx.Sequential(
            nnx.Conv(in_channels, num_channels, kernel_size=(7, 7),
                     strides=(2, 2), padding=3, use_bias=False,
                     kernel_init=he, rngs=rngs),
            nnx.BatchNorm(num_channels, momentum=0.9,
                          use_fast_variance=False, rngs=rngs), nnx.relu,
            max_pool)

    def stage(self, depth, num_channels, stride, in_channels, rngs):
        blk = [d2l.Residual(num_channels, use_1x1conv=stride > 1,
                            strides=(stride, stride), in_channels=in_channels,
                            rngs=rngs)]
        blk += [d2l.Residual(num_channels, in_channels=num_channels,
                             rngs=rngs) for _ in range(depth - 1)]
        return nnx.Sequential(*blk)

def max_pool(X):  # 3x3 windows, stride 2, padding 1 on every side
    return nnx.max_pool(X, window_shape=(3, 3), strides=(2, 2),
                        padding=((1, 1), (1, 1)))
class ResNet18(AnyNet):
    def __init__(self, lr=0.1, num_classes=10, num_steps=None):
        super().__init__(((2, 64, 1), (2, 128, 2), (2, 256, 2), (2, 512, 2)),
                         64, lr, num_classes)
        self.num_steps = num_steps

    def stem(self, num_channels):
        net = nn.HybridSequential()
        net.add(nn.Conv2D(num_channels, kernel_size=7, strides=2, padding=3,
                          use_bias=False),
                nn.BatchNorm(), nn.Activation('relu'),
                nn.MaxPool2D(pool_size=3, strides=2, padding=1))
        return net

    def stage(self, depth, num_channels, stride):
        net = nn.HybridSequential()
        net.add(d2l.Residual(num_channels, use_1x1conv=stride > 1,
                             strides=stride))
        for _ in range(depth - 1):
            net.add(d2l.Residual(num_channels))
        return net

Now we train ResNet18 on the exact same data for 10 epochs.

model = ResNet18(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

trainer = d2l.Trainer(max_epochs=10)
with d2l.try_gpu():
    model = ResNet18(lr=0.1, num_steps=10 * len(data.train_dataloader()))
    trainer.fit(model, data)

model = ResNet18(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

model = ResNet18(lr=0.1, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

As before, we print d2l.num_params(model) and the final validation accuracy trainer.history["val_acc"][-1] so we can compare ResNet18 directly against RegNetX32.

print(f'{d2l.num_params(model):,} parameters, validation accuracy '
      f'{trainer.history["val_acc"][-1]:.3f}')
11,175,370 parameters, validation accuracy 0.937
11,175,370 parameters, validation accuracy 0.941
11,175,370 parameters, validation accuracy 0.940
11,175,370 parameters, validation accuracy 0.941

Both architectures finish near 94% validation accuracy (93.7–94.2% across runs), yet RegNetX32 uses only 519,658 parameters compared with ResNet-18’s 11,175,370—under 5% of the weights and a third of the multiply-adds (112M vs. 319M). Three nuances frame this result:

  1. Architecture–optimizer coupling: Under plain SGD without momentum or weight decay (Section 7.4), RegNetX32 drops to ~91% while ResNet-18 reaches ~93%; RegNetX32 pulls even only under the momentum-and-weight-decay protocol on which the RegNet space was calibrated.
  2. Dataset ceiling: Scaling up to four-stage RegNets (RegNetX-400MF, -800MF, -1.6GF; 4.8–8.3M parameters) plateaus at the same 93–94% ceiling on Fashion-MNIST.
  3. Arithmetic vs. GPU latency: An epoch of RegNetX32 takes roughly \(1.5\times\) as long as one of ResNet-18, despite a third of the multiply-adds. Multiply-adds count arithmetic, not time (Section 7.5): RegNetX32 is nearly twice as deep, and its many narrow, grouped layers write about \(2.5\times\) as many activations per image, so memory traffic rather than arithmetic sets the pace. The RegNet authors found the same on ImageNet (Radosavovic et al. 2020): GPU runtime tracks activations more closely than multiply-adds, RegNetX models train and run about as fast as ResNets with equal activation counts, and at comparable multiply-adds RegNets run up to \(5\times\) faster than EfficientNets, whose activations grow linearly with multiply-adds.

7.8.4 Summary

Comparing design spaces shifts architectural analysis from single point estimates to error distributions over populations sampled from a parameterized template (AnyNet). Across 500 briefly trained ImageNet samples per space, tying a single bottleneck ratio \(b\) and group width \(g\) across stages costs nothing while enforcing nondecreasing stage widths (\(u_j = u_0 + a j\) quantized to a staircase) and depths cuts mean population error from 49% to 43%, yielding the RegNetX family. On Fashion-MNIST, RegNetX32 matches ResNet-18’s ~94% accuracy with under 5% of its parameters and a third of its multiply-adds. Across the entire chapter, a small core of structural primitives (repeatable blocks, activation normalization, and residual shortcuts) and the discipline of separating architectural gains from training-recipe gains form the foundation of modern vision backbones.

7.8.5 Exercises

  1. [code] Four stages at matched budget. RegNetX32 uses two stages on \(96 \times 96\) Fashion-MNIST. Extend it to the four stages of Figure 7.8.1, keeping widths and depths nondecreasing across stages and the total parameter count within 10% of RegNetX32. Compare validation accuracy and time per epoch against RegNetX32, and state the spatial feature-map resolution at which each of the four stages operates.

  2. Quantized linear widths. Radosavovic et al. (2020) parameterize the block widths of a \(d\)-block network via the linear ramp \(u_j = u_0 + a\, j\) (\(j = 0, \ldots, d-1\)) of Section 7.8.3, then snap each block to a geometric grid with ratio \(m\): \[s_j = \operatorname{round}\left(\frac{\log(u_j / u_0)}{\log m}\right), \qquad \tilde{u}_j = u_0\, m^{s_j}, \tag{7.8.3}\] grouping blocks with equal \(\tilde{u}_j\) into a single stage.

    1. Figure 7.8.3 shows the result for RegNetX-200MF. Repeat the computation for RegNetX-400MF, which has \(d = 22\), \(u_0 = 24\), \(a = 24.48\), and \(m = 2.54\) (the paper’s \(w_0, w_a, w_m\)): compute the number of stages, the depth \(d_i\) of each stage, and the stage widths rounded to the nearest multiple of 8.
    2. How do the number of stages and the staircase approximation \(\tilde{u}_j \approx u_j\) behave as \(m \to 1\) versus as \(m\) becomes large?
    3. Which of your rounded stage widths from (a) are not divisible by a shared group width of \(g = 16\), and how should they be adjusted?
  3. [code] RegNetY (adding Squeeze-and-Excitation). RegNetY inserts the squeeze-and-excitation gate SE (Section 7.5.2.3, with reduction ratio \(r = 4\)) into every ResNeXtBlock right after its grouped \(3 \times 3\) convolution (Radosavovic et al. 2020).

    1. Build RegNetY32 with the stage configuration of RegNetX32. Predict the added parameter count using the \(2c^2/r\) formula and verify it against d2l.num_params.
    2. Train RegNetY32 on \(96 \times 96\) Fashion-MNIST and compare its validation accuracy and time per epoch against RegNetX32. Why does SE add measurable wall-clock time despite adding almost zero multiply-adds?
  4. [code] Breaking the RegNet rules. ● Implement three variants of RegNetX32 at roughly matched parameter counts that each violate one AnyNetX\(_E\) rule (Section 7.8.3): (i) decreasing stage depths (\(d_1 > d_2\)), (ii) unequal group widths across stages, and (iii) bottleneck compression \(b_i > 1\) that differs across stages. Train each variant three times on Fashion-MNIST, compare against RegNetX32, and contrast your findings with the population CDFs in Figure 7.8.2. Why does testing a single hand-picked network per violation provide weaker evidence than comparing two empirical CDFs?

  5. [extended] A ConvNeXt design space. ● Build a two-stage AnyNet design space using ConvNeXtBlock (Section 7.7, adding the expansion ratio \(t \in \{2, 4\}\) as an argument) together with ConvNeXt’s stem and downsampling layers, sampling stage depths \(d_i \in \{1, 2, 4\}\) and widths \(c_i \in \{32, 64, 128\}\).

    1. Which of AnyNet’s four per-stage degrees of freedom (\(d_i, c_i, g_i, b_i\)) have a direct counterpart in ConvNeXtBlock, and which are fixed by depthwise separability?
    2. Sample 16 networks from the unconstrained space, 16 with a shared expansion ratio \(t_1 = t_2\), and 16 enforcing \(c_1 \le c_2\) and \(d_1 \le d_2\). Train each for 2 epochs on \(96 \times 96\) Fashion-MNIST, plot the three empirical error CDFs Equation 7.8.1, and check which RegNet principles carry over to ConvNeXt blocks.