ConvNeXt: Modernizing a ResNet Step by Step

Dive into Deep Learning · §7.7

ConvNeXt: Modernizing a ResNet Step by Step
controlled ablation vs. Swin-T · 7\times 7 depthwise + 4\times inverted bottleneck · single GELU/LayerNorm · patchify stem pitfall

Did Self-Attention Make Convnets Obsolete in 2021?

Motivation & The Swin-T Challenge

  • The 2021 Swin-T challenge: Swin-T (4.5\textrm{G} MACs) hit 81.3\% ImageNet top-1 vs. 76.1\% for 2015 ResNet-50.
  • Confounded variables: Swin-T also changed the 300-epoch AdamW recipe, stage ratio, stem, bottleneck geometry, and normalizer.
  • ConvNeXt (Liu et al., 2022): Modernizing ResNet-50 step-by-step reaches 82.0\% with zero attention layers.

The Eleven-Step ConvNeXt Modernization Roadmap

Cumulative ImageNet Ablation

  • Step 1 — 300-ep Modern Recipe (+2.7%): Lifts untouched ResNet-50 from 76.1\% \to 78.8\% (46% of the total gain).
  • Steps 2–6 — Macro & 7 \times 7 InvBot (+1.8%): (3,3,9,3) stages, 4 \times 4_{s4} patchify stem, depthwise 7 \times 7 at front of 4\times inverted bottleneck (80.6\%).
  • Steps 7–11 — Micro Hygiene (+1.4%): 1 GELU, 1 LayerNorm, layer scale, and separate 2 \times 2_{s2} downsamplers (82.0\%).

Macro Design: Recipe, 1:1:3:1 Stages & Patchify Stem

Steps 1–3: Macro Structure

  • Stage ratio (3,4,6,3) \to (3,3,9,3) (+0.6%): Concentrates 50% of blocks in Stage 3 (14 \times 14 resolution).
  • Patchify stem (+0.1% on 224^2): Replaces overlapping 7 \times 7_{s2} + MaxPool with a non-overlapping 4 \times 4 stride-4 conv (identical to ViT patch embedding, though too coarse for 64 \times 64 thumbnails).

Block Geometry: Depthwise + 1×1 Mirrors Transformers

Steps 4–6: Factorization & 7×7 Kernels

  • Move depthwise conv to the front: Placing \textrm{DWConv}_{7\times 7} before the c \to 4c expansion filters c channels instead of 4c (49c vs. 196c MACs/pixel).
  • Large spatial kernel for <6\% of block MACs: Total block compute is 49c + 8c^2 per pixel; at c=96, the 7 \times 7 spatial filter is only 6.0\% of block MACs (1.6\% at c=384).

Micro Design: Why Fewer Activations and Norms Win

Steps 7–11: Block Hygiene

Comparing a ResNet-50 bottleneck against the resulting ConvNeXt block highlights how stripping away redundant activations and normalizations boosted accuracy by +1.4 points:

  • One GELU per block (+0.7\%): Classic ResNet puts ReLU after every conv (3 per block). Keeping only a single GELU between the two 1\times 1 layers (just like a Transformer MLP) yields the largest micro-design jump on the roadmap.
  • One LayerNorm per block (+0.2\%): Keeps a single per-pixel channel LayerNorm right after the 7\times 7 depthwise conv.
  • Layer scale \boldsymbol{\gamma} \in \mathbb{R}^c (init 10^{-6}): Multiplies the residual branch before addition so deep blocks start near the identity.

Separate Downsampling Layers and the Full ConvNeXt-T

Full Backbone Topology

Whereas ResNet downsamples inside the first residual block of each stage via a stride-2 conv, ConvNeXt places dedicated \textrm{LayerNorm} + 2\times 2\text{ stride-2 conv} patch-merging layers between stages (+0.5\%):

  • Zero pooling in the body: Downsampling is handled entirely by non-overlapping stride-4 (4\times 4 stem) and stride-2 (2\times 2 inter-stage) convolutions.
  • Stabilizing normalizations: Adding LayerNorm before each 2\times 2 stride-2 downsampling conv, after the stem, and after global average pooling prevents activation scale spikes when spatial tokens merge.
  • Final ImageNet score: 82.0% (82.1% with tuned EMA), beating Swin-T’s 81.3% at equal FLOPs and higher throughput.

Implementing the ConvNeXt Block

Code Implementation

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)

Assembling the Full ConvNeXt Class

Backbone Implementation

ConvNeXt downsamples between stages and ramps drop-path linearly across blocks:

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)

Verifying ConvNeXt-Atto Shapes and Parameter Count

Sanity Check: 3,376,450 Parameters

model = ConvNeXt()
assert model(torch.randn(1, 1, 64, 64)).shape == (1, 10)
d2l.num_params(model)
3376450
  • Compact Atto pyramid: Depths (2, 2, 6, 2) and widths (40, 80, 160, 320) total 3.38\textrm{M} parameters (1/3 of ResNet-18).

The Shared ModernRecipe Mixin for Fair Ablation

Controlled Training Protocol

ModernRecipe fixes the optimizer and regularization for every roadmap step:

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

Controlled Three-Step Ablation on 64×64 Fashion-MNIST

Local Modernization Roadmap

With ModernRecipe fixed, three steps turn a parameter-matched CompactResNet18 into ConvNeXt:

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}

When ImageNet Design Choices Hurt Small-Image Tasks

Ablation Results & Resolution Pitfall

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
  • Body + LN tie at \approx 94.0\%: Matches CompactResNet18 when keeping the overlapping stem.
  • Patchify pitfall (\approx -2 points): Non-overlapping 4 \times 4_{s4} stem is too coarse on 64 \times 64 thumbnails.

Frontiers: Masked Pretraining & Global Response Norm

ConvNeXt V2 & Open Questions

\textrm{GRN}(\mathbf{X})_c = \gamma_c \frac{g_c}{\bar{g} + \epsilon}\mathbf{X}_c + \beta_c + \mathbf{X}_c

  • Sparse MAE pretraining: Submanifold sparse convs prevent masked zero-bleeding.
  • Global Response Norm (GRN): Normalizes channel L2 norms g_c = \|\mathbf{X}_c\|_2 against layer mean \bar{g} to prevent dead/collapsed channels.

Concept Check: Block FLOPs, Parameters & Layer Scale

Concept Check

  • 1. Block MAC split (c=96): 7 \times 7 depthwise costs 49c = 4{,}704 MACs/px (only 6.0%) vs. 8c^2 = 73{,}728 for the two 1 \times 1 layers.
  • 2. Why move DW to front: Filtering c channels instead of 4c saves 4\times (49c vs. 196c).
  • 3. LayerScale vs. DropPath: LayerScale (\gamma_0 = 10^{-6}) is a deterministic multiplier kept at eval; DropPath is a random gate turned off (b \equiv 1) at eval.

Summary: Key Takeaways from ConvNeXt

Summary

Design Dimension Classic ResNet-50 (2015) Modernized ConvNeXt-T (2022) ImageNet Impact & Principle
Training recipe 90 ep, SGD + step decay, crops/flips 300 ep, AdamW, Mixup/CutMix, smoothing, EMA +2.7\% (76.1\% \to 78.8\%); accounts for nearly half the ViT gap
Stage ratio & stem (3, 4, 6, 3) stages; 7\times 7_{s2} + max-pool (3, 3, 9, 3) stages; 4\times 4_{s4} patchify conv +0.7\% on 224^2 ImageNet (but 4\times 4_{s4} loses \approx 2\% on 64^2 thumbnails)
Spatial vs. channel mixing Dense 3\times 3 inside 4\times compressed bottleneck Front 7\times 7 depthwise conv + 4\times inverted bottleneck +1.1\%; 49c depthwise cost is <6\% of 8c^2 pointwise MLP cost
Activations & norms 3 ReLUs and 3 BatchNorms per block 1 GELU and 1 per-pixel LayerNorm per block +0.9\%; removing 2 nonlinearities per block gives +0.7\% alone
Downsampling & scaling Stride-2 conv inside block 1 of stage Separate \textrm{LN} + 2\times 2_{s2} conv; layer scale \boldsymbol{\gamma}=10^{-6} +0.6\% (reaching 82.0\% vs. Swin-T’s 81.3\% without attention)