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)(2, 2, 2, 2) blocks per stage, ResNet-50 uses (3,4,6,3)(3, 4, 6, 3), and ConvNeXt-T uses (3,3,9,3)(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 216=65,5362^{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/41/4, 1/81/8, 1/161/16, and 1/321/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 20.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).
NetworkBlocks per stageOutput channels per stageBlock
ResNet-18 (Section 7.4)2, 2, 2, 264, 128, 256, 512two 3×33 \times 3 convolutions
ResNet-50 (He et al., 2016)3, 4, 6, 3256, 512, 1024, 20481×11 \times 1, 3×33 \times 3, 1×11 \times 1 bottleneck
ResNeXt-50 (Section 7.4.5.1)3, 4, 6, 3256, 512, 1024, 2048bottleneck with 32 groups
ConvNeXt-T (Section 7.7)3, 3, 9, 396, 192, 384, 7687×77 \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×33 \times 3 convolution emitting c0=32c_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 ii stacks did_i ResNeXt blocks (Figure 7.4.5): a 1×11 \times 1 convolution projects cic_i channels to ci/bic_i / b_i, a grouped 3×33 \times 3 convolution processes groups of gig_i channels, and a second 1×11 \times 1 convolution restores cic_i channels, with batch normalization after every convolution and a residual shortcut. (Note the paper's notation: bib_i is the bottleneck ratio, so the bottleneck width that Section 7.4.5.1 denoted bb is ci/bic_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×11 \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 i\mathit{i} repeats a ResNeXt block di\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 r×r\mathit{r} \times \mathit{r} input; the head outputs n\mathit{n} class scores. The free choices per stage are the depth di\mathit{d_i}, the width ci\mathit{c_i}, the group width gi\mathit{g_i}, and the bottleneck ratio bi\mathit{b_i}.

Each stage therefore exposes four degrees of freedom: depth did_i, output width cic_i, bottleneck ratio bi≥1b_i \geq 1, and group width gig_i (the number of channels per group; do not confuse this with the group count gg 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}\{1, 2, 4\}, and power-of-two group widths up to 32) span roughly (16⋅128⋅3⋅6)4≈2×1018(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×224224 \times 224 ImageNet inputs, the stem and four stages perform five spatial halvings, ending at 224/25=7×7224 / 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())

Each stage stacks depth instances of d2l.ResNeXtBlock (Section 7.4.5.1) parameterized by output width cic_i, number of groups, and bot_mul =1/bi= 1/b_i (so group width equals (ci/bi)/groups(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)

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)

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×10−55 \times 10^{-5} for 100 ImageNet epochs, for our shorter Fashion-MNIST runs we use 10−310^{-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

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 nn random networks from a space, train each briefly, and record their validation errors e1,…,ene_1, \ldots, e_n. The empirical cumulative distribution function (CDF) gives, at every error threshold ee, the fraction of sampled models achieving error at most ee:

F^(e)=1n∑j=1n1(ej≤e).(7.8.1)\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 AnyNetXA_A space one rule at a time. Sharing a single bottleneck ratio bb across all four stages (AnyNetXB_B) and then sharing a single group width gg (AnyNetXC_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 (ci+1≥cic_{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 (di+1≥did_{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; wiw_i is the paper's symbol for the width cic_i. Top: one bottleneck ratio for all stages (AnyNetXB_B) against none (AnyNetXA_A), then one group width as well (AnyNetXC_C). Bottom: widths that increase, stay equal, or decrease across stages; then depths that do the same in the space with increasing widths (AnyNetXD_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=1b = 1, group width 16), drawing stage depths di∈{1,…,8}d_i \in \{1, \ldots, 8\} and widths ci∈{16,32,…,256}c_i \in \{16, 32, \ldots, 256\} subject to c1<c2c_1 \lt c_2 in one space and c1>c2c_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×9696 \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

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)

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 (7.8.1) produces a step function jumping by 1/n1/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

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 AnyNetXE_E design space:

  • a single shared bottleneck ratio bb across all stages;
  • a single shared group width gg across all stages;
  • nondecreasing stage widths, ci≤ci+1c_{i} \leq c_{i+1};
  • nondecreasing stage depths, di≤di+1d_{i} \leq d_{i+1}.

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

uj=u0+aj,(7.8.2)u_j = u_0 + a j, \tag{7.8.2}

parameterized by an initial width u0u_0 and slope a>0a > 0. Because every block inside a stage shares one width, RegNet quantizes each uju_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=1b = 1 (no internal bottleneck compression at all) consistently outperforms the b=4b = 4 bottlenecks of ResNet-50 and ResNeXt-50. Combining quantized linear widths with b=1b = 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 uj=u0+aju_j = u_0 + a j (dots) snaps to the nearest level of the geometric grid u0,u0m,u0m2,…u_0, u_0 m, u_0 m^2, \ldots (dashed lines), and consecutive blocks at the same level form a stage. With u0=24u_0 = 24, a=36.44a = 36.44, and m=2.49m = 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×9696 \times 96 Fashion-MNIST images originate from 28×2828 \times 28 thumbnails, running four stages (five halvings) would shrink the final stages to tiny 6×66 \times 6 and 3×33 \times 3 grids; we therefore use two stages operating at 24×2424 \times 24 and 12×1212 \times 12 (problem 1 tests four stages). Behind a 32-channel stem, we hand-pick increasing depths and widths (stage 1 with d1=4d_1 = 4, c1=64c_1 = 64 and stage 2 with d2=6d_2 = 6, c2=160c_2 = 160) together with b=1b = 1 and shared group width g=16g = 16 (giving 64/16=464/16 = 4 and 160/16=10160/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

Inspecting layer_summary confirms that spatial resolution steps down cleanly from 96→48→24→1296 \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)

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

Let us train RegNetX32 on 96×9696 \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)

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

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)

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)

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

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×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×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×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 bb and group width gg across stages costs nothing while enforcing nondecreasing stage widths (uj=u0+aju_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×9696 \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 dd-block network via the linear ramp uj=u0+a ju_j = u_0 + a\, j (j=0,…,d−1j = 0, \ldots, d-1) of Section 7.8.3, then snap each block to a geometric grid with ratio mm:

sj=round⁡(log⁡(uj/u0)log⁡m),u~j=u0 msj,(7.8.3)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 u~j\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=22d = 22, u0=24u_0 = 24, a=24.48a = 24.48, and m=2.54m = 2.54 (the paper's w0,wa,wmw_0, w_a, w_m): compute the number of stages, the depth did_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 u~j≈uj\tilde{u}_j \approx u_j behave as m→1m \to 1 versus as mm becomes large?
  3. Which of your rounded stage widths from (a) are not divisible by a shared group width of g=16g = 16, and how should they be adjusted?
  1. [code] RegNetY (adding Squeeze-and-Excitation). RegNetY inserts the squeeze-and-excitation gate SE (Section 7.5.2.3, with reduction ratio r=4r = 4) into every ResNeXtBlock right after its grouped 3×33 \times 3 convolution (Radosavovic et al., 2020).

    1. Build RegNetY32 with the stage configuration of RegNetX32. Predict the added parameter count using the 2c2/r2c^2/r formula and verify it against d2l.num_params.
    2. Train RegNetY32 on 96×9696 \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?
  2. [code] Breaking the RegNet rules. ● Implement three variants of RegNetX32 at roughly matched parameter counts that each violate one AnyNetXE_E rule (Section 7.8.3): (i) decreasing stage depths (d1>d2d_1 > d_2), (ii) unequal group widths across stages, and (iii) bottleneck compression bi>1b_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?

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

    1. Which of AnyNet's four per-stage degrees of freedom (di,ci,gi,bid_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 t1=t2t_1 = t_2, and 16 enforcing c1≤c2c_1 \le c_2 and d1≤d2d_1 \le d_2. Train each for 2 epochs on 96×9696 \times 96 Fashion-MNIST, plot the three empirical error CDFs (7.8.1), and check which RegNet principles carry over to ConvNeXt blocks.

Discussions