AI Logic

Architectures

ResNeXt

Updated:

Architecture of ResNeXt. The left side shows the overall flow of ResNeXt-50 (32×4d) (a 7×7 convolution and max pooling, four stages of ResNeXt blocks, global average pooling, and a fully connected layer) with the output shape of each stage. The right side shows the inside of a block: the form that sums 32 paths of the same shape, the same computation written as a group convolution, and a ResNet bottleneck for comparison.

Background and overview

ResNeXt is a convolutional neural network that replaces the bottleneck block of ResNet with a block that sums many thin paths of the same shape. It was published in 2016 by Xie and colleagues at UC San Diego and Facebook AI Research and accepted at CVPR 2017. It is the basis of the model that took second place in image classification at ILSVRC 2016.

The paper calls the number of parallel paths cardinality (the size of the set). Until then, the main ways to strengthen a network were to "go deeper (add layers)" or to "go wider (add channels)". ResNeXt showed that cardinality is a third design dimension alongside these, and that at the same computation, increasing cardinality improves accuracy more than increasing depth or width. The name stands for "the next dimension".

In implementation, the parallel paths are combined into a single group convolution. It only replaces the 3×3 convolution in ResNet's bottleneck with a wider group convolution, so the structure is almost the same as ResNet.

The main results of the paper are as follows.

  • On ImageNet, it lowered ResNet-50's top-1 error from 23.9% to 22.2% while keeping computation and parameter count the same (ResNeXt-50, 32×4d).
  • When doubling computation, increasing cardinality (ResNeXt-101, 20.4%) beat going deeper (ResNet-200, 21.7%) and going wider (ResNet-101, 21.3%).
  • On CIFAR-10/100 and COCO object detection, it also outperformed ResNets of similar size.

Theory: split, transform, and aggregate

The starting point of ResNeXt's idea is a single neuron in a fully connected or convolutional layer. A neuron computes a weighted sum of a DD-channel input x=[x1,…,xD]\mathbf{x} = [x_1, \ldots, x_D] (Eq. 1 of the paper).

∑i=1Dwixi\sum_{i=1}^{D} w_i x_i

The paper reinterprets this computation as the following three steps.

  1. Split: the input x\mathbf{x} is split into one-dimensional parts xix_i.
  2. Transform: each is transformed into wixiw_i x_i (here, a scalar multiplication).
  3. Aggregate: everything is summed.

ResNeXt replaces the "transform" in step 2 with a small network Ti\mathcal{T}_i (Eq. 2).

F(x)=∑i=1CTi(x)\mathcal{F}(\mathbf{x}) = \sum_{i=1}^{C} \mathcal{T}_i(\mathbf{x})

CC is the cardinality, the number of transformations summed. It sits in the same position as DD in Eq. 1, but need not equal DD and can be chosen freely. The paper gives all Ti\mathcal{T}_i the same shape (the same bottleneck as ResNet: a 1×1 convolution reduces to a low dimension, a 3×3 is applied, and a 1×1 restores the dimension). Using this as the residual function, the block's output is as follows (Eq. 3).

y=x+∑i=1CTi(x)\mathbf{y} = \mathbf{x} + \sum_{i=1}^{C} \mathcal{T}_i(\mathbf{x})

Three equivalent forms

As shown on the right of the figure at the top of the article, this block can be written in the following three ways, which compute exactly the same thing when BN and ReLU are placed correctly (Figure 3 of the paper).

  • (a) Summing paths: a 256-channel input passes through 32 paths (1×1 to 4 channels, 3×3 to 4 channels, 1×1 to 256 channels), and the outputs are summed.
  • (b) Early concatenation: the outputs of the 32 3×3s (4 channels each, 128 channels in total) are concatenated and then restored to 256 channels with a single 1×1 convolution. Summing the last 1×1 convolutions and applying one convolution after concatenation are the same computation.
  • (c) Group convolution: further, the first 1×1 convolutions of the 32 paths are merged into one 1×1 (128 channels), and the 3×3 becomes a group convolution with 32 groups.

The paper's implementation uses form (c). All three trained to the same results, and (c) was the most concise and the fastest. Form (c) is almost the same as ResNet's bottleneck; the only difference is that "the 3×3 layer is wider and split into groups with sparse connections".

Group convolution was originally a device that AlexNet used to split the model across two GPUs. According to the ResNeXt paper, there had been almost no use of group convolution to improve accuracy before. The special case where the number of groups equals the number of channels is channel-wise convolution (the first half of a depthwise separable convolution).

Difference from Inception

The modules of GoogLeNet (Inception) also follow a "split, transform, aggregate" form, but the filter sizes and counts are hand-crafted for each branch, and the modules are tuned stage by stage. ResNeXt gives all paths the same shape, so the number of paths can be studied as a single number, and fewer hyperparameters need tuning for new data.

Overall architecture and training setup

Following VGG and ResNet, ResNeXt stacks blocks of the same shape. The shape of the blocks is determined by the following two rules (Section 3.1 of the paper).

  • Blocks that output feature maps of the same size share the same width and filter sizes.
  • Each time the feature map's height and width are halved, the block width is doubled.

The second rule makes the computation (number of multiply-adds) of every block nearly the same. With these rules, only the "template" of the first stage needs to be designed, and a model can be described as "cardinality × width of one path". For example, a model whose template uses 32 paths of 4 channels each is written 32×4d.

Architecture of ResNeXt-50 (32×4d) (Table 1 of the paper; left side of the figure at the top of the article)

StageOutput sizeResNet-50 blockResNeXt-50 (32×4d) blockCount
conv1112×1127×7, 64, stride 2Same1
conv256×563×3 max pooling, stride 2Same1
56×561×1, 64 / 3×3, 64 / 1×1, 2561×1, 128 / 3×3, 128 (C=32C=32) / 1×1, 2563
conv328×281×1, 128 / 3×3, 128 / 1×1, 5121×1, 256 / 3×3, 256 (C=32C=32) / 1×1, 5124
conv414×141×1, 256 / 3×3, 256 / 1×1, 10241×1, 512 / 3×3, 512 (C=32C=32) / 1×1, 10246
conv57×71×1, 512 / 3×3, 512 / 1×1, 20481×1, 1024 / 3×3, 1024 (C=32C=32) / 1×1, 20483
1×1Global average pooling, 1000-class fully connected layer, softmaxSame1

The parameter count is 25.0 million versus ResNet-50's 25.5 million, and computation is 4.2 billion versus 4.1 billion operations, nearly the same.

Relationship between cardinality and width

To change cardinality while keeping computation the same, the width dd of each path is reduced. The parameter count of the conv2 template (256 input and output channels) is given by the following (Eq. 4).

C⋅(256⋅d+3⋅3⋅d⋅d+d⋅256)C \cdot (256 \cdot d + 3 \cdot 3 \cdot d \cdot d + d \cdot 256)

ResNet's bottleneck (C=1C = 1, d=64d = 64) has about 70K parameters, and C=32C = 32, d=4d = 4 also has nearly the same, about 70K. The combinations in Table 2 of the paper are as follows.

Cardinality CC124832
Width of one path dd644024144
Group convolution width (C×dC \times d)648096112128

Training setup (ImageNet, Section 4 of the paper)

ItemSetting
Data augmentation224×224 crops with random size and aspect ratio
ShortcutsIdentity; projection (1×1 convolution) only where the number of channels increases
Where height and width are halvedThe 3×3 convolution of the first block in conv3–5 (stride 2)
OptimizationSGD, mini-batch 256 (8 GPUs), momentum 0.9, Weight Decay 0.0001
Learning rateStarts at 0.1 and is divided by 10 three times
Weight initializationHe initialization
BN and activationBatch normalization right after each convolution, followed by ReLU. The last ReLU of a block comes after adding the shortcut
EvaluationResize the shorter side to 256 and take the center 224×224 crop

Why cardinality works

The paper explains why increasing cardinality improves accuracy as follows.

  • Representational power increases: in comparisons at matched computation, ResNeXt-50 (32×4d) had much lower error than ResNet-50 not only on validation data but also on training data. The paper takes this to mean that the model's representational power itself has increased, rather than overfitting being suppressed by regularization.
  • Paths of the same shape need little tuning: unlike Inception, there is no need to hand-craft each branch; simply increasing the number of paths as a single number is enough. The paper notes that having fewer hyperparameters to tune also reduces the risk of overfitting the design to specific data.
  • An effect separate from residual connections: comparing without shortcuts, ResNet-50 had an error of 31.2% and ResNeXt-50 had 26.1%. ResNeXt was better in both cases, and the paper separates the two effects: "residual connections help optimization, and aggregating paths strengthens representation".

Difference from ensembles

Because the outputs of multiple paths are summed, it looks similar to an ensemble that averages independently trained models. However, the paper notes that ResNeXt's paths are trained jointly, so calling it an ensemble is not accurate.

As an everyday analogy, ResNet's bottleneck is like "64 people holding one big meeting", while ResNeXt is like "forming 32 small teams of 4, letting each team discuss, and pooling the results at the end". The total number of people (computation) is the same, but each team can dig into a different perspective, which improves the quality of the conclusion.

This rewriting is meaningful only when the block has three or more layers (a bottleneck). Applied to ResNet's basic block of two stacked 3×3 convolutions, parallel paths simply become the same as an ordinary wide convolution (Figure 4 of the paper).

Experimental results

Varying cardinality at matched computation (ImageNet-1K, top-1 error % with a single 224×224 crop; Table 3 of the paper)

ModelSetting (C×dC \times d)Top-1 error
ResNet-501 × 64d23.9
ResNeXt-502 × 40d23.0
ResNeXt-504 × 24d22.6
ResNeXt-508 × 14d22.3
ResNeXt-5032 × 4d22.2
ResNet-1011 × 64d22.0
ResNeXt-1012 × 40d21.7
ResNeXt-1014 × 24d21.4
ResNeXt-1018 × 14d21.3
ResNeXt-10132 × 4d21.2

With computation held constant (about 4.1 billion operations for 50 layers and about 7.8 billion for 101 layers), the error dropped as cardinality increased. However, the improvement from 8×14d to 32×4d was a small 0.1 points, and the paper does not make the width of a path smaller than 4d.

Which dimension to grow when doubling computation (Table 4 of the paper)

ModelSettingTop-1Top-5
ResNet-101 (baseline)1 × 64d22.06.0
ResNeXt-101 (same computation as baseline)32 × 4d21.25.6
ResNet-200 (deeper)1 × 64d21.75.8
ResNet-101 (wider)1 × 100d21.35.7
ResNeXt-101 (2× cardinality)2 × 64d20.75.5
ResNeXt-101 (2× cardinality)64 × 4d20.45.3

Going deeper (0.3 points) or wider (0.7 points) gave small improvements, while increasing cardinality gave large ones. Even ResNeXt-101 (32×4d, 21.2%) with half the computation beats ResNet-200 and the wider ResNet-101.

Comparison with other models (ImageNet-1K validation data, single crop, %; Table 5 of the paper)

ModelTop-1 (224)Top-5 (224)Top-1 (320/299)Top-5 (320/299)
ResNet-20021.75.820.14.8
Inception-v3——21.25.6
Inception-v4——20.05.0
Inception-ResNet-v2——19.94.9
ResNeXt-101 (64×4d)20.45.319.14.4

ResNet and ResNeXt values use 320×320 crops, and Inception-family values use 299×299 crops. At ILSVRC 2016, an ensemble of multiple models achieved a top-5 error of 3.03% on the test data, taking second place (first place was 2.99%).

Results on other data

Data / taskResNetResNeXtSource
ImageNet-5K (5000 classes, top-1 error)45.5 (50 layers)42.3 (50 layers, 32×4d)Table 6
CIFAR-10 (error)Wide ResNet 4.17 (36.5M)3.58 (ResNeXt-29, 16×64d, 68.1M)Table 7
CIFAR-100 (error)Wide ResNet 20.5017.31 (same as above)Table 7
COCO object detection (AP, Faster R-CNN)26.5 (50 layers)27.5 (50 layers, 32×4d)Table 8

On CIFAR, even ResNeXt-29 (8×64d, 34.4M) outperformed Wide ResNet with a similar parameter count (3.65% on CIFAR-10). CIFAR values are averages over 10 runs. ResNeXt was later also used as the backbone of Mask R-CNN.

Practical considerations

Keep the following points in mind when using ResNeXt.

  • The same computation can still take more time: with the paper's implementation (Torch's built-in group convolution with no special optimization), on 8 M40 GPUs, training ResNeXt-101 (32×4d) took 0.95 seconds per mini-batch, about 35% slower than the 0.70 seconds of ResNet-101 with nearly the same computation. This depends on the efficiency of the group convolution implementation, so measure in your actual environment.
  • Do not make each path too thin: increasing cardinality at matched computation shrinks the width of each path, and the improvement plateaus. The paper uses widths of 4d or more.
  • The gap tends to widen with more data: at 101 layers, the difference in validation error on ImageNet-1K (0.8 points) was smaller than at 50 layers, but the difference in training error remained large. The paper reports that the gap widens with more data, as on ImageNet-5K.

When using group convolution in PyTorch, make both in_channels and out_channels of nn.Conv2d divisible by groups. ResNeXt's 3×3 layer uses groups=32, and its input and output channel counts (128 for conv2) are multiples of 32.

Comparison with other models

Comparing ResNeXt with other networks that innovate on the paths or convolutions inside their blocks, from the same perspectives:

Network3×3 convolution in the blockShape of pathsResidual connectionsMain dimension for scaling up
ResNetOrdinary convolution (one path)OneYesDepth
GoogLeNet (Inception)Convolutions of different sizes per branchDifferent per branch (hand-crafted)No (yes in Inception-ResNet)Branch design
ResNeXtGroup convolution (32 groups, etc.)All the same shapeYesCardinality
XceptionDepthwise convolution (split by the number of channels)Per channelYesMaximize the split
SENet (SE-ResNeXt)Same as ResNeXt + per-channel weightingAll the same shapeYesAdd channel weighting

The only difference from ResNet is making the bottleneck's 3×3 layer "wider and split into groups". As a result, it can replace ResNet almost directly wherever ResNet is used. Xception corresponds to the extreme form that increases the number of groups up to the number of channels, and ResNeXt uses a point in between. In the SENet paper, SE-ResNeXt-50, which adds SE blocks to ResNeXt, outperformed ResNeXt-101.

Guidelines for choosing:

  • To improve accuracy at the same computation as ResNet: replacing it with a ResNeXt of the same depth, such as ResNeXt-50 (32×4d), is easy. torchvision provides pretrained weights.
  • For even higher accuracy: SE-ResNeXt with SE blocks, or ResNeXt-101 (64×4d) with increased cardinality, are candidates.
  • When speed matters: group convolutions can be slow depending on the environment, so compare against a ResNet of the same computation by actual measurement before choosing.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision.models import resnext50_32x4d, ResNeXt50_32X4D_Weights

"""
1. Build a ResNeXt block as in Figure 3(c) of the paper (1×1 → 3×3 group convolution → 1×1, then add the identity)
2. Classify an image with torchvision's pretrained ResNeXt-50 (32×4d)
"""


class ResNeXtBlock(nn.Module):
  def __init__(self, in_ch, out_ch, cardinality=32, width=4, stride=1):
    super().__init__()
    inner = cardinality * width                          # group convolution width (32 × 4 = 128 for conv2)
    self.body = nn.Sequential(
      nn.Conv2d(in_ch, inner, 1, bias=False), nn.BatchNorm2d(inner), nn.ReLU(inplace=True),
      nn.Conv2d(inner, inner, 3, stride=stride, padding=1, groups=cardinality, bias=False),   # the 3×3s of the 32 paths combined
      nn.BatchNorm2d(inner), nn.ReLU(inplace=True),
      nn.Conv2d(inner, out_ch, 1, bias=False), nn.BatchNorm2d(out_ch),                    # corresponds to the sum of the 32 outputs (Eq. (2))
    )
    self.shortcut = nn.Identity()
    if stride != 1 or in_ch != out_ch:                   # project only when the shape changes
      self.shortcut = nn.Sequential(nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False), nn.BatchNorm2d(out_ch))

  def forward(self, x):
    return F.relu(self.shortcut(x) + self.body(x))      # Eq. (3): y = x + Σ T_i(x), ReLU after the addition


block = ResNeXtBlock(256, 256)                           # conv2 template (32×4d, 256 ch in and out)
resnet_like = ResNeXtBlock(256, 256, cardinality=1, width=64)   # ResNet bottleneck (1×64d)
count = lambda m: sum(p.numel() for n, p in m.named_parameters() if "body" in n and p.dim() == 4)
print(count(block), count(resnet_like))                 # both have about 70K convolution weights (Eq. (4))

block.train()                                            # BN uses mini-batch statistics
y = block(torch.randn(4, 256, 56, 56))
print(y.shape)                                           # [4, 256, 56, 56]

# --- torchvision's pretrained ResNeXt-50 (32×4d) ---
weights = ResNeXt50_32X4D_Weights.IMAGENET1K_V1
net = resnext50_32x4d(weights=weights)
net.eval()                                               # BN uses the mean and variance accumulated during training
preprocess = weights.transforms()
image = Image.open("cat.jpg").convert("RGB")
with torch.no_grad():
  probs = net(preprocess(image).unsqueeze(0)).softmax(dim=1)   # [1, 1000]
print(weights.meta["categories"][probs.argmax().item()])

FAQ

Q. What is the difference between ResNeXt and ResNet?
A.

The 3×3 convolution in the bottleneck block differs. ResNet uses an ordinary 64-channel 3×3 convolution, while ResNeXt uses a group convolution widened to 128 channels and split into 32 groups. This is the same computation as summing 32 thin paths of 4 channels each. With nearly the same parameter count and computation, the ImageNet top-1 error dropped from 23.9% to 22.2% (50 layers).

Q. What does 32×4d mean?
A.

It means a cardinality (number of parallel paths) of 32 and a width of one path (number of bottleneck channels) of 4. It describes the template of the first stage (conv2); since the width doubles each time the height and width are halved in later stages, the later stages correspond to 32×8d, 32×16d, and 32×32d. Written as a group convolution, the 3×3 layer is 32×4=12832 \times 4 = 128 channels wide, split into 32 groups.

Q. What cardinality should I use?
A.

The paper commonly uses 32. Increasing it through 1, 2, 4, 8, and 32 at matched computation kept lowering the error, but the improvement from 8 to 32 was a small 0.1 points, and it plateaus once each path becomes too thin. The paper keeps the width of each path at 4 or more. If computation can be increased, doubling cardinality while keeping the width (32×4d → 64×4d) was more effective than going deeper or wider.

References

  1. Xie, S., Girshick, R., Dollár, P., Tu, Z., & He, K. (2017). Aggregated Residual Transformations for Deep Neural Networks. CVPR 2017. arXiv:1611.05431.
  2. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  3. Official implementation (Torch) and pretrained models: facebookresearch/ResNeXt.
  4. PyTorch. torchvision/models/resnet.py (source code; resnext50_32x4d and others).