AI Logic

Architectures

X3D

Updated:

X3D architecture. Left: the overall flow of X3D-M (16 frames sampled every 5 frames pass through a spatial conv1 and a channel-wise temporal convolution, then 3, 5, 11, and 7 3D residual blocks in res2 to res5, and are classified by conv5, global average pooling, and two fully connected layers; the temporal dimension is never reduced). Right: inside a residual block (expand with 1×1², a 3×3² channel-wise 3D convolution, SE in every other block, project back with 1×1², and add the residual), and the six expansion axes (frame interval, frame count, spatial resolution, overall width, bottleneck width, depth) with their per-step factors and values from X2D to X3D-M

Background and overview

X3D (Expand 3D) is a family of lightweight video recognition networks built by starting from a tiny 2D network that looks at a single image (X2D) and expanding six axes of time, space, width, and depth, one axis per step. It was presented by Feichtenhofer of Facebook AI Research (FAIR) at CVPR 2020. Sizes from X3D-XS to X3D-XXL can be chosen to fit a compute budget.

Most earlier video networks were built by extending image classification networks (ResNet, Inception, and others) along the time axis (C3D, I3D, SlowFast, and others). Even when the temporal axis was carefully designed, depth, width, and resolution were usually inherited unchanged from the image network. The paper argues that this is not necessarily optimal in terms of the trade-off between compute and accuracy, and poses the following questions:

  • Is it better to look sparsely over a long interval or densely over a short one?
  • How far can spatial resolution be raised before gains saturate?
  • Is it better to look slowly with a wide network or at a high frame rate with a thin one?
  • When widening, should the whole network be widened, or only the inside of the blocks?

Instead of having people decide these, X3D answers them by training models that each expand one of the six axes per expansion step, comparing them, and choosing the best axis.

The main results of the paper are as follows:

  • On Kinetics-400, X3D-XL reaches 79.1% top-1. That is only 0.7 points below SlowFast (16×8, R101+Non-local) at 79.8%, with 4.8 times less compute and 5.5 times fewer parameters.
  • The expansion to the smallest model, X3D-XS, required training only 30 small models.
  • As the most surprising finding, the paper highlights that "networks with high spatiotemporal resolution and very thin width (channels)" work well. This is close to the design of the Fast pathway in SlowFast.

Architecture

The base network X2D (Section 3.1, Table 1)

X2D, the starting point of X3D, combines the stage layout of ResNet with the channel-wise convolutions of MobileNet (the first half of a depthwise separable convolution). When all expansion factors are 1, it takes only a single 112 × 112 image as input, so it is the same as an image classification network. It costs just 20.67M FLOPs (multiply-add pairs) and has only 1.63M parameters.

StageFilters (time × space², channels)Output size (time × space²)
Data layerSample frames with interval γτ\gamma_\tau1γt×(112γs)21\gamma_t \times (112\gamma_s)^2
conv11×321 \times 3^2 and 3×13 \times 1 (channel-wise), 24γw24\gamma_w1γt×(56γs)21\gamma_t \times (56\gamma_s)^2
res2[1×12,24γbγw; 3×32,24γbγw; 1×12,24γw]×γd[1 \times 1^2, 24\gamma_b\gamma_w;\ 3 \times 3^2, 24\gamma_b\gamma_w;\ 1 \times 1^2, 24\gamma_w] \times \gamma_d1γt×(28γs)21\gamma_t \times (28\gamma_s)^2
res3Same form with width 48, ×2γd\times 2\gamma_d1γt×(14γs)21\gamma_t \times (14\gamma_s)^2
res4Same form with width 96, ×5γd\times 5\gamma_d1γt×(7γs)21\gamma_t \times (7\gamma_s)^2
res5Same form with width 192, ×3γd\times 3\gamma_d1γt×(4γs)21\gamma_t \times (4\gamma_s)^2
conv51×121 \times 1^2, 192γbγw192\gamma_b\gamma_w1γt×(4γs)21\gamma_t \times (4\gamma_s)^2
pool5 → fc1 → fc2Global average pooling → 1×121 \times 1^2, 2048 → number of classes1×1×11 \times 1 \times 1

The design has four key points:

  1. 3D convolutions inside the residual blocks are channel-wise: The central 3×323 \times 3^2 convolution of the bottleneck is a channel-wise 3D convolution that does not mix channels. Channels are mixed by the 1×121 \times 1^2 convolutions before and after it.
  2. No temporal downsampling: As in both pathways of SlowFast, neither temporal pooling nor temporal stride is used. All frames are kept in the features until the final global average pooling.
  3. Width is thin, following the Fast pathway: conv1 outputs 24 channels, and the width doubles each time a stage halves the spatial size.
  4. Mobile components: The SE block from SENet is inserted in every other block (after the 3×323 \times 3^2, reduction ratio 1/16), and Swish is used only before and after the 3×323 \times 3^2 layers. All other layers use ReLU (Appendix A.3).

An expanded example: X3D-M (Table 3(b); left of the figure at the top of the article)

X3D-M is the model expanded with γτ=5\gamma_\tau = 5, γt=16\gamma_t = 16, γs=2\gamma_s = 2, γw=1\gamma_w = 1, γb=2.25\gamma_b = 2.25, and γd=2.2\gamma_d = 2.2. It takes 16 frames (224 × 224) sampled every 5 frames as input; res2 to res5 have 3, 5, 11, and 7 blocks, with inner block widths of 54, 108, 216, and 432. It costs 4.73 GFLOPs and has 3.76M parameters.

X3D-S keeps the same 3.76M parameters but lowers only the input resolution (13 frames, 160 × 160, 1.96 GFLOPs), while X3D-XL expands spatial resolution, width, and depth from X3D-M (16 frames, 312 × 312, 35.84 GFLOPs, 11.0M). Even in X3D-XL, the widest layer has only 630 channels.

Theory: expanding one axis at a time

Six expansion operations (Section 3.2)

X2D can be expanded along the following six axes (bottom right of the figure at the top of the article).

OperationExpansion factorWhat it changes
X-Fastγτ\gamma_\tauRaises the frame rate while keeping the interval length (the frame count γt\gamma_t also increases)
X-Temporalγt\gamma_tLengthens the interval and also raises the frame rate
X-Spatialγs\gamma_sRaises the spatial resolution of the input
X-Depthγd\gamma_dMultiplies the number of blocks in each stage by γd\gamma_d
X-Widthγw\gamma_wMultiplies the channels of all layers by γw\gamma_w
X-Bottleneckγb\gamma_bWidens only the channels of the central convolution in the residual blocks

Forward expansion (Section 3.3, Appendix A.3)

Expansion follows the procedure below, modeled on forward selection in machine learning feature selection (adding useful features one at a time).

  1. Start from X2D with all six factors set to 1.
  2. For each of the six axes, build a model that expands only that axis so that the compute (FLOPs) roughly doubles. The per-step factors are: X-Fast scales the frame interval by 0.5 (doubling the frame count), X-Temporal scales the interval by 0.75 and doubles the count, X-Spatial scales the resolution by 2\sqrt{2}, X-Depth by about 2.2, X-Width by 2, and X-Bottleneck by about 2.25.
  3. Train the six models and compare their accuracy on validation data.
  4. Keep the one with the best compute-accuracy trade-off as the starting point for the next expansion.
  5. Repeat steps 2 to 4 until the target compute is reached.

The paper writes this with an evaluation function J(X)J(X) (the accuracy of the model expanded with factors XX) and a complexity function C(X)C(X) (FLOPs):

X=argmax⁡Z, C(Z)=cJ(Z)X = \operatorname*{argmax}_{Z,\ C(Z) = c} J(Z)

ZZ is a candidate set of factors and cc is the target compute. Because only one axis changes per step, only six candidates are tried each time. This is a form of coordinate descent (optimizing by moving only one coordinate at a time) in the space of expansion factors.

Backward contraction (Section 3.3)

Forward expansion roughly doubles the compute each step, so it does not necessarily hit the target compute exactly. When the target is exceeded, the last expansion is shrunk to a factor below 2 to match it. For example, X3D-S is the model obtained after the 7th expansion by reducing the frame count γt\gamma_t to fit under 2 GFLOPs (reducing γt\gamma_t was reported to work better than reducing other axes).

Each expansion step trains only six models, and most of them are low-compute models. The five expansions leading to the smallest model, X3D-XS, train six models each at roughly 0.04, 0.08, 0.15, 0.30, and 0.60 GFLOPs, for only 30 models in total. This is a very different cost from image architecture search (MnasNet and others), which tries thousands of models.

Why thin, high-resolution networks work

1. Expanding any axis improves accuracy, but by different amounts

During expansion (Figure 2), expanding any of the six axes improved accuracy. Beyond that, the order in which axes were chosen reveals the following:

  • The first axis chosen was not time but bottleneck width (γb\gamma_b): In the first step, from X2D (47.75% top-1) to 41.4M FLOPs, the model expanding γb\gamma_b was best at 55.0%, while the model expanding depth γd\gamma_d was worst at 51.3%. The paper attributes this to channel-wise convolutions being cheap, so widening the inside of the block adds little compute. This goes in the same direction as the inverted bottleneck (a block that widens its inside) of MobileNetV2.
  • In the second step, the frame count goes from 1 to 2: Only at this point does the network start handling temporal information.
  • After that, spatial and temporal resolution are raised alternately, and depth is added after raising resolution: The paper explains that as resolution rises, more depth is needed to grow the receptive field (the input region that one output sees) of each stage.
  • Overall width γw\gamma_w is not chosen until the 10th expansion: Even though X2D was deliberately built thin, expanding resolution and depth paid off more than width.

As an everyday analogy: when choosing a camera on a fixed budget, increasing the frame count and pixel count (temporal and spatial resolution) helps distinguish motion more than buying an expensive lens (wide layers).

2. The result has the same "thin and fine-grained" shape as the Fast pathway

The resulting X3D is much thinner than video networks derived from image networks (which have wide layers), and has higher spatiotemporal resolution. The Fast pathway of SlowFast was designed to be thin with a high frame rate, though on its own its accuracy is low (51.7% on Kinetics-400). X3D showed that this shape can reach sufficient accuracy even without the wide Slow pathway.

3. Mobile components help especially at small compute budgets (Appendix B, Table A.1)

Change (Kinetics-400 val, 10 clips)X3D-S top-1X3D-XL top-1
As is72.9 (1.96 GFLOPs)78.4 (35.84 GFLOPs)
Remove channel-wise convolution and lower γb\gamma_b to match compute68.9 (1.95)76.0 (34.80)
Remove channel-wise convolution (γb\gamma_b unchanged)73.2 (17.6)79.2 (365.4)
Remove Swish72.078.0
Remove SE71.377.1

Without channel-wise convolutions, accuracy drops by 4.0 points (X3D-S) and 2.4 points (X3D-XL) at the same compute. Switching back to ordinary convolutions raises accuracy slightly, but compute grows about 9 to 10 times. Removing SE costs more (1.6 and 1.3 points) than removing Swish (0.9 and 0.4 points).

Experimental results

X3D at each size (Kinetics-400 val, center crop of 10 clips, Table 2 of the paper; GFLOPs per clip)

ModelCompute targettop-1top-5GFLOPsParameters
X3D-XS≤ 0.668.687.90.603.76M
X3D-S≤ 272.990.51.963.76M
X3D-M≤ 574.691.74.733.76M
X3D-L≤ 2076.892.518.376.08M
X3D-XL≤ 4078.493.635.8411.0M
X3D-XXL≤ 15080.094.5143.520.3M

Comparison with earlier methods (Kinetics-400 val, 30 views = 10 clips × 3 crops; excerpt from Table 4 of the paper; "Compute" is GFLOPs per view × number of views)

ModelPretrainingtop-1top-5ComputeParameters
I3DImageNet71.190.3108 × N/A12M
TSM R50ImageNet74.7N/A65 × 1024.3M
Nonlocal R101ImageNet77.793.3359 × 3054.3M
ip-CSN-152None77.892.8109 × 3032.8M
SlowFast 4×16, R50None75.692.136.1 × 3034.4M
SlowFast 8×8, R101+NLNone78.793.5116 × 3059.9M
SlowFast 16×8, R101+NLNone79.893.9234 × 3059.9M
X3D-MNone76.092.36.2 × 303.8M
X3D-LNone77.592.924.8 × 306.1M
X3D-XLNone79.193.948.4 × 3011.0M
X3D-XXLNone80.494.6194.1 × 3020.3M

X3D-M is 0.4 points higher than SlowFast 4×16 (R50) with about 1/6 the compute and about 1/9 the parameters. On Kinetics-600 as well, X3D-XL reaches 81.9% top-1, on par with SlowFast 16×8, R101+NL (81.8%, 234 × 30 GFLOPs) (Table 5).

Comparison with EfficientNet extended to 3D (Kinetics-400 val, Table 7 of the paper)

X3D was compared with EfficientNet3D, which uses the same mobile components and expands time and space uniformly with the scaling factors of EfficientNet.

Modeltop-1GFLOPsParameters
EfficientNet3D-B066.70.743.30M
X3D-XS68.60.603.76M
EfficientNet3D-B372.46.918.19M
X3D-M74.64.733.76M
EfficientNet3D-B474.523.8012.16M
X3D-L76.818.376.08M

Expanding one axis at a time on video gave higher accuracy with less compute than reusing factors found on images directly in 3D. The gap widens for larger models.

Other tasks (Tables 6 and 8 of the paper)

TaskModelPretrainingResultCompute
Charades (mAP)SlowFast+NLKinetics-60045.2234 × 30
Charades (mAP)X3D-XLKinetics-60047.148.4 × 30
AVA v2.2 (action detection, mAP)SlowFast 8×8, R101+NLKinetics-60027.4146
AVA v2.2 (action detection, mAP)X3D-XLKinetics-60027.448.4

For AVA detection, as with SlowFast, X3D serves as the backbone of a detector similar to Faster R-CNN, and person-region features are extracted from the res5 feature map with RoIAlign.

Practical considerations

Keep the following points in mind when using X3D:

  • Three clips are nearly enough: In Figure 3, going from 1 clip to 3 clips gives a large gain, and adding more clips helps only slightly. For example, X3D-S with 3 clips reaches 71.4% (5.9 GFLOPs), surpassing CSN-50 with 10 clips (70.8%, 119 GFLOPs) at about 1/20 the compute. The 30-view numbers in the tables are the setting that maximizes accuracy.
  • Input size differs by model: X3D-S uses 13 frames at 160 × 160, X3D-M 16 frames at 224 × 224, and X3D-XL 16 frames at 312 × 312. When using pretrained weights, match that model's frame count, interval, and resolution.
  • Training is large-scale, like SlowFast: On Kinetics, models are trained from scratch without ImageNet pretraining. The setup is synchronous SGD (128 GPUs, mini-batch 1024, momentum 0.9, weight decay 5×10−55 \times 10^{-5}), a half-period cosine learning rate schedule (base learning rate 1.6), warmup for the first 8k iterations, 256 epochs, and dropout of 0.5 before the classifier. Larger models also add DropConnect (0.1, 0.2).
  • The mobile "linear bottleneck" is not used: The MobileNetV2-style design that removes the activation after the last 1×1² is not used, because it sometimes made distributed training unstable (it prevents initializing the scale of the last BN in the residual block to 0).

X3D's "lightness" is measured in FLOPs and parameter counts. The paper compares compute in FLOPs as a hardware-independent metric and does not report actual runtime. Fewer FLOPs do not necessarily shorten runtime by the same ratio, so when deploying on a device or server, measure the actual speed in that environment before choosing.

Comparison with other models

Comparing video action recognition models from the same perspective gives the following:

ModelConvolution / attentionHow time is handledHow the design is decidedKinetics-400 top-1 (paper values)
Two-Stream ConvNets2DOptical flow streamReuse an image CNN as is―
C3D3D (all 3×3×3)3D convolutions in every layerHand-designed―
I3D3D (inflated Inception-v1)3D convolutions + flowInflate an image CNN71.1 (RGB)
TSM2DShift part of the channels along timeUse an image CNN74.7
SlowFast3D (early Slow layers are 2D)Two pathways at different frame ratesExtend an image ResNet79.8
X3DChannel-wise 3DHigh frame rate with a thin networkExpand a small model one axis at a time79.1 (XL) to 80.4 (XXL)
TimeSformer, ViViTSpatiotemporal self-attentionAttention along timeExtend an image Transformer―

The numbers for TSM versus SlowFast and X3D differ in conditions such as pretraining and number of clips (see the tables in "Experimental results").

Rough guidelines for choosing:

  • High accuracy with little compute and few parameters: X3D is a good fit. X3D-M, with 3.8M parameters and 6.2 GFLOPs per view, surpassed SlowFast 4×16 (R50).
  • Choosing a size to fit a compute budget: X3D offers a family built the same way from XS (0.6 GFLOPs) to XXL (143.5 GFLOPs), so a size can be picked to match the budget.
  • Running with only the same operations as a 2D CNN: TSM, which uses no 3D convolutions, is a good fit.
  • Large-scale pretraining is available: Attention-based video models such as TimeSformer, ViViT, and Video Swin Transformer are also options.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of X3D (Feichtenhofer 2020, Section 3.1, Table 1, Table 3(b), Appendix A.3).
X3D-M settings: input (N, 3, 16, 224, 224), γb = 2.25, blocks per stage 3, 5, 11, 7.
"""


class SE(nn.Module):
  """Squeeze-and-Excitation. Global average -> reduce -> expand -> sigmoid weights applied to channels."""

  def __init__(self, c, ratio=1 / 16):
    super().__init__()
    h = max(8, int(c * ratio))
    self.fc = nn.Sequential(nn.AdaptiveAvgPool3d(1), nn.Conv3d(c, h, 1), nn.ReLU(inplace=True),
                            nn.Conv3d(h, c, 1), nn.Sigmoid())

  def forward(self, x):
    return x * self.fc(x)


class X3DBlock(nn.Module):
  """Expand with 1×1² -> 3×3² channel-wise 3D conv (-> SE) -> project back with 1×1² -> residual sum."""

  def __init__(self, cin, cmid, cout, stride, use_se):
    super().__init__()
    self.a = nn.Sequential(nn.Conv3d(cin, cmid, 1, bias=False), nn.BatchNorm3d(cmid), nn.SiLU())   # swish before the 3×3²
    # groups=cmid makes it channel-wise. Temporal stride is 1 (no temporal downsampling)
    self.b = nn.Sequential(nn.Conv3d(cmid, cmid, 3, stride=(1, stride, stride), padding=1, groups=cmid, bias=False),
                           nn.BatchNorm3d(cmid))
    self.se = SE(cmid) if use_se else nn.Identity()
    self.act = nn.SiLU()                       # swish after the 3×3² (swish only around it, ReLU elsewhere; Appendix A.3)
    self.c = nn.Sequential(nn.Conv3d(cmid, cout, 1, bias=False), nn.BatchNorm3d(cout))
    self.short = nn.Identity() if (cin == cout and stride == 1) else nn.Sequential(
      nn.Conv3d(cin, cout, 1, stride=(1, stride, stride), bias=False), nn.BatchNorm3d(cout))
    self.out = nn.ReLU(inplace=True)

  def forward(self, x):
    y = self.c(self.act(self.se(self.b(self.a(x)))))
    return self.out(y + self.short(x))


class X3D(nn.Module):
  def __init__(self, num_classes=400, widths=(24, 48, 96, 192), depths=(3, 5, 11, 7), gamma_b=2.25):
    super().__init__()
    c0 = widths[0]
    self.conv1 = nn.Sequential(
      nn.Conv3d(3, c0, (1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1), bias=False),      # spatial 1×3²
      nn.Conv3d(c0, c0, (3, 1, 1), padding=(1, 0, 0), groups=c0, bias=False),            # temporal 3×1, channel-wise
      nn.BatchNorm3d(c0), nn.ReLU(inplace=True))
    blocks, cin = [], c0
    for w, n in zip(widths, depths):
      for i in range(n):
        blocks.append(X3DBlock(cin, int(w * gamma_b), w, stride=2 if i == 0 else 1, use_se=(i % 2 == 0)))
        cin = w
    self.stages = nn.Sequential(*blocks)
    c5 = int(widths[-1] * gamma_b)                                                         # conv5: 432
    self.conv5 = nn.Sequential(nn.Conv3d(cin, c5, 1, bias=False), nn.BatchNorm3d(c5), nn.ReLU(inplace=True))
    self.pool = nn.AdaptiveAvgPool3d(1)                                                   # pool5
    self.head = nn.Sequential(nn.Flatten(), nn.Linear(c5, 2048), nn.ReLU(inplace=True),    # fc1
                              nn.Dropout(0.5), nn.Linear(2048, num_classes))               # dropout 0.5 before fc2

  def forward(self, clip):                     # clip: (N, 3, T, H, W)
    x = self.conv5(self.stages(self.conv1(clip)))
    return self.head(self.pool(x))


model = X3D(num_classes=400)
model.eval()    # disable dropout; BN uses learned statistics (use model.train() for training)
with torch.no_grad():
  clip = torch.randn(1, 3, 16, 224, 224)      # 16 frames sampled every 5 frames (X3D-M)
  print(model(clip).shape)                    # torch.Size([1, 400])

FAQ

Q. What do the "X" and "3D" in X3D stand for?
A.

It stands for Expand 3D: a small 2D spatial network (X2D) is "expanded" into 3D spatiotemporal space. The six axes being expanded are frame interval γτ\gamma_\tau, frame count γt\gamma_t, spatial resolution γs\gamma_s, overall width γw\gamma_w, bottleneck width γb\gamma_b, and depth γd\gamma_d.

Q. How does X3D scaling differ from EfficientNet scaling?
A.

EfficientNet scales depth, width, and resolution together at fixed ratios, which are first found by a grid search. X3D repeatedly expands only one axis per step and picks the best of six candidates, so the order and amount of expansion differ per axis. In the paper, X3D was 1.9 to 2.3 points higher at the same compute than models expanded to 3D with EfficientNet's factors.

Q. Should I use X3D or SlowFast?
A.

At similar accuracy, X3D has the advantage of less compute and fewer parameters. On Kinetics-400, X3D-XL (79.1%) falls 0.7 points short of SlowFast 16×8, R101+NL (79.8%), but uses about 1/5 the compute and about 1/5.5 the parameters. However, the comparison is in FLOPs, and actual speed depends on the environment, so measure on the target hardware before deciding.

References

  1. Feichtenhofer, C. (2020). X3D: Expanding Architectures for Efficient Video Recognition. CVPR 2020. arXiv:2004.04730.
  2. facebookresearch/SlowFast (the authors' public code, including X3D).
  3. Feichtenhofer, C., Fan, H., Malik, J., & He, K. (2019). SlowFast Networks for Video Recognition. ICCV 2019. arXiv:1812.03982.
  4. Tan, M., & Le, Q. V. (2019). EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks. arXiv:1905.11946.