AI Logic

Architectures

TimeSformer

Updated:

TimeSformer architecture. Left: the overall flow (each of 8 frames is split into 196 patches of 16×16, embedded with a linear layer, a class token and space-time positional embeddings are added, the tokens pass through 12 divided space-time attention blocks, and an MLP classifies from the class token output). Upper right: inside a block (time attention, space attention, and MLP in that order, each preceded by layer normalization and followed by a residual connection). Lower right: a comparison of what one patch attends to (space only, joint space-time, and divided; the number of tokens compared is 197, 1569, and 206)

Background and overview

TimeSformer (Time-Space Transformer) is a video recognition model that treats a video as "a sequence of patches from each frame," feeds it into a Transformer, and computes temporal and spatial self-attention separately in each block. It uses no convolutions at all. Bertasius, Wang, and Torresani of Facebook AI presented it at ICML 2021, in a paper titled "Is Space-Time Attention All You Need for Video Understanding?"

For images, ViT had split an image into patches, arranged them like words, and matched CNN accuracy using only a Transformer encoder. TimeSformer extends ViT to video. The paper lists three advantages of using self-attention for video:

  • Weaker inductive bias: The convolutional properties of "looking only nearby" and "being the same under shifts" help when data is scarce, but with plenty of data they may overly restrict the functions the model can represent.
  • Direct capture of long-range relations: Convolutions cannot see beyond their receptive field, so long-range relations can only be gathered gradually by stacking layers. Self-attention can directly compare every pair of time steps and positions.
  • Fast training and inference: Image Transformers had been reported to train larger models than CNNs within the same compute budget.

However, video has many patches (1,568 even for 8 frames), and self-attention that compares every pair becomes computationally heavy. The paper therefore compared five ways of applying space-time self-attention and showed that "divided attention," which applies temporal attention and spatial attention separately in sequence, is best in both compute and accuracy.

The paper's main results are:

  • On Kinetics-400, the default TimeSformer reached 78.0% top-1 with 0.59 TFLOPs of inference compute per video. TimeSformer-L, which sees longer inputs, reached 80.7%, the best at the time.
  • Training on Kinetics-400 took only 416 GPU hours, reaching higher accuracy (75.8%) in less time than SlowFast (75.6% with 3,840 GPU hours; both pretrained on ImageNet-1K).
  • It can see 96 frames (about 12 seconds of Kinetics video) in a single clip, and outperformed SlowFast by 8–11 points on classification of long videos several minutes in length.

Architecture

Input and patch embedding (Section 3, Eq. (1))

  1. The input is FF RGB frames sampled from a video, X∈RH×W×3×FX \in \mathbb{R}^{H \times W \times 3 \times F}. The default is 8 frames at 224 × 224, sampled every 32 frames.
  2. Each frame is split into N=HW/P2=196N = HW/P^2 = 196 non-overlapping P×PP \times P (P=16P = 16) patches, each flattened into a vector x(p,t)\mathbf{x}_{(p,t)} of length 3P23P^2. pp is the position within the frame, and tt is the frame index.
  3. A learnable matrix EE maps each to DD dimensions, and a learnable space-time positional embedding e(p,t)pos\mathbf{e}^{pos}_{(p,t)} is added.
z(p,t)(0)=E x(p,t)+e(p,t)pos\mathbf{z}^{(0)}_{(p,t)} = E\,\mathbf{x}_{(p,t)} + \mathbf{e}^{pos}_{(p,t)}
  1. As in BERT, a learnable classification token z(0,0)(0)\mathbf{z}^{(0)}_{(0,0)} is prepended to the sequence. The number of tokens is NF+1=1,569NF + 1 = 1{,}569.

Encoder blocks (Section 3, Eqs. (2)–(9))

LL blocks are stacked. In each block, Layer Normalization is applied to the previous block's output before computing queries, keys, and values (Pre-LN), and the output of multi-head attention is projected and added as a residual. The MLP that follows also has LN and a residual connection.

z(p,t)′(ℓ)=WO[s(p,t)(ℓ,1)⋮s(p,t)(ℓ,A)]+z(p,t)(ℓ−1),z(p,t)(ℓ)=MLP(LN(z(p,t)′(ℓ)))+z(p,t)′(ℓ)\mathbf{z}'^{(\ell)}_{(p,t)} = W_O \begin{bmatrix} \mathbf{s}^{(\ell,1)}_{(p,t)} \\ \vdots \\ \mathbf{s}^{(\ell,A)}_{(p,t)} \end{bmatrix} + \mathbf{z}^{(\ell-1)}_{(p,t)}, \qquad \mathbf{z}^{(\ell)}_{(p,t)} = \mathrm{MLP}\left(\mathrm{LN}\left(\mathbf{z}'^{(\ell)}_{(p,t)}\right)\right) + \mathbf{z}'^{(\ell)}_{(p,t)}

s(p,t)(ℓ,a)\mathbf{s}^{(\ell,a)}_{(p,t)} is the attention output of the aa-th head, and AA is the number of heads.

Classification (Eq. (10))

The classification token's output from the last block, with LN applied, y=LN(z(0,0)(L))\mathbf{y} = \mathrm{LN}(\mathbf{z}^{(L)}_{(0,0)}), is fed into an MLP with one hidden layer to predict the class.

Size (Section 4)

It uses ViT-Base (D=768D = 768, L=12L = 12, 12 heads), initialized from ViT weights trained on ImageNet-1K or ImageNet-21K. TimeSformer with divided attention has 121.4M parameters. There are three variants with different inputs:

VariantInput (frames × height × width)Frame sampling interval
TimeSformer8 × 224 × 224Every 32 frames
TimeSformer-HR (high resolution)16 × 448 × 448―
TimeSformer-L (long input)96 × 224 × 224Every 4 frames

Theory: self-attention divided into time and space

Self-attention that compares everything jointly (Eq. (5))

The weights of scaled dot-product attention are computed from the dot products between the query q\mathbf{q} of patch (p,t)(p, t) and the keys k\mathbf{k} of all patches, including the classification token.

α(p,t)(ℓ,a)=SM(q(p,t)(ℓ,a)⊤Dh⋅[k(0,0)(ℓ,a) {k(p′,t′)(ℓ,a)}p′=1,…,N; t′=1,…,F])\boldsymbol{\alpha}^{(\ell,a)}_{(p,t)} = \mathrm{SM}\left( \frac{\mathbf{q}^{(\ell,a)\top}_{(p,t)}}{\sqrt{D_h}} \cdot \left[ \mathbf{k}^{(\ell,a)}_{(0,0)} \ \left\{ \mathbf{k}^{(\ell,a)}_{(p',t')} \right\}_{p'=1,\dots,N;\ t'=1,\dots,F} \right] \right)

SM is softmax, and Dh=D/AD_h = D/A is the dimension of one head. Each patch is compared with NF+1NF + 1 tokens, so the total compute grows with the square of the number of tokens, that is, rapidly with the number of frames and the resolution.

Divided space-time attention (T+S, Eqs. (6) and (11))

Each TimeSformer block computes the following in order (upper right of the figure at the top of the article).

  1. Time attention: Patch (p,t)(p, t) is compared only with patches at the same position pp in other frames.
α(p,t)(ℓ,a) time=SM(q(p,t)(ℓ,a)⊤Dh⋅[k(0,0)(ℓ,a) {k(p,t′)(ℓ,a)}t′=1,…,F])\boldsymbol{\alpha}^{(\ell,a)\,\mathrm{time}}_{(p,t)} = \mathrm{SM}\left( \frac{\mathbf{q}^{(\ell,a)\top}_{(p,t)}}{\sqrt{D_h}} \cdot \left[ \mathbf{k}^{(\ell,a)}_{(0,0)} \ \left\{ \mathbf{k}^{(\ell,a)}_{(p,t')} \right\}_{t'=1,\dots,F} \right] \right)
  1. The output, after the projection and residual of Eq. (8), z(p,t)′(ℓ) time\mathbf{z}'^{(\ell)\,\mathrm{time}}_{(p,t)}, is passed not to the MLP but to the following space attention.
  2. Space attention: New queries, keys, and values are computed from z′(ℓ) time\mathbf{z}'^{(\ell)\,\mathrm{time}}, and patch (p,t)(p, t) is compared only with patches in the same frame tt.
α(p,t)(ℓ,a) space=SM(q(p,t)(ℓ,a)⊤Dh⋅[k(0,0)(ℓ,a) {k(p′,t)(ℓ,a)}p′=1,…,N])\boldsymbol{\alpha}^{(\ell,a)\,\mathrm{space}}_{(p,t)} = \mathrm{SM}\left( \frac{\mathbf{q}^{(\ell,a)\top}_{(p,t)}}{\sqrt{D_h}} \cdot \left[ \mathbf{k}^{(\ell,a)}_{(0,0)} \ \left\{ \mathbf{k}^{(\ell,a)}_{(p',t)} \right\}_{p'=1,\dots,N} \right] \right)
  1. The output of space attention is passed through the MLP of Eq. (9).

Time and space use separately learned query, key, and value weights (e.g., WQtimeW_{Q^{\mathrm{time}}} and WQspaceW_{Q^{\mathrm{space}}}). Each patch is compared with (N+1)+(F+1)=N+F+2(N + 1) + (F + 1) = N + F + 2 tokens, which in the default setting drops from 1,569 to 206 (lower right of the figure at the top of the article).

Time attention gathers "the past and future at the same position," and space attention then compares the patches that carry this information, so in two stages information reaches every patch in space and time. As an everyday analogy, instead of talking one-on-one with everyone in the classroom, you first talk to yourself in the same seat at earlier and later times, and then talk with everyone in the classroom at the same moment.

The other three schemes compared in the paper (Figure 1, Figure 2)

SchemeWhat one patch attends to
Space only (S)Only patches in the same frame (no temporal relations)
Joint space-time (ST)All patches in all frames
Sparse local-global (L+G)Nearby F×H/2×W/2F \times H/2 \times W/2 patches, plus all patches at a stride of 2 in time, height, and width
Axial (T+W+H)The three axes of time, width, and height, one at a time in sequence

Schemes split into two or more stages, including divided (T+S), learn separate query, key, and value weights for each stage.

Both the time and space attention weights are initialized from the attention weights of the same layer of a ViT trained on ImageNet (Appendix A). Time attention is a component ViT does not have, but this lets the weights learned on images serve directly as the starting point.

Why dividing time and space works

1. Highest accuracy (Validation on Kinetics-400 and Something-Something-V2. Table 1 of the paper.)

SchemeParametersKinetics-400SSv2
Space only85.9M76.936.6
Joint space-time85.9M77.458.5
Divided (time → space)121.4M78.059.5
Sparse local-global121.4M75.956.3
Axial156.8M73.556.2

Space-only attention still scores a high 76.9% on Kinetics-400, but drops to 36.6% on Something-Something-V2 (SSv2), which requires capturing complex temporal relations. The paper explains that Kinetics is biased toward spatial (scene) cues, whereas SSv2 cannot be solved without capturing temporal relations. Divided attention was best on both, and the paper attributes this to its greater learning capacity from having separate weights for time and space.

2. Compute grows slowly even for long videos and high resolutions (Figure 3)

The joint space-time scheme ran out of GPU memory when the resolution was raised to 448 pixels or the frames were increased to 32. With divided attention, each patch is compared with N+F+2N + F + 2 tokens, which grows only additively as frames increase, so it can handle inputs of up to 96 frames or 560 pixels.

3. Order and arrangement make little difference (Section 4.7)

Putting space first and time second lowered accuracy by 0.5 points on both Kinetics-400 and SSv2. Running time and space attention in parallel lowered it by 0.4 points.

4. Space-time positional embeddings support temporal information (Table 4 of the paper)

Positional embeddingKinetics-400SSv2
None75.445.8
Space only77.852.5
Space-time78.059.5

On SSv2, omitting temporal positions lowers accuracy by 7.0 points.

Experimental results

Comparison with 3D CNNs (Kinetics-400. Table 2 of the paper. Inference TFLOPs are per video.)

ModelPretrainingTraining time (V100 GPU hours)top-1Inference TFLOPsParameters
I3D 8×8 R50ImageNet-1K44471.01.1128.0M
I3D 8×8 R50ImageNet-1K1,44073.41.1128.0M
SlowFast R50ImageNet-1K44870.01.9734.6M
SlowFast R50ImageNet-1K3,84075.61.9734.6M
SlowFast R50None6,33676.41.9734.6M
TimeSformerImageNet-1K41675.80.59121.4M
TimeSformerImageNet-21K41678.00.59121.4M

Despite having more parameters, TimeSformer required less inference compute and less training time. With comparable training time (about 440 GPU hours), SlowFast reaches only 70.0% and I3D only 71.0%.

Comparison with the previous state of the art (Kinetics-400 validation. Excerpt from Table 5 of the paper.)

Modeltop-1top-5Inference TFLOPs
R(2+1)D72.090.017.5
TSM74.7N/AN/A
ip-CSN-15277.892.83.2
SlowFast79.893.97.0
X3D-XXL80.494.65.8
TimeSformer78.093.70.59
TimeSformer-HR79.794.45.11
TimeSformer-L80.794.77.14

While many other methods run inference with 30 views (10 clips × 3 crops), TimeSformer uses only 3 crops (3 views) from a single clip at the center of the video. Inference on the 20,000 Kinetics-400 validation videos (8 V100s) took 14.88 hours for SlowFast, 36 minutes for TimeSformer, and 2.6 hours for TimeSformer-L. On Kinetics-600, TimeSformer-L reached 82.2% top-1, beating SlowFast (81.8%) and X3D-XL (81.9%) (Table 6).

Datasets where temporal relations matter (Table 7 of the paper. Pretrained on ImageNet-1K.)

ModelSSv2Diving-48
SlowFast61.777.6
TSM63.4N/A
bLVNet65.2N/A
TimeSformer59.574.9
TimeSformer-HR62.278.0
TimeSformer-L62.481.0

On SSv2, it did not reach the best method. On Diving-48, it outperformed the reproduced SlowFast 16×8 (R101).

Long-video classification (Classification of 1,059 tasks in HowTo100M. Table 8 of the paper. Both pretrained on Kinetics-400.)

Input framesTime span covered by one clipSlowFastTimeSformer
88.5 s48.256.8
3234.1 s50.861.2
6468.3 s51.562.2
96102.4 s51.262.6

For clips covering the same time span, TimeSformer outperformed SlowFast by 8–11 points and improved with longer inputs.

Practical considerations

Keep the following in mind when using TimeSformer:

  • Image pretraining is nearly essential: With many parameters (121.4M), the paper says training from scratch is difficult. Training on Kinetics-400 without ImageNet pretraining reached only 64.8%, even with longer training and more data augmentation. ImageNet-21K pretraining helped on Kinetics-400 (75.8% → 78.0%) but made little difference on SSv2 (Table 3).
  • With little video data, it can lose to 3D CNNs: On SSv2, when training data was reduced to 25% or 50%, TimeSformer was not the best of the three models (compared with SlowFast and I3D); it became the best at 75% or more (Figure 4). On Kinetics-400, TimeSformer was the best at every data amount.
  • Bigger is not always better: Using ViT-Large lowered accuracy by about 1 point on Kinetics-400 and SSv2, and ViT-Small lowered it by about 5 points. Using 32 × 32 patches lowered it by about 3 points (Section 4.7).
  • Training settings: 15 epochs, initial learning rate 0.005 (divided by 10 at epochs 11 and 14), synchronous SGD (32 GPUs, momentum 0.9, weight decay 10−410^{-4}), and a mini-batch of 16. The shorter side is resized to 256–320 and a 224 × 224 crop is taken (Appendix A).

High accuracy on Kinetics can be achieved without much use of temporal relations. In the paper, even the "space only" model without time attention reached 76.9% on Kinetics-400. When deciding whether to use it for tasks where motion or order is decisive (how objects are moved, the direction of an action, etc.), check results not only on Kinetics but also on datasets where temporal relations matter, such as SSv2.

Comparison with other models

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

ModelCore operationHow time is capturedPretrainingKinetics-400 top-1 (as reported in the papers)
I3D3D convolution3D convolution + optical flowImageNet + Kinetics71.1 (RGB)
SlowFast3D convolutionTwo pathways at different frame ratesNone79.8
X3DChannel-wise 3D convolutionHigh frame rate with a thin networkNone80.4 (XXL)
TimeSformerSelf-attentionDivided time → space attention (every block)ImageNet-21K80.7 (L)
ViViTSelf-attentionFour variants, including a temporal encoder after a spatial encoderImageNet-21K, etc.―
Video Swin Transformer3D window self-attentionLocal space-time windowsImageNet-21K, etc.―

Rough guidelines for choosing:

  • Short training time or few GPUs: TimeSformer, which can start from a ViT trained on ImageNet, is a good fit. In the paper, it exceeded SlowFast's accuracy at 3,840 GPU hours with only 416 GPU hours.
  • Seeing long videos (tens of seconds to minutes) in one clip: TimeSformer-L can handle 96 frames, so it is a good fit.
  • Temporal relations matter and training data is scarce: 3D CNNs (such as SlowFast) may be better.
  • Minimal compute and parameters: X3D is a good fit. TimeSformer needs little inference compute but has many parameters (121.4M).

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of TimeSformer's divided space-time attention (Bertasius et al. 2021, Section 3, Eqs. (6), (8), (9), (11)).
x: (B, 1 + N*F, D). The first token is the class token; the rest are patches at frame t and position p, ordered by (p, t).
The class token is handled as in the official implementation (facebookresearch/TimeSformer):
  it is excluded from time attention; in space attention it is attached to each frame and its outputs are averaged over frames.
"""


class DividedSpaceTimeBlock(nn.Module):
  def __init__(self, dim=768, heads=12, mlp_ratio=4.0):
    super().__init__()
    self.norm_t = nn.LayerNorm(dim)
    self.attn_t = nn.MultiheadAttention(dim, heads, batch_first=True)   # q/k/v and W_O for time
    self.norm_s = nn.LayerNorm(dim)
    self.attn_s = nn.MultiheadAttention(dim, heads, batch_first=True)   # Separate weights for space
    self.norm_m = nn.LayerNorm(dim)
    self.mlp = nn.Sequential(nn.Linear(dim, int(dim * mlp_ratio)), nn.GELU(), nn.Linear(int(dim * mlp_ratio), dim))

  def forward(self, x, N, F):
    B, _, D = x.shape
    cls, xp = x[:, :1], x[:, 1:]                                  # (B, 1, D), (B, N*F, D)

    # (1) Time attention: among the F patches at the same position p
    xt = xp.reshape(B * N, F, D)
    h = self.norm_t(xt)
    xt = xt + self.attn_t(h, h, h, need_weights=False)[0]         # Residual of Eq. (8)
    xp = xt.reshape(B, N * F, D)

    # (2) Space attention: among the N patches in the same frame t (+ class token)
    xs = xp.reshape(B, N, F, D).transpose(1, 2).reshape(B * F, N, D)
    c = cls.repeat_interleave(F, dim=0)                           # Attach the class token to each frame
    xs = torch.cat([c, xs], dim=1)                                # (B*F, 1+N, D)
    h = self.norm_s(xs)
    xs = xs + self.attn_s(h, h, h, need_weights=False)[0]
    cls = xs[:, :1].reshape(B, F, 1, D).mean(dim=1)               # Average the class token over frames
    xp = xs[:, 1:].reshape(B, F, N, D).transpose(1, 2).reshape(B, N * F, D)

    # (3) MLP: Eq. (9)
    x = torch.cat([cls, xp], dim=1)
    return x + self.mlp(self.norm_m(x))


class TimeSformer(nn.Module):
  def __init__(self, num_classes=400, frames=8, img=224, patch=16, dim=768, depth=12, heads=12):
    super().__init__()
    self.N, self.F = (img // patch) ** 2, frames
    self.embed = nn.Conv2d(3, dim, patch, stride=patch)           # Linear patch embedding E for each frame (Eq. (1))
    self.cls = nn.Parameter(torch.zeros(1, 1, dim))
    self.pos = nn.Parameter(torch.zeros(1, 1 + self.N * frames, dim))   # Space-time positional embedding e_pos(p, t)
    self.blocks = nn.ModuleList([DividedSpaceTimeBlock(dim, heads) for _ in range(depth)])
    self.norm = nn.LayerNorm(dim)
    self.head = nn.Linear(dim, num_classes)   # The paper uses an MLP with one hidden layer; the official code uses a single linear layer

  def forward(self, video):                   # video: (B, 3, F, H, W)
    B, C, F, H, W = video.shape
    x = self.embed(video.transpose(1, 2).reshape(B * F, C, H, W))  # (B*F, D, 14, 14)
    x = x.flatten(2).transpose(1, 2)                                # (B*F, N, D)
    x = x.reshape(B, F, self.N, -1).transpose(1, 2).reshape(B, self.N * F, -1)   # Order by (p, t)
    x = torch.cat([self.cls.expand(B, -1, -1), x], dim=1) + self.pos
    for blk in self.blocks:
      x = blk(x, self.N, self.F)
    return self.head(self.norm(x[:, 0]))      # Eq. (10): LN on the class token output


model = TimeSformer(num_classes=400)
model.eval()    # Disables dropout etc. if present (use model.train() for training)
with torch.no_grad():
  print(model(torch.randn(1, 3, 8, 224, 224)).shape)   # torch.Size([1, 400])

FAQ

Q. How does TimeSformer differ from ViT?
A.

ViT computes self-attention among the patches of a single image. TimeSformer arranges patches from multiple frames and, in each block, first applies time attention with other frames at the same position, then space attention within the same frame. Its positional embeddings also include temporal positions, not just spatial ones. The weights for space attention and the MLP start from a ViT trained on ImageNet.

Q. Doesn't divided attention lose information compared with joint space-time attention?
A.

Each attention step sees a narrower range, but because time attention first gathers information from other frames at the same position before space attention is applied, information from every patch in space and time reaches each patch in two stages. In the paper, divided attention (78.0% on Kinetics-400, 59.5% on SSv2) scored higher than joint space-time attention (77.4% and 58.5%).

Q. Why is TimeSformer inference fast?
A.

Besides reducing the number of tokens each patch is compared with from NF+1=1,569NF + 1 = 1{,}569 to N+F+2=206N + F + 2 = 206, it uses few views per video. Many 3D CNNs run inference with 30 views (10 clips × 3 crops), while TimeSformer uses only 3 crops from a single center clip. In the paper, inference on the Kinetics-400 validation set took 36 minutes, versus 14.88 hours for SlowFast.

References

  1. Bertasius, G., Wang, H., & Torresani, L. (2021). Is Space-Time Attention All You Need for Video Understanding? ICML 2021. arXiv:2102.05095.
  2. facebookresearch/TimeSformer (the authors' official code).
  3. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  4. Feichtenhofer, C., Fan, H., Malik, J., & He, K. (2019). SlowFast Networks for Video Recognition. ICCV 2019. arXiv:1812.03982.