AI Logic

Architectures

ViViT

Updated:

Architecture of ViViT. Left: the overall flow of Model 2 (factorised encoder): 32 frames sampled with a stride of 2 are embedded as 16 (height) Γ— 16 (width) Γ— 2 (time) tubelets; for each of 16 time steps, 196 tokens plus a CLS token pass through the same spatial encoder, and the CLS outputs of all time steps pass through the temporal encoder for classification. Right: a comparison of one layer in each of the four models (Model 1: self-attention over all tokens; Model 2: spatial encoder followed by temporal encoder; Model 3: spatial MSA, temporal MSA, and MLP within one layer; Model 4: dot-product attention with half the heads spatial and the rest temporal).

Background and Overview

ViViT (Video Vision Transformer) is a video classification model that processes spatio-temporal tokens extracted from a video with the same Transformer as ViT. It uses no convolutions; its main operation is self-attention. It was presented at ICCV 2021 by Arnab, Dehghani, Heigold, Sun, LučiΔ‡, and Schmid of Google Research.

The problem with applying a Transformer to video is the number of tokens. A video yields dozens of times more tokens than an image, and self-attention, which compares every pair, grows quadratically with the number of tokens. In addition, a Transformer lacks the inductive biases of a CNN (looking at nearby pixels, translation equivariance, and so on), so it needs large datasets to perform well. Video datasets, however, are much smaller than image datasets.

ViViT addresses these two problems as follows.

  • Number of tokens: It builds four variants (Models 1–4) that factorise spatial and temporal processing in different ways, and compares their accuracy and cost.
  • Scarcity of data: It shows how to initialise from ViT weights trained on images, together with a combination of regularisation techniques that curbs overfitting on small datasets.

The main results of the paper are as follows.

  • On Kinetics-400, ViViT-L/16x2 (Model 2) pretrained on ImageNet-21K reaches 81.7% top-1, outperforming SlowFast (79.8%), X3D-XXL (80.4%), and the contemporaneous TimeSformer-L (80.7%).
  • ViViT-H/14x2, pretrained on the larger JFT dataset, reaches 84.9% on Kinetics-400 and 85.8% on Kinetics-600.
  • It set the state of the art at the time on five datasets: Kinetics-400, Kinetics-600, Epic Kitchens-100, Something-Something v2, and Moments in Time.

Architecture

The underlying ViT (Section 3.1)

ViT splits an image into NN non-overlapping patches, projects them linearly, prepends a classification token zclsz_{cls}, and adds a learned positional embedding p\mathbf{p}.

z=[zcls,Ex1,Ex2,…,ExN]+p\mathbf{z} = [z_{cls}, E\mathbf{x}_1, E\mathbf{x}_2, \dots, E\mathbf{x}_N] + \mathbf{p}

This sequence passes through an LL-layer Transformer. Each layer consists of multi-head attention (MSA) and an MLP, each preceded by Layer Normalization (LN) and wrapped in a residual connection. The MLP is two linear layers with a GELU in between.

yβ„“=MSA(LN(zβ„“))+zβ„“,zβ„“+1=MLP(LN(yβ„“))+yβ„“\mathbf{y}^{\ell} = \mathrm{MSA}(\mathrm{LN}(\mathbf{z}^{\ell})) + \mathbf{z}^{\ell}, \qquad \mathbf{z}^{\ell+1} = \mathrm{MLP}(\mathrm{LN}(\mathbf{y}^{\ell})) + \mathbf{y}^{\ell}

Two ways to tokenise a video (Section 3.2)

The paper compares two ways to map a video V∈RTΓ—HΓ—WΓ—CV \in \mathbb{R}^{T \times H \times W \times C} to a token sequence z~∈RntΓ—nhΓ—nwΓ—d\tilde{\mathbf{z}} \in \mathbb{R}^{n_t \times n_h \times n_w \times d}.

MethodWhat it doesWhere temporal information is mixed
Uniform frame samplingSamples ntn_t frames, embeds each frame as patches exactly as in ViT, and concatenates all of themInside the Transformer
Tubelet embeddingExtracts non-overlapping boxes (tubelets) of height hh Γ— width ww Γ— time tt and projects them linearly (equivalent to a 3D convolution)At tokenisation

With a tubelet of size tΓ—hΓ—wt \times h \times w, the number of tokens along time, height, and width is nt=⌊T/tβŒ‹n_t = \lfloor T/t \rfloor, nh=⌊H/hβŒ‹n_h = \lfloor H/h \rfloor, and nw=⌊W/wβŒ‹n_w = \lfloor W/w \rfloor. Smaller tubelets produce more tokens and more computation.

Sizes and naming (Section 4.1)

The backbones are ViT-Base (12 layers, 12 heads, d=768d = 768), ViT-Large (24 layers, 16 heads, d=1024d = 1024), and ViT-Huge (32 layers, 16 heads, d=1280d = 1280). A name such as "ViViT-B/16x2" denotes a ViT-Base backbone with tubelets of 16 Γ— 16 spatially and 2 temporally. The default input is 32 frames sampled with a stride of 2. With 16 Γ— 16 Γ— 2 tubelets and a 224 Γ— 224 input, nt=16n_t = 16 and nh=nw=14n_h = n_w = 14, giving 16Γ—196=3,13616 \times 196 = 3{,}136 tokens.

Theory: Four Ways to Factorise Space and Time

The paper builds four models that differ in where the Transformer separates space and time (right side of the figure at the top of the article).

Model 1: Spatio-temporal attention

All spatio-temporal tokens are fed to the Transformer as they are. From the first layer, the model can capture relations between distant tokens anywhere in the video, but the cost is O((ntβ‹…nhβ‹…nw)2)O((n_t \cdot n_h \cdot n_w)^2), which grows quickly as frames are added.

Model 2: Factorised encoder (left side of the figure at the top of the article)

Two Transformer encoders are connected in series.

  1. Spatial encoder (LsL_s layers): computes self-attention only among tokens from the same time index. The output of each time index's classification token (or the mean of all tokens if there is no classification token) becomes the representation of that time index, hi∈Rd\mathbf{h}_i \in \mathbb{R}^d.
  2. The representations are stacked into H∈RntΓ—d\mathbf{H} \in \mathbb{R}^{n_t \times d}.
  3. Temporal encoder (LtL_t layers): computes self-attention among the per-time representations and classifies the output token.

The spatial encoder has the same form as an image classification encoder, which corresponds to the "late fusion" of CNNs that extract per-frame features and then aggregate them over time (such as TSN). Although it has more layers and parameters than Model 1, its cost is lower: O((nhβ‹…nw)2+nt2)O((n_h \cdot n_w)^2 + n_t^2).

Model 3: Factorised self-attention (Eqs. (4)–(6))

The number of layers stays the same as in Model 1, but the self-attention in each layer is split into two steps: spatial (among tokens at the same time index) and temporal (among tokens at the same spatial position).

ysβ„“=MSA(LN(zsβ„“))+zsβ„“\mathbf{y}^{\ell}_s = \mathrm{MSA}(\mathrm{LN}(\mathbf{z}^{\ell}_s)) + \mathbf{z}^{\ell}_s ytβ„“=MSA(LN(ysβ„“))+ysβ„“\mathbf{y}^{\ell}_t = \mathrm{MSA}(\mathrm{LN}(\mathbf{y}^{\ell}_s)) + \mathbf{y}^{\ell}_s zβ„“+1=MLP(LN(ytβ„“))+ytβ„“\mathbf{z}^{\ell+1} = \mathrm{MLP}(\mathrm{LN}(\mathbf{y}^{\ell}_t)) + \mathbf{y}^{\ell}_t

For the spatial MSA, the tokens are reshaped into ntn_t groups (each of nhβ‹…nwn_h \cdot n_w tokens); for the temporal MSA, into nhβ‹…nwn_h \cdot n_w groups (each of ntn_t tokens). The cost is about the same as Model 2. No classification token is used, to avoid ambiguity during reshaping. The idea is the same as the "divided attention" of the contemporaneous TimeSformer (TimeSformer applies time first, while Model 3 applies space first; the paper reports that, with the initialisation described below, the order did not change the results).

Model 4: Factorised dot-product attention (Eq. (7))

This variant keeps the cost at the level of Models 2 and 3 while keeping the same number of parameters as Model 1. The heads of a layer's multi-head attention are split in half: one half attends only to tokens at the same time index (keys and values Ks,Vs∈Rnhβ‹…nwΓ—dK_s, V_s \in \mathbb{R}^{n_h \cdot n_w \times d}), and the other half only to tokens at the same spatial position (Kt,Vt∈RntΓ—dK_t, V_t \in \mathbb{R}^{n_t \times d}). Each head is scaled dot-product attention.

Attention(Q,K,V)=Softmax(QK⊀dk)V\mathrm{Attention}(Q, K, V) = \mathrm{Softmax}\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V Ys=Attention(Q,Ks,Vs),Yt=Attention(Q,Kt,Vt),Y=Concat(Ys,Yt) WOY_s = \mathrm{Attention}(Q, K_s, V_s), \quad Y_t = \mathrm{Attention}(Q, K_t, V_t), \quad Y = \mathrm{Concat}(Y_s, Y_t)\,W_O

Initialisation from image weights (Section 3.4)

Because video data is scarce, training starts from ViT weights learned on images. Parts that the image model lacks are initialised as follows.

  • Positional embeddings: the nhβ‹…nwn_h \cdot n_w positional embeddings of the image model are repeated ntn_t times along time. Initially, tokens at the same spatial position share the same embedding; they diverge during training.
  • Tubelet embedding EE: the paper compares "inflation", which stacks the 2D filter along time and scales it by 1/t1/t as in I3D, with "central frame initialisation", which places the image filter only at the central time step and zeros elsewhere, and adopts the latter.
E=1t[Eimage,…,Eimage,…,Eimage](inflation),E=[0,…,Eimage,…,0](centralΒ frame)E = \frac{1}{t}[E_{image}, \dots, E_{image}, \dots, E_{image}] \quad \text{(inflation)}, \qquad E = [0, \dots, E_{image}, \dots, 0] \quad \text{(central frame)}
  • Temporal MSA in Model 3: the spatial MSA is initialised from the image weights and the temporal MSA from all zeros. Eq. (5) then initially reduces to a plain residual connection, so training starts from the same behaviour as the image model.

With central frame initialisation, the tubelet embedding initially behaves as if it "looks at one frame per time step", and as training proceeds it learns to mix in information from neighbouring frames. This preserves the image weights while leaving room to learn temporal information.

Why the Factorised Designs Work

1. Accuracy and cost of the four models (ViViT-B, 16 Γ— 2 tubelets. Table 2 of the paper. EK is action accuracy on Epic Kitchens; runtime is inference on TPU-v3.)

ModelK400EKGFLOPsParametersRuntime
Model 1: Spatio-temporal80.043.1455.288.9M58.9 ms
Model 2: Factorised encoder78.843.7284.4115.1M17.4 ms
Model 3: Factorised self-attention77.439.1372.3117.3M31.7 ms
Model 4: Factorised dot-product76.339.5277.188.9M22.9 ms
Model 2 with the temporal encoder replaced by average pooling75.838.8283.986.7M17.3 ms

With the same input, Model 1, which compares everything, scores highest on Kinetics-400, but it overfits more easily on the smaller Epic Kitchens, where Model 2 scores highest. Model 2 runs in about one third of Model 1's time. Replacing the temporal encoder with global average pooling barely changes the cost but lowers accuracy by 3.0 points on Kinetics and 4.9 points on Epic Kitchens, showing that learning relations between time steps matters. The number of temporal encoder layers LtL_t makes little difference, 78.6–78.9% for 1 to 12 layers (Table 3); the default is 4.

2. Lighter designs can handle more tokens

Because Model 2 is cheaper, it can take more frames as input. Model 1 (ViViT-L, temporal tubelet size 2) ran out of memory at 48 frames, while Model 2 handled up to 128 frames and reached higher accuracy than Model 1 at a lower total cost (Section 4.2, Figure 9). Kinetics videos have 250 frames (10 seconds at 25 frames per second), so 128 frames sampled with a stride of 2 cover the whole video in a single view.

As an everyday analogy, Model 1 is a meeting where everyone talks directly with everyone else, while Model 2 has each department talk first (space) and then gathers only the department representatives (time). The latter loses the fine-grained exchanges between individuals, but the meeting still works as the number of people grows.

3. Finer tokens give higher accuracy

Shortening the temporal length of the tubelet from 8 β†’ 4 β†’ 2 (increasing the number of tokens) improved accuracy for all four models (Figure 8). Raising the spatial resolution from 224 β†’ 288 β†’ 320 also improved ViViT-L/16x2 (Model 1) from 80.3% β†’ 80.7% β†’ 81.0% (Table 5).

4. Input encoding and initialisation (ViViT-B, Model 1, Kinetics-400. Table 1 of the paper)

Input encodingtop-1
Uniform frame sampling78.5
Tubelet (random initialisation)73.2
Tubelet (inflation)77.6
Tubelet (central frame)79.2

Experimental Results

Comparison on Kinetics-400 (excerpt from Table 6a of the paper. "Views" is temporal clips Γ— spatial crops; TFLOPs is the total over all views.)

ModelPretrainingtop-1top-5ViewsTFLOPs
I3D NL―77.793.310 Γ— 310.77
ip-CSN-152―79.293.810 Γ— 33.27
SlowFast R101-NL―79.893.910 Γ— 37.02
X3D-XXL―80.494.610 Γ— 35.82
TimeSformer-LImageNet-21K80.794.71 Γ— 37.14
ViViT-L/16x2 FEImageNet-21K80.692.71 Γ— 13.98
ViViT-L/16x2 FEImageNet-21K81.793.81 Γ— 311.94
ip-CSN-152IG (large-scale)82.595.310 Γ— 33.27
ViViT-L/16x2 FEJFT83.594.31 Γ— 311.94
ViViT-H/14x2JFT84.995.84 Γ— 347.77

FE is Model 2 (factorised encoder). A "―" in the pretraining column means Table 6a gives no entry (SlowFast and X3D are trained from scratch). Whereas many CNN methods use 30 views, ViViT reaches comparable or higher accuracy with 1 to 3 views.

Other datasets (Tables 6b–e of the paper. ViViT-L/16x2 FE, pretrained on ImageNet-21K)

DatasetMetricPrevious best (within the paper's tables)ViViT
Kinetics-600top-1TimeSformer-L 82.282.9
Moments in Timetop-1AssembleNet-101 34.338.5
Epic Kitchens-100Action top-1SlowFast 38.544.0
Something-Something v2top-1bLVNet 65.265.9

Something-Something v2 (SSv2) is a dataset in which backgrounds and objects look similar across classes, so classes must be distinguished by fine-grained motion. The margin here is small, but ViViT also outperforms TimeSformer-HR (62.5%), another pure Transformer.

Effect of regularisation (Epic Kitchens, Model 2. Table 4 of the paper. Each row includes everything above it.)

AddedAction top-1
Random crop, flip, colour jitter38.4
+ Initialise from Kinetics-400 weights39.6
+ Stochastic Depth40.2
+ RandAugment41.1
+ Label Smoothing43.1
+ Mixup43.7

The total gain is 5.3 points. On SSv2, the same regularisation also gave a gain of about 5 points.

Practical Considerations

Keep the following points in mind when using ViViT.

  • Choose the variant by dataset size: on large datasets such as Kinetics, Model 1 scores highest, but it overfits easily on small datasets, where Model 2 is a better fit. Model 2 is also easier to handle in terms of compute and memory, and the paper mainly uses Model 2 for comparisons with the state of the art.
  • Add regularisation on small datasets: on Epic Kitchens and SSv2, even models pretrained on ImageNet overfit. Adding Stochastic Depth, RandAugment (applying the same transformation to every frame), Label Smoothing, and Mixup improved accuracy by around 5 points. On Kinetics and Moments in Time, the state of the art was reached without them.
  • Set the number of views by video length: accuracy plateaus once the views are enough to cover the whole video (Figure 9). The 32-frame model peaks at 4 views and the 128-frame model at 1 view, with nearly the same total cost (995.3 GFLOPs per view Γ— 4 versus 3,980.4 GFLOPs Γ— 1).
  • Training setup: synchronous SGD (momentum 0.9), a cosine learning rate schedule with warmup (2.5 epochs), and a mini-batch size of 64. On Kinetics-400, training runs for 30 epochs with a base learning rate of 0.1 (Table 7 in the appendix).

ViViT depends on weights pretrained on images. The paper states that because video datasets are much smaller than image datasets, training large models from scratch to high accuracy is extremely difficult, and lists removing the dependence on image models as future work. The best result of 84.9% also comes from pretraining on the non-public JFT dataset, so when reproducing results, use the value with ImageNet-21K weights (81.7%) as a reference.

Comparison with Other Models

Comparing models that handle video with Transformers or CNNs from the same viewpoints gives the following.

ModelTokens / inputHandling of space and timePretrainingKinetics-400 top-1 (up to ImageNet-type pretraining)
SlowFastFrames (two frame rates)Two pathways of 3D convolutionsNone79.8
X3DFramesChannel-wise 3D convolutionsNone80.4 (XXL)
TimeSformer16Γ—16 patches per frameDivided attention, time β†’ space, in every blockImageNet-21K80.7 (L)
ViViT16Γ—16Γ—2 tubeletsFour variants (mainly spatial encoder β†’ temporal encoder)ImageNet-21K, JFT81.7 (L/16x2 FE)
Video Swin Transformer2Γ—4Γ—4 3D patchesLocal spatio-temporal 3D windows, hierarchicalImageNet-21K, etc.―

Rough guidelines for choosing are as follows.

  • Large pretrained weights are available and high accuracy with few views is wanted: ViViT (Model 2) is a good fit. With 1 to 3 views, it outperformed CNNs that use 30 views.
  • A long video should be seen in a single input: Model 2's cost grows roughly linearly with the number of frames, so it can handle long inputs such as 128 frames.
  • The ViT architecture should be reused almost as is: to keep every block identical to ViT, use TimeSformer; to reuse the spatial encoder as is and append a temporal encoder, ViViT's Model 2 is the closer fit.
  • No pretraining and a small compute budget: a lightweight 3D CNN such as X3D is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of ViViT Model 2 (factorised encoder; Arnab et al. 2021, Sections 3.2-3.4).
Embeds an input (B, 3, T, H, W) with 16 x 16 x 2 (space x time) tubelets,
runs the spatial encoder per time step (shared weights) -> feeds each time step's CLS output to the temporal encoder -> classifies.
"""


def encoder(dim, depth, heads):
  # Pre-LN (norm_first=True) Transformer encoder with a 4x GELU MLP (Eqs. (2)(3))
  layer = nn.TransformerEncoderLayer(dim, heads, dim_feedforward=4 * dim, activation="gelu",
                                     batch_first=True, norm_first=True, dropout=0.0)
  return nn.TransformerEncoder(layer, depth)


class ViViTFactorisedEncoder(nn.Module):
  def __init__(self, num_classes=400, frames=32, img=224, tube=(2, 16, 16), dim=768, heads=12, Ls=12, Lt=4):
    super().__init__()
    t, h, w = tube
    self.nt, self.ns = frames // t, (img // h) * (img // w)          # n_t = 16, n_hΒ·n_w = 196
    # Tubelet embedding = 3D convolution whose kernel and stride equal the tubelet size
    self.embed = nn.Conv3d(3, dim, kernel_size=tube, stride=tube)
    self.cls_s = nn.Parameter(torch.zeros(1, 1, dim))               # CLS token of the spatial encoder
    self.pos_s = nn.Parameter(torch.zeros(1, 1 + self.ns, dim))     # spatial positional embedding
    self.spatial = encoder(dim, Ls, heads)
    self.cls_t = nn.Parameter(torch.zeros(1, 1, dim))               # CLS token of the temporal encoder
    self.pos_t = nn.Parameter(torch.zeros(1, 1 + self.nt, dim))     # temporal positional embedding
    self.temporal = encoder(dim, Lt, heads)
    self.norm = nn.LayerNorm(dim)
    self.head = nn.Linear(dim, num_classes)

  def forward(self, video):                                         # (B, 3, T, H, W)
    B = video.shape[0]
    x = self.embed(video)                                           # (B, d, n_t, 14, 14)
    x = x.flatten(3).permute(0, 2, 3, 1).reshape(B * self.nt, self.ns, -1)   # 196 tokens per time step
    x = torch.cat([self.cls_s.expand(B * self.nt, -1, -1), x], dim=1) + self.pos_s
    h = self.spatial(x)[:, 0]                                       # per-time representation h_i (CLS output)
    h = h.reshape(B, self.nt, -1)                                   # H: (B, n_t, d)
    z = torch.cat([self.cls_t.expand(B, -1, -1), h], dim=1) + self.pos_t
    z = self.temporal(z)[:, 0]
    return self.head(self.norm(z))


def central_frame_init(conv3d, conv2d_weight):
  """Initialise the tubelet embedding with "central frame" initialisation (Eq. (9)).
  conv2d_weight: patch embedding of an image ViT, (d, 3, 16, 16)."""
  with torch.no_grad():
    w = torch.zeros_like(conv3d.weight)                             # (d, 3, t, 16, 16)
    w[:, :, conv3d.weight.shape[2] // 2] = conv2d_weight            # image weights only at the central time step ⌊t/2βŒ‹
    conv3d.weight.copy_(w)


model = ViViTFactorisedEncoder(num_classes=400)
central_frame_init(model.embed, torch.randn(768, 3, 16, 16))       # in practice, pretrained ViT weights
model.eval()    # use model.train() for training (the paper adds Stochastic Depth etc. on small datasets)
with torch.no_grad():
  print(model(torch.randn(1, 3, 32, 224, 224)).shape)              # torch.Size([1, 400])

FAQ

Q. Which of ViViT's four models should I use?
A.

Model 2 (factorised encoder) is a safe first choice. In the paper, with the same input, Model 1 scores highest on Kinetics-400 (80.0%), but Model 2 scores highest on the smaller Epic Kitchens and runs inference in about one third of Model 1's time. Because it is cheaper, it can take more frames, and it is the model mainly used in the comparisons with the state of the art.

Q. What is tubelet embedding?
A.

It cuts a video into non-overlapping boxes of height hh Γ— width ww Γ— time tt and projects each box linearly into one token. It is equivalent to a 3D convolution whose kernel and stride equal the box size. Unlike splitting each frame into patches, it mixes information from neighbouring time steps already at tokenisation. In the paper, tubelets with central frame initialisation scored 0.7 points higher than uniform frame sampling.

Q. How do ViViT and TimeSformer differ?
A.

Both are contemporaneous models that extend ViT to video. TimeSformer uses per-frame patches and applies divided temporal and spatial attention in every block. ViViT tokenises with tubelets and mainly uses Model 2, which runs the full spatial encoder before the temporal encoder. ViViT's Model 3 is essentially the same idea as TimeSformer's divided attention. In the paper, ViViT (65.9%) outperformed TimeSformer-HR (62.5%) on SSv2.

References

  1. Arnab, A., Dehghani, M., Heigold, G., Sun, C., LučiΔ‡, M., & Schmid, C. (2021). ViViT: A Video Vision Transformer. ICCV 2021. arXiv:2103.15691.
  2. google-research/scenic (official code by the ViViT authors).
  3. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  4. Bertasius, G., Wang, H., & Torresani, L. (2021). Is Space-Time Attention All You Need for Video Understanding? ICML 2021. arXiv:2102.05095.