7.7 ConvNeXt: Modernizing a ResNet Step by Step

Every architecture in this chapter so far has been convolutional, and until 2020 convnets sat atop every major image-classification leaderboard. Then architectures built around attention, without a single overlapping spatial convolution, took the lead. The first vision transformer did so in late 2020 with the help of a pre-training set far larger than ImageNet. In 2021 the Swin Transformer (Liu et al., 2021) needed no such help: trained on ImageNet alone, it achieved 81.3% top-1 accuracy, compared with 76.1% for a similarly sized ResNet-50. Did attention itself cause that five-point leap—and if so, were convolutional networks obsolete?

A brief sketch of vision transformers suffices here (we develop them fully in Chapter 11). A vision transformer (Dosovitskiy et al., 2021) partitions an image into a grid of patches, embeds each patch as a feature vector, and processes the sequence through a stack of identical blocks. Each block has two sublayers: an attention layer that lets every patch compute a data-dependent weighted average of other patches, followed by a pointwise MLP applied independently to each patch vector. Swin restores hierarchical convnet structure by computing attention inside local 7×77 \times 7 windows and downsampling between stages.

After Section 7.6, we should immediately be skeptical of crediting a five-point gap to attention alone. Swin differs from a 2015 ResNet in at least a dozen ways beyond attention: it trains with a 300-epoch modern recipe, slices images with a patch stem, allocates depth differently across stages, and adopts different activations and normalizations. To disentangle these factors, Liu et al. (2022) ran a landmark controlled experiment: starting from a standard ResNet-50, they introduced Swin-inspired modernizations one at a time, measuring ImageNet top-1 accuracy after every change without ever adding attention. The resulting pure convnet, ConvNeXt, reaches 82.0%—edging past Swin-T using primitives we have already built in this chapter: modern training recipes (Section 7.6), depthwise convolutions and inverted bottlenecks (Section 7.5), and layer normalization (Section 7.3). Because each row of their ablation requires a full ImageNet run, we walk through their published roadmap step by step, implement ConvNeXt from scratch, and then conduct a compact three-step modernization roadmap of our own on Fashion-MNIST starting from a parameter-matched ResNet-18.

7.7.1 The Modernization Roadmap#

Table 7.7.1 walks through the exact sequence of changes tested by Liu et al. (2022). Each row accumulates every modification above it while keeping compute anchored near Swin-T's budget of roughly 4.5 billion multiply-adds per image (reported as 4.5 GFLOPs in the paper).

Table 7.7.1. The ConvNeXt modernization roadmap (Liu et al., 2022). ImageNet top-1 accuracy of a ResNet-50 as design changes accumulate; each row includes all rows above it, at roughly constant cost. Swin-T, a transformer of similar cost, reaches 81.3%.
ChangeWhat it meansTop-1
(starting point)ResNet-50 with its 2015 recipe76.1%
Modern training recipe300 epochs, AdamW, Mixup, label smoothing, stochastic depth (Section 7.6)78.8%
Stage ratioblocks per stage (3,4,6,3)→(3,3,9,3)(3, 4, 6, 3) \to (3, 3, 9, 3)79.4%
Patchify stem7×77 \times 7 stride-2 convolution plus pooling →\to one 4×44 \times 4 stride-4 convolution79.5%
Depthwise convolutionsthe 3×33 \times 3 convolution becomes depthwise; width grows from 64 to 96 channels80.5%
Inverted bottleneckexpand 4×4\times inside the block instead of compressing80.6%
Large kernelsdepthwise convolution moved to the front and enlarged to 7×77 \times 780.6%
ReLU →\to GELUa smooth activation, as in transformers80.6%
Fewer activationsone activation per block instead of three81.3%
Fewer normalizationsone normalization per block instead of three81.4%
BN →\to LNlayer normalization over channels at each position81.5%
Separate downsamplingan LN plus 2×22 \times 2 stride-2 convolution between stages82.0%

Immediately, the very first row delivers the largest single jump—without touching a single layer of the network. Echoing Section 7.6, upgrading the training recipe alone lifts an untouched ResNet-50 by 2.7 percentage points. Of the 5.9-point total gain separating 2015 ResNet-50 from ConvNeXt, 2.7 points come from training and 3.2 from architecture (in this ordering), confirming that pitting a modern transformer against a 2015-recipe ResNet confounded recipes with architectures.

7.7.1.1 Macro Design#

The next two rows reshape the network's macro structure. Swin-T allocates its blocks across four stages in a 1:1:3:11{:}1{:}3{:}1 ratio, concentrating depth in stage 3 where feature maps are compact and compute is cheap; shifting ResNet-50's (3,4,6,3)(3, 4, 6, 3) layout to (3,3,9,3)(3, 3, 9, 3) adds 0.6 points. Next comes the stem. Whereas ResNet opens with an overlapping 7×77 \times 7 stride-2 convolution followed by max-pooling to downsample fourfold, a vision transformer chops the image into disjoint patches and projects each patch through a shared linear layer—which is algebraically identical to a non-overlapping 4×44 \times 4 convolution with stride 4 (Section 6.3). Swapping in this patchify stem preserves accuracy (79.5%) while producing one token vector per 4×44 \times 4 patch, just like a transformer.

7.7.1.2 Depthwise Convolutions and the Inverted Bottleneck#

A transformer block cleanly factors computation into two stages: attention mixes information across spatial positions, and the MLP mixes information across channels at each position. As we saw in Section 7.5.1.1, a convnet can perform the exact same factorization: a depthwise convolution mixes across space within each channel, and 1×11 \times 1 convolutions mix across channels at each pixel. Replacing the dense 3×33 \times 3 layer in ResNet's bottleneck with a depthwise convolution slashes compute enough to widen stage 1 from 64 to 96 channels (matching Swin-T), jumping accuracy to 80.5%.

Once the spatial convolution is depthwise rather than dense, its cost scales linearly rather than quadratically with width, removing the rationale for compressing channels before filtering. ConvNeXt therefore adopts MobileNetV2's inverted bottleneck (Section 7.5), maintaining a thin residual stream and expanding 4×4\times inside the block (the same 1×→4×→1×1\times \to 4\times \to 1\times geometry as a transformer MLP), nudging accuracy to 80.6%.

With spatial filtering now lightweight, kernel size also becomes easy to enlarge. First, moving the depthwise convolution to the front of the block so it acts on cc channels instead of 4c4c drops accuracy by 0.7 points (to 79.9%—the sole dip on the roadmap); expanding its kernel from 3×33 \times 3 to 7×77 \times 7 immediately recovers that ground. A 7×77 \times 7 filter matches the receptive field of three stacked 3×33 \times 3 layers (Section 6.3). If both cover the same window, why should the single large kernel help? The stack covers its window unevenly: far more paths lead from a central pixel to the output than from a pixel at the border, so the effective receptive field of a stack is roughly Gaussian and much smaller than the nominal one (Luo et al., 2016). A single 7×77 \times 7 kernel can give every position in the window whatever weight it learns, in one layer. Back in VGG (Section 7.2.1), dense 7×77 \times 7 kernels were prohibitively expensive (k2cicok^2 c_\textrm{i} c_\textrm{o}); for a depthwise kernel (k2ck^2 c), growing from 3×33 \times 3 to 7×77 \times 7 only scales a tiny fraction of block compute by 49/9≈549/9 \approx 5. Accuracy saturates right at 7×77 \times 7, matching the exact window size of Swin's local attention.

7.7.1.3 Micro Design#

The final group of edits refines individual layers inside the block. Swapping ReLU for GELU (Hendrycks and Gimpel, 2016), the smooth activation favored by transformers, leaves accuracy unchanged on its own (80.6%). What does move the needle is trimming the number of activations and normalizations. A classic ResNet bottleneck puts a normalization and an activation after all three convolutions, whereas a transformer block uses only a single activation inside its MLP and fewer normalizations. Removing two of the three GELUs, keeping only the one between the two 1×11 \times 1 layers, jumps accuracy by 0.7 points, the biggest micro-design gain on the table. (There is still no crisp theoretical proof for why removing two nonlinearities improves accuracy; it is best viewed as a clean empirical finding.) Trimming three normalizations down to one adds 0.1 points, and switching that lone normalization from batch normalization to per-position layer normalization across channels (Section 7.3.4.1) adds another 0.1 points (81.5%). Figure 7.7.1 compares the original ResNet bottleneck against the resulting ConvNeXt block (including the learnable per-channel layer scale γ\boldsymbol{\gamma} described below).

Figure 7.7.1:

The ResNet-50 bottleneck block and the ConvNeXt block that the roadmap turns it into. Three normalizations and three activations become one of each; the compress-process-expand bottleneck becomes an inverted bottleneck led by a 7×77 \times 7 depthwise convolution, and a learnable per-channel layer scale γ\boldsymbol{\gamma} multiplies the branch before the addition.

Finally, whereas ResNet downsamples inside the opening block of each stage with a stride-2 convolution, Swin inserts dedicated patch-merging layers between stages. Adopting separate downsampling layers (a layer normalization followed by a 2×22 \times 2 stride-2 convolution between stages, plus normalizations after the stem and before the linear head to stabilize training) completes the roadmap at 82.0%. Figure 7.7.2 shows the assembled ConvNeXt-T backbone, stacking (3,3,9,3)(3, 3, 9, 3) blocks of widths (96,192,384,768)(96, 192, 384, 768) in the classic stem--body--head layout (Section 7.2.3).

Figure 7.7.2:

ConvNeXt-T. A patchify stem replaces convolution-plus-pooling; stages of 3, 3, 9, and 3 blocks are joined by separate LN plus 2×22 \times 2 stride-2 downsampling layers; there is no pooling anywhere in the body.

At matched compute, ConvNeXt-T surpasses Swin-T without a single attention layer. The takeaway is not that convolutions are inherently superior to attention, but that the 2021 accuracy gap came from training recipes and architectural design hygiene rather than attention alone—under matched tuning, both paradigms scale comparably.

7.7.2 Implementation#

Because the modernization roadmap stripped away more layers than it added, the ConvNeXt block is remarkably clean to implement.

7.7.2.1 The ConvNeXt Block#

Each block applies a 7×77 \times 7 depthwise convolution, per-position layer normalization, a 1×11 \times 1 expansion (c→4cc \to 4c), GELU, and a 1×11 \times 1 projection (4c→c4c \to c), then adds the residual input. Two training stabilizers from the paper accompany the block. Layer scale (Touvron et al., 2021) multiplies the residual branch by a learnable per-channel vector γ\boldsymbol{\gamma} initialized to 10−610^{-6} (distinct from batch-norm scale), ensuring every block starts nearly as the identity so deep optimization begins smoothly. It does for a layer-normalized block what starting the last batch-norm scale of a residual branch at zero does for a ResNet (Section 7.4.2). Stochastic depth randomly drops entire residual branches during training via d2l.drop_path (Section 7.6).

Because layer normalization operates across the channel vector at each spatial location, in a channels-last tensor (batch, height, width, channels) it is standard LayerNorm over the final axis, and the two 1×11 \times 1 convolutions are ordinary linear layers over that same axis. Following Liu et al. (2022), we initialize all convolutional and linear weights from N(0,0.022)\mathcal{N}(0, 0.02^2) with zero biases.

Images are stored channels-first, so LayerNorm2d permutes to channels-last for the normalization and back, and the block does the same around its two linear layers.

class LayerNorm2d(nn.LayerNorm):
    """LayerNorm over the channel axis of an NCHW tensor."""
    def __init__(self, num_channels, eps=1e-6):
        super().__init__(num_channels, eps=eps)

    def forward(self, X):
        return super().forward(X.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)

class ConvNeXtBlock(nn.Module):
    """Depthwise 7x7, norm, 1x1 expand, GELU, 1x1 project, scaled residual."""
    def __init__(self, dim, drop_prob=0.0, layer_scale=1e-6,
                 norm=LayerNorm2d):
        super().__init__()
        self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3,
                                groups=dim)
        self.norm = norm(dim)
        self.pwconv1 = nn.Linear(dim, 4 * dim)  # 1x1 conv in channels-last
        self.pwconv2 = nn.Linear(4 * dim, dim)
        self.gamma = nn.Parameter(layer_scale * torch.ones(dim))
        self.drop_prob = drop_prob

    def forward(self, X):
        Y = self.norm(self.dwconv(X)).permute(0, 2, 3, 1)  # to channels-last
        Y = self.pwconv2(F.gelu(self.pwconv1(Y)))
        Y = (self.gamma * Y).permute(0, 3, 1, 2)  # back to channels-first
        return X + d2l.drop_path(Y, self.drop_prob, self.training)

7.7.2.2 The Full Network#

As in VGG (Section 7.2.1), the complete architecture iterates over a tuple of (depth, channels) stage specifications, opening with the patchify stem plus layer normalization and inserting dedicated downsampling layers between stages with no spatial pooling anywhere in the body. Stochastic-depth drop probabilities ramp linearly from 0 in the first block to drop_path_max in the last. For Fashion-MNIST we adopt the compact ConvNeXt-atto profile, with widths (40,80,160,320)(40, 80, 160, 320) and stage depths (2,2,6,2)(2, 2, 6, 2), keeping the third stage deepest just like ConvNeXt-T. Exposing norm as an argument and stem as a method makes swapping them trivial in our ablation below.

class ConvNeXt(d2l.Classifier):
    def __init__(self, arch=((2, 40), (2, 80), (6, 160), (2, 320)),
                 lr=2e-3, num_classes=10, drop_path_max=0.1,
                 norm=LayerNorm2d):
        super().__init__()
        self.save_hyperparameters()
        depths = [d for d, c in arch]
        rates = torch.linspace(0, drop_path_max, sum(depths)).tolist()
        layers = self.stem(arch[0][1], norm)
        c_prev, b = arch[0][1], 0
        for i, (depth, c) in enumerate(arch):
            if i > 0:  # Separate downsampling layer between stages
                layers += [norm(c_prev),
                           nn.Conv2d(c_prev, c, kernel_size=2, stride=2)]
            for _ in range(depth):
                layers.append(ConvNeXtBlock(c, rates[b], norm=norm))
                b += 1
            c_prev = c
        layers += [nn.AdaptiveAvgPool2d((1, 1)), norm(c_prev), nn.Flatten(),
                   nn.Linear(c_prev, num_classes)]
        self.net = nn.Sequential(*layers)
        self.net.apply(self.weight_init)

    def stem(self, c, norm):  # Patchify: a 4x4 convolution with stride 4
        return [nn.Conv2d(1, c, kernel_size=4, stride=4), norm(c)]

    def weight_init(self, module):
        if type(module) in (nn.Conv2d, nn.Linear):
            nn.init.normal_(module.weight, std=0.02)
            nn.init.zeros_(module.bias)

On 64×6464 \times 64 Fashion-MNIST inputs, the patchify stem produces a 16×1616 \times 16 grid, and the three downsampling layers step resolution down to 8×88 \times 8, 4×44 \times 4, and 2×22 \times 2 before global average pooling. Let us check the output shape and count trainable parameters.

model = ConvNeXt()
assert model(torch.randn(1, 1, 64, 64)).shape == (1, 10)
d2l.num_params(model)
3376450

Our ConvNeXt-atto model contains exactly 3,376,450 parameters—roughly a third of ResNet-18's 11.2 million (Section 7.4). Because any misconfigured width or kernel size immediately shifts this exact number, matching the parameter count is a reliable sanity check for any reimplementation.

7.7.3 A Small Roadmap on Fashion-MNIST#

Every choice in Table 7.7.1 was validated on 1.3 million 224×224224 \times 224 ImageNet photos. Do those same architectural decisions carry over to small 64×6464 \times 64 grayscale garments? To find out, we run a compact cumulative roadmap of our own: starting from a parameter-matched control, a ResNet-18 narrowed from base width 64 to 35 channels (3.35M parameters), we apply ConvNeXt's modifications in three cumulative steps. Every model trains for 20 epochs on full Fashion-MNIST under the compact modern recipe from Section 7.6 (AdamW with decoupled weight decay, 10% linear warmup plus cosine decay, label smoothing, and Mixup; Chapter 9 covers AdamW in detail). To isolate architecture cleanly, we set ConvNeXt's stochastic-depth rate to 0 so both families share identical regularization.

Packaging the training procedure as a ModernRecipe mixin lets every model in the roadmap inherit the exact same optimizer, schedule, and mixed training step while keeping validation loss as plain cross-entropy.

class ModernRecipe:
    """AdamW, linear warmup then cosine decay, label smoothing, Mixup."""
    def configure_optimizers(self):
        optim = torch.optim.AdamW(self.parameters(), lr=self.lr,
                                  weight_decay=0.05)
        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

    def training_step(self, batch):
        X, y_a, y_b, lam = d2l.mixup(*batch, alpha=0.2)
        Y_hat = self(X)
        loss = lambda y: F.cross_entropy(Y_hat, y, label_smoothing=0.1)
        return lam * loss(y_a) + (1 - lam) * loss(y_b)

class ModernConvNeXt(ModernRecipe, ConvNeXt):
    def __init__(self, num_steps, lr=2e-3, norm=LayerNorm2d):
        super().__init__(lr=lr, drop_path_max=0.0, norm=norm)
        self.num_steps = num_steps

Our baseline CompactResNet18 stacks d2l.Residual blocks (Section 7.4) across widths 35, 70, 140, and 280 behind ResNet's standard 7×77 \times 7 stride-2 stem and max-pooling.

class CompactResNet18(ModernRecipe, d2l.Classifier):
    """ResNet-18 with base width 35 instead of 64, trained by the recipe."""
    def __init__(self, num_steps, lr=2e-3, num_classes=10, base=35):
        super().__init__()
        self.save_hyperparameters()
        layers = [nn.LazyConv2d(base, kernel_size=7, stride=2, padding=3,
                                bias=False),
                  nn.LazyBatchNorm2d(), nn.ReLU(),
                  nn.MaxPool2d(kernel_size=3, stride=2, padding=1)]
        for i, c in enumerate((base, 2 * base, 4 * base, 8 * base)):
            for j in range(2):
                down = i > 0 and j == 0
                layers.append(d2l.Residual(c, use_1x1conv=down,
                                           strides=2 if down else 1))
        layers += [nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
                   nn.LazyLinear(num_classes)]
        self.net = nn.Sequential(*layers)

    def weight_init(self, module):
        # The Trainer calls this after the first minibatch fixed the shapes
        if type(module) in (nn.Conv2d, nn.Linear):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
            if module.bias is not None:
                nn.init.zeros_(module.bias)

We bundle the paper's changes into three clean steps by architectural region: (1) replace ResNet's blocks and stages with ConvNeXt's 7×77 \times 7 inverted bottlenecks, (2,2,6,2)(2, 2, 6, 2) stage ratio, single GELU/norm, layer scale, and separate downsampling while keeping ResNet's stem and batch normalization (covering eight rows of Table 7.7.1); (2) swap batch normalization for layer normalization; and (3) replace ResNet's stem with the 4×44 \times 4 patchify stem to arrive at full ConvNeXt. (Although the original paper swapped the stem earlier, the final architecture is order-independent, even if individual step attributions can vary slightly.) Overriding stem in ResNetStemConvNeXt and toggling norm implements all four models cleanly.

class ResNetStemConvNeXt(ModernConvNeXt):
    """ConvNeXt with the stem of ResNet-18 instead of the patchify stem."""
    def stem(self, c, norm):  # 7x7 convolution with stride 2, max-pooling
        return [nn.Conv2d(1, c, kernel_size=7, stride=2, padding=3), norm(c),
                nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2, padding=1)]

roadmap = {'compact ResNet-18': CompactResNet18,
           'ConvNeXt blocks and stages, BN': (
               lambda num_steps: ResNetStemConvNeXt(num_steps,
                                                    norm=nn.BatchNorm2d)),
           '+ BN -> LN': ResNetStemConvNeXt,
           '+ patchify stem = ConvNeXt': ModernConvNeXt}

Let us train all four models in sequence and record their parameter counts and final validation accuracies.

data = d2l.FashionMNIST(batch_size=128, resize=(64, 64))
num_steps = 20 * len(data.train_dataloader())
results = {}
for name, make_model in roadmap.items():
    model = make_model(num_steps)
    trainer = d2l.Trainer(max_epochs=20, num_gpus=1)
    trainer.board.display = False  # Four runs; we tabulate the results
    trainer.fit(model, data)
    results[name] = (d2l.num_params(model), trainer.history['val_acc'][-1])

We now iterate through results to display the parameter count and 20-epoch validation accuracy for each step along the roadmap.

for name, (params, accuracy) in results.items():
    print(f'{name:34s} {params:>9,} parameters, '
          f'validation accuracy {accuracy:.3f}')
compact ResNet-18                  3,346,675 parameters, validation accuracy 0.936
ConvNeXt blocks and stages, BN     3,377,770 parameters, validation accuracy 0.937
+ BN -> LN                         3,377,770 parameters, validation accuracy 0.937
+ patchify stem = ConvNeXt         3,376,450 parameters, validation accuracy 0.918
Table 7.7.2. Our roadmap on Fashion-MNIST beside the paper's. The last column is the validation accuracy after 20 epochs of the modern recipe at 64×6464 \times 64, rounded to the stability of repeated runs; the paper's column adds up the ImageNet top-1 gains of the rows of Table 7.7.1 that each step covers.
StepRows of the paperGain on ImageNetParametersValidation accuracy
Compact ResNet-18(ResNet-50 with the modern recipe)3.35M≈ 94%
ConvNeXt blocks and stages, BNstage ratio to fewer normalizations, separate downsampling+3.03.38M≈ 94%
BN →\to LNBN →\to LN+0.13.38M≈ 94%
Patchify stem (our ConvNeXt)patchify stem+0.13.38M≈ 92%

The results in Table 7.7.2 pinpoint what transfers to 64×6464 \times 64 Fashion-MNIST and what does not. Keeping ResNet's overlapping stem, ConvNeXt's modernized blocks, stage ratio, and layer normalization tie with our parameter-matched CompactResNet18 (~94%, within ~43--46M multiply-adds per image). The entire ~2-point drop to ~92% comes from the single step that was neutral on 224×224224 \times 224 ImageNet: the non-overlapping 4×44 \times 4 stride-4 patchify stem, which jumps straight to a coarse 16×1616 \times 16 grid in one linear projection. Architectural choices tuned at ImageNet resolution do not transfer blindly to low-resolution domains, and a cumulative ablation immediately identifies which component to adapt.

7.7.4 Limits and Open Problems#

While ConvNeXt showed that pure convnets match hierarchical Vision Transformers in supervised classification under matched recipes, two active frontiers remain:

  1. Masked self-supervised pretraining: Dropping random image patches as in masked autoencoders (He et al., 2022) is natural for a sequence of patch tokens, whereas dense sliding convolutions bleed across masked holes. ConvNeXt V2 (Woo et al., 2023) bridges this gap with sparse convolutions and Global Response Normalization (Exercise 4).
  2. Global context: Even a 7×77 \times 7 depthwise filter is local, leaving open how ultra-large depthwise kernels (Ding et al., 2022), deformable convolutions, and hybrid conv--attention stacks compare at frontier scale.

7.7.5 Summary#

Starting from a standard ResNet-50, ConvNeXt applied Swin-inspired upgrades one at a time: a 300-epoch modern recipe (+2.7 points), a 1:1:3:11{:}1{:}3{:}1 stage ratio, a 4×44 \times 4 stride-4 patchify stem, a 7×77 \times 7 depthwise convolution leading a 4×4\times inverted bottleneck, a single GELU and LayerNorm per block, layer scale, and separate 2×22 \times 2 stride-2 downsampling layers. Together these changes reach 82.0% on ImageNet without attention. On 64×6464 \times 64 Fashion-MNIST, ConvNeXt's body and LayerNorm match a parameter-matched ResNet-18 (~94%), while the coarse 4×44 \times 4 patchify stem costs ~2 points.

7.7.6 Exercises#

  1. Arithmetic of the depthwise move and kernel enlargement. In Table 7.7.1, just before the "Large kernels" row, each block expands c→4cc \to 4c with a 1×11 \times 1 convolution, filters the 4c4c channels with a 3×33 \times 3 depthwise convolution, and projects 4c→c4c \to c with a second 1×11 \times 1 convolution. The "Large kernels" step first moves the depthwise convolution to the front of the block (where it acts on cc channels instead of 4c4c) and then enlarges its kernel to 7×77 \times 7.

    1. Count the multiply-adds per spatial pixel of the depthwise layer before the move (3×33 \times 3 on 4c4c), after the move (3×33 \times 3 on cc), and after enlarging to 7×77 \times 7 on cc. Compare the net change against what enlarging to 7×77 \times 7 in place on 4c4c channels would have cost.
    2. What fraction of the full ConvNeXtBlock's multiply-adds per pixel (49c+8c249c + 8c^2) does the 7×77 \times 7 depthwise convolution account for at c=96c = 96 and at c=384c = 384?
  2. Where the parameters live in ConvNeXt.

    1. For the ConvNeXt model of this section (3,376,4503{,}376{,}450 parameters), compute the exact fraction of parameters in (i) the 7×77 \times 7 depthwise convolutions, (ii) the 1×11 \times 1 expansion and projection layers, (iii) the normalization and layer-scale vectors inside the blocks, (iv) the downsampling layers, and (v) the stem and head.
    2. Express the parameter count of a ConvNeXtBlock and a two-layer Residual block (Section 7.4, without a 1×11 \times 1 shortcut) as functions of width cc. By what asymptotic factor is ConvNeXtBlock more parameter-efficient for large cc, and which design choice accounts for that factor?
  3. [code] Layer scale versus stochastic depth. Under the roadmap recipe of Table 7.7.2, train ConvNeXt with layer-scale initialization γ0=10−6\gamma_0 = 10^{-6} (default), with γ0=1\gamma_0 = 1, and with layer scale removed altogether, and compare their training curves. Both layer scale at 10−610^{-6} and stochastic depth (Section 7.6) make a deep network effectively shallower at the start of training: contrast how each mechanism works, when during training it is active, and whether it alters the evaluation-time network.

  4. [code] Global Response Normalization (ConvNeXt V2). ConvNeXt V2 (Woo et al., 2023) removes layer scale and inserts Global Response Normalization (GRN) right after the GELU inside each block. For a feature map X\mathbf{X} with CC channels, let gc=∥Xc∥2g_c = \|\mathbf{X}_c\|_2 be the spatial ℓ2\ell_2 norm of channel cc and gˉ=1C∑c=1Cgc\bar{g} = \frac{1}{C}\sum_{c=1}^C g_c. GRN rescales each channel by its relative response with a learnable affine transform and residual:

GRN(X)c=γcgcgˉ+ϵXc+βc+Xc,(7.7.1)\mathrm{GRN}(\mathbf{X})_c = \gamma_c \frac{g_c}{\bar{g} + \epsilon} \mathbf{X}_c + \beta_c + \mathbf{X}_c, \tag{7.7.1}

where ϵ=10−6\epsilon = 10^{-6} and γ,β\boldsymbol{\gamma}, \boldsymbol{\beta} are initialized to zero so GRN begins as the identity. Implement GRN in a few lines of code, insert it into ConvNeXtBlock in place of layer scale, and compare validation accuracy under the roadmap recipe of Table 7.7.2.

  1. [code] Depthwise kernel size sweep. ● Under the recipe of Table 7.7.2, train ConvNeXt with 3×33 \times 3, 7×77 \times 7, and 11×1111 \times 11 depthwise kernels (padding 1, 3, and 5) and compare parameter counts, multiply-adds, wall-clock time per epoch, and validation accuracy. Why does the wall-clock time per epoch grow much faster from 7×77 \times 7 to 11×1111 \times 11 than the total multiply-add count would suggest?

  2. [code] 2×2 architecture-by-recipe ablation. ● The first and last rows of Table 7.7.2 compare CompactResNet18 and ModernConvNeXt under the modern AdamW/Mixup/smoothing recipe. Complete the 2×22 \times 2 ablation square by training both architectures under Recipe A of Section 7.6 (momentum SGD, step decay, no Mixup or label smoothing, retuning the peak learning rate). Does the modern training recipe boost both architectures equally?

Discussions