AI Logic

Architectures

ConvNeXt

Updated:

Structure of ConvNeXt. Left: the overall flow of ConvNeXt-T (a 4×4 convolution patchify stem, 4 stages with 3, 3, 9, and 3 blocks and downsampling layers between them, global average pooling, and a fully connected layer). Right: inside the block (7×7 depthwise convolution, layer normalization, 1×1 convolutions 96→384→96, GELU, LayerScale, residual connection), with a ResNet-50 bottleneck block for comparison

Background and overview

ConvNeXt is an image recognition model built entirely from convolutions, created by "modernizing" a standard ResNet step by step toward the design of vision Transformers. It was presented in "A ConvNet for the 2020s" by Liu et al. of Meta (Facebook AI Research) and UC Berkeley in 2022. Without using any attention, it matched or exceeded the accuracy of Swin Transformer at roughly the same compute.

After ViT appeared in 2020, the leading role in image recognition was shifting from convolutional neural networks (CNNs) to Transformers. In particular, Swin Transformer, which computes attention only within windows, outperformed CNNs not only in classification but also in object detection and segmentation, and Transformers were believed to be "inherently superior."

The ConvNeXt paper examined whether this gap was really due to attention. Besides attention, CNNs and Transformers also differ in how they are trained (optimization, data augmentation, regularization) and in fine-grained network design (stage ratios, kernel size, activation, normalization, and so on). The paper introduced these into ResNet-50 one at a time and recorded how the accuracy changed.

The main results of the paper are:

  • Simply aligning the training recipe with that of ViT-style models (DeiT, Swin) raised ResNet-50's ImageNet accuracy from 76.1% to 78.8%.
  • Changing the design step by step reached 82.0%, surpassing the 81.3% of Swin-T at the same compute (4.5 GFLOPs).
  • The largest model, ConvNeXt-XL, pre-trained on ImageNet-22K, reached 87.8% on ImageNet. On COCO object detection and ADE20K segmentation, it also matched or exceeded Swin Transformer.

ConvNeXt contains almost no new components. The paper itself notes that each design choice it used had been studied individually in CNN research over the past decade, and that what is new is testing them "collectively."

Theory: modernizing ResNet step by step

ConvNeXt was built by starting from ResNet-50 and moving it toward the design of Swin-T (about 4.5 GFLOPs) one change at a time. The accuracy at each stage is the average of 3 training runs on ImageNet-1K with different random seeds (Figure 2 and Table 10 of the paper).

The steps are as follows:

  1. Change the training recipe: extend training from 90 to 300 epochs and use AdamW, Mixup, CutMix, RandAugment, Random Erasing, Stochastic Depth, and Label Smoothing. The architecture remains ResNet-50.
  2. Change the stage ratio: change the number of blocks in the 4 stages from (3, 4, 6, 3) to (3, 3, 9, 3), the same 1:1:3:1 ratio as Swin-T.
  3. Patchify the stem: instead of a 7×7, stride-2 convolution followed by max pooling, use a non-overlapping 4×4, stride-4 convolution that cuts the image into 4×4 patches (the same idea as ViT's patchify).
  4. Use depthwise convolution and widen: replace the 3×3 convolution in the bottleneck with a depthwise convolution (each channel convolved separately; a grouped convolution whose number of groups equals the number of channels), and use the saved compute to widen the channels from 64 to 96 (the idea of ResNeXt).
  5. Invert the bottleneck: instead of a bottleneck that narrows the middle, widen the middle to 4 times the input, as in MobileNetV2 and the Transformer MLP.
  6. Move the depthwise convolution to the top of the block and enlarge the kernel to 7×7: following the Transformer, where attention comes before the MLP, the heavy spatial processing is placed at the start, where there are fewer channels. The kernel is then enlarged from 3 to 7.
  7. Match the details to the Transformer: replace ReLU with GELU, keep only one activation and one normalization per block, and replace batch normalization with layer normalization.
  8. Make downsampling a separate layer: instead of halving the height and width in the first block of each stage, place a 2×2, stride-2 convolution between stages. To stabilize training, layer normalization is also placed before it, after the stem, and after the final global average pooling.

The ImageNet-1K accuracy at each stage is as follows (Table 10 of the paper, for the ResNet-50 compute regime).

StepAccuracy (%)GFLOPs
ResNet-50 (original training)76.134.09
ResNet-50 (modernized training recipe)78.824.09
Change stage ratio79.364.53
Patchify stem79.514.42
Depthwise convolution78.282.35
Widen to 9680.505.27
Inverted bottleneck80.644.64
Move depthwise convolution up79.924.07
7×7 kernel80.574.15
ReLU → GELU80.624.15
Fewer activations (one)81.274.15
Fewer normalizations81.414.15
Batch norm → layer norm81.474.46
Separate downsampling layers (ConvNeXt-T)81.974.49
Swin-T (reference)81.304.50

Kernels of 5, 9, and 11 were also tried, but the benefit saturated at 7×7 (80.47% at 11×11). Also, simply making downsampling a separate layer caused training to diverge; it became stable only after adding the layer normalizations mentioned above.

Overall architecture

Like ResNet, ConvNeXt is a hierarchical CNN that reduces the height and width while increasing the channels over 4 stages. In the figure at the top of the article, the left shows the overall flow of ConvNeXt-T, and the right shows the inside of the block along with a ResNet bottleneck block for comparison.

An image flows in the following order (ConvNeXt-T with a 224×224 input; Table 9 of the paper):

  1. Stem (patchify): a 4×4, stride-4 convolution produces 96 channels, followed by layer normalization. The spatial size becomes 56×56.
  2. 4 stages: each stage stacks (3, 3, 9, 3) ConvNeXt blocks. The channels double at each stage (96, 192, 384, 768), and the spatial size halves (56, 28, 14, 7).
  3. Downsampling layers: between stages, layer normalization followed by a 2×2, stride-2 convolution halves the spatial size and doubles the channels.
  4. Output: global average pooling produces a 768-dimensional vector, which is layer-normalized and classified by a fully connected layer.

ConvNeXt block

With input xx (with CC channels), the output of the block is:

y=x+γ⊙W2 GELU(W1 LN(DWConv7×7(x)))y = x + \gamma \odot W_2\,\mathrm{GELU}\bigl(W_1\,\mathrm{LN}(\mathrm{DWConv}_{7\times 7}(x))\bigr)

Here, DWConv7×7\mathrm{DWConv}_{7\times 7} is a 7×7 depthwise convolution, LN is layer normalization, and W1W_1 (C→4CC \to 4C) and W2W_2 (4C→C4C \to C) are 1×1 convolutions (per-pixel fully connected layers). γ\gamma is the per-channel learned scale of LayerScale, initialized to 10−610^{-6} (training settings in Section 3.1 of the paper).

The differences from a ResNet bottleneck block are as follows (Figure 4 of the paper).

AspectResNet-50 bottleneckConvNeXt block
Spatial mixing convolution3×3, mixes all channels7×7, per channel (depthwise)
Channel width256 → 64 → 256 (narrow middle)96 → 384 → 96 (4× middle)
Position of spatial convolutionMiddleStart
Activation3 ReLUs1 GELU
Normalization3 batch norms1 layer norm

This block closely resembles a Transformer block. The depthwise convolution mixes only along the spatial dimensions (the role of attention), and the two 1×1 layers mix only along the channel dimension (the role of the MLP).

Model sizes

Models of different sizes differ only in the number of channels CC and the number of blocks BB in each stage (Section 3 of the paper).

ModelChannels CCBlocks BBParametersGFLOPs (224×224)
ConvNeXt-T(96, 192, 384, 768)(3, 3, 9, 3)29M4.5
ConvNeXt-S(96, 192, 384, 768)(3, 3, 27, 3)50M8.7
ConvNeXt-B(128, 256, 512, 1024)(3, 3, 27, 3)89M15.4
ConvNeXt-L(192, 384, 768, 1536)(3, 3, 27, 3)198M34.4
ConvNeXt-XL(256, 512, 1024, 2048)(3, 3, 27, 3)350M60.9

A 1×1 convolution is the same computation as applying the same fully connected layer to every pixel. The official implementation also permutes the tensor to (height, width, channel) order inside the block and computes the layer normalization and the two 1×1 convolutions with nn.LayerNorm and nn.Linear.

Why a CNN can catch up with Transformers

Three main reasons can be read from the paper's results:

  • Much of the gap was the training recipe: aligning only the training recipe with ViT-style models, without changing the architecture, raised ResNet-50 by 2.7 points. That is roughly half of the total gain from ResNet-50 to ConvNeXt-T (about 5.8 points). Comparisons between CNNs and Transformers had thus mixed architectural differences with differences in training.
  • Mixing space and channels separately: the combination of depthwise and 1×1 convolutions mixes the spatial and channel dimensions separately. The paper points out that this is the same property as Transformers, which alternate attention and MLP layers. Because depthwise convolution is cheap, the saved compute can be used to widen the channels.
  • Seeing a wide area at once: Swin Transformer's windows are 7×7 or larger, covering a much wider area at once than ResNet's 3×3. ConvNeXt also enlarged its kernels to 7×7 to see a comparable area.

At the same time, ConvNeXt retains the properties of convolution as they are: looking at nearby pixels (locality) and producing the same features even when an object shifts position (translation equivariance). The paper states that ConvNeXt and Swin have a better compute-accuracy trade-off than ViT because both perform this local computation, not because of attention itself.

As an everyday analogy: when an old car model (ResNet) was compared with a new one (Transformer), the difference turned out to lie less in the engine than in the tires and fuel (training recipe) and small parts. Keeping the engine (convolution) and updating everything else made it run just as fast.

Experimental results

ImageNet-1K classification (top-1 accuracy %; throughput in images per second on a V100; Table 1 of the paper)

ModelResolutionParametersGFLOPsThroughputImageNet-1K onlyPre-trained on ImageNet-22K
Swin-T22428M4.5757.981.3—
ConvNeXt-T22429M4.5774.782.182.9
Swin-S22450M8.7436.783.0—
ConvNeXt-S22450M8.7447.183.184.6
Swin-B22488M15.4286.683.585.2
ConvNeXt-B22489M15.4292.183.885.8
Swin-B38488M47.185.184.586.4
ConvNeXt-B38489M45.095.785.186.8
Swin-L384197M103.946.0—87.3
ConvNeXt-L384198M101.050.485.587.5
ConvNeXt-XL384350M179.030.2—87.8

At similar compute, ConvNeXt matches or exceeds Swin Transformer at every size, with slightly higher throughput. Against the view that "Transformers, with fewer inductive biases, scale better with large-scale pre-training," ConvNeXt pre-trained on ImageNet-22K also matched or exceeded Swin. Measured on A100 GPUs, ConvNeXt's throughput was up to 49% higher than Swin at the same compute (Table 12 of the paper).

Object detection and instance segmentation (COCO, Cascade Mask R-CNN, 3× schedule; Table 3 of the paper)

BackbonePre-trainingBox APMask AP
ResNet-50ImageNet-1K46.340.1
Swin-TImageNet-1K50.443.7
ConvNeXt-TImageNet-1K50.443.7
Swin-BImageNet-22K53.045.8
ConvNeXt-BImageNet-22K54.046.9
ConvNeXt-XLImageNet-22K55.247.7

For semantic segmentation (ADE20K, UperNet, multi-scale mIoU; Table 4 of the paper), ConvNeXt-T scored 46.7 against Swin-T's 45.8, and ConvNeXt-L scored 53.7 against 53.5 for Swin-L pre-trained on ImageNet-22K.

Isotropic form like ViT (Table 2 of the paper): even a ConvNeXt that stacks the same blocks at 14×14 without downsampling reached 79.7%, 82.0%, and 82.6% with the same parameter counts as ViT-S, B, and L, almost the same as ViT (79.8%, 81.8%, 82.6%).

Practical notes

When using ConvNeXt, keep the following points in mind:

  • Use the paper's training recipe as a set: the paper's accuracy comes from combining AdamW (learning rate 4e-3, weight decay 0.05, batch size 4096), 300 epochs, 20 epochs of warmup with cosine decay, strong data augmentation, Stochastic Depth (0.1 for ConvNeXt-T), Label Smoothing 0.1, LayerScale, and an exponential moving average (EMA) of the weights (Table 5 of the paper).
  • Apply layer normalization along the channel dimension: applying nn.LayerNorm directly to an image tensor (batch, channel, height, width) normalizes over the wrong axes. Either permute the channels to the last position as the official implementation does, or use a layer that normalizes only over the channel dimension.
  • Depthwise convolution can be slow relative to its FLOPs: the paper also notes that, at the same FLOPs, models using depthwise convolution are known to be slower and to use more memory. Even so, ConvNeXt's inference throughput matched or exceeded Swin's. Measuring the actual speed on the GPU you use is the reliable approach.
  • Changing the resolution is easy: because ConvNeXt is fully convolutional, it can be fine-tuned at a different resolution without interpolating position embeddings or relative position biases as ViT and Swin require (Section 3.1 of the paper).

Nearly half of the comparison "ConvNeXt is almost 6 points higher than ResNet" comes from the difference in training recipes. When comparing with your own ResNet, compare against a ResNet trained with the same recipe. In the paper as well, ResNet-50 with the modernized recipe reaches 78.8%, 2.7 points above the original 76.1%.

Comparison with other models

ConvNeXt keeps a CNN architecture while adopting Transformer design choices. Comparing from the same angles gives the following:

ModelSpatial mixingStructureNormalization / activationGood for
ResNetStandard 3×3 convolution4-stage hierarchyBatch norm / ReLUA light, reliable baseline
ConvNeXt7×7 depthwise convolution4-stage hierarchyLayer norm / GELUBackbone for classification, detection, segmentation
Swin TransformerAttention within shifted windows4-stage hierarchyLayer norm / GELUBackbone for classification, detection, segmentation
ViTGlobal attentionConstant size throughoutLayer norm / GELULarge-scale pre-training, combination with other modalities

Rough guidelines for choosing:

  • A backbone for detection or segmentation is needed: ConvNeXt matches or exceeds Swin in accuracy and is simple to implement, with no special components (shifted windows, relative position biases).
  • Attention is needed, e.g. to combine images with text: the paper itself notes as a limitation that Transformers may be more flexible for combining with other modalities or for tasks requiring structured outputs. Consider ViT-style models.
  • Compute is limited or the model runs on a smartphone: also compare light CNNs such as MobileNetV2 and EfficientNet. The smallest ConvNeXt is ConvNeXt-T (4.5 GFLOPs).

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.models import convnext_tiny, ConvNeXt_Tiny_Weights

"""
An example of classification with torchvision's pre-trained ConvNeXt-T,
and a hand-written version of the block in Figure 4 of the paper
"""

weights = ConvNeXt_Tiny_Weights.IMAGENET1K_V1
model = convnext_tiny(weights=weights)
model.eval()                                   # disable Stochastic Depth
preprocess = weights.transforms()              # preprocessing matched to the weights


class ConvNeXtBlock(nn.Module):
  """7×7 depthwise conv -> LN -> 1×1 (C->4C) -> GELU -> 1×1 (4C->C) -> LayerScale -> add input"""

  def __init__(self, dim, layer_scale_init=1e-6, drop_path=0.0):
    super().__init__()
    self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)  # groups=dim makes it depthwise
    self.norm = nn.LayerNorm(dim, eps=1e-6)        # applied after moving channels last
    self.pwconv1 = nn.Linear(dim, 4 * dim)         # 1×1 conv = per-pixel fully connected layer
    self.act = nn.GELU()
    self.pwconv2 = nn.Linear(4 * dim, dim)
    self.gamma = nn.Parameter(layer_scale_init * torch.ones(dim))  # LayerScale
    self.drop_path = drop_path

  def forward(self, x):                          # x: [B, C, H, W]
    shortcut = x
    x = self.dwconv(x)
    x = x.permute(0, 2, 3, 1)                    # [B, H, W, C]
    x = self.pwconv2(self.act(self.pwconv1(self.norm(x))))
    x = self.gamma * x
    x = x.permute(0, 3, 1, 2)                    # back to [B, C, H, W]
    if self.training and self.drop_path > 0:     # Stochastic Depth: skip the block per sample, only during training
      keep = 1 - self.drop_path
      mask = x.new_empty(x.shape[0], 1, 1, 1).bernoulli_(keep)
      x = x * mask / keep
    return shortcut + x


block = ConvNeXtBlock(96, drop_path=0.1)
y = block(torch.randn(2, 96, 56, 56))           # shape unchanged: [2, 96, 56, 56]

FAQ

Q. Is ConvNeXt a Transformer?
A.

No. ConvNeXt is a purely convolutional model that uses no attention. What it borrows from Transformers are design ideas: the inverted bottleneck (widening the middle 4×), GELU, layer normalization, the patchify stem, and the training recipe.

Q. Why was the kernel set to 7×7?
A.

Because when the paper tried 3, 5, 7, 9, and 11, accuracy rose from 79.9% at 3×3 to 80.6% at 7×7 and did not improve with larger kernels. A 7×7 kernel sees about the same area at once as a Swin Transformer window (7×7). Because depthwise convolution is cheap, enlarging the kernel barely increases compute.

Q. What is the biggest difference between ConvNeXt and ResNet?
A.

The shape of the block. ResNet places a standard 3×3 convolution inside a narrow bottleneck, whereas ConvNeXt places a 7×7 depthwise convolution at the start and then mixes channels with two 1×1 layers whose middle is widened 4×. It also reduces activations and normalizations to one each.

References

  1. Liu, Z., Mao, H., Wu, C.-Y., Feichtenhofer, C., Darrell, T., & Xie, S. (2022). A ConvNet for the 2020s. CVPR 2022. arXiv:2201.03545.
  2. facebookresearch/ConvNeXt (official implementation).
  3. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  4. Liu, Z., et al. (2021). Swin Transformer: Hierarchical Vision Transformer using Shifted Windows. ICCV 2021. arXiv:2103.14030.
  5. PyTorch. torchvision.models.convnext_tiny (ConvNeXt_Tiny_Weights).