The Video Swin Transformer is a hierarchical video recognition model that extends the image Swin Transformer to video and computes self-attention only within small 3D windows spanning time ร height ร width. From layer to layer, the windows are shifted along time, height, and width so that information is also exchanged with neighboring windows. Liu, Ning, Cao, Wei, Zhang, Lin, and Hu at Microsoft Research Asia released it on arXiv in 2021 and presented it at CVPR 2022.
Earlier video Transformers (TimeSformer, ViViT, and others) were all based on ViT and used self-attention that connects the whole of space or time. Even when they reduced computation by factorizing time and space, each direction was still attended globally.
The paper instead advocates an inductive bias of locality. In video, pixels that are close in time and space are more strongly related, so global self-attention can be well approximated by self-attention computed only over nearby positions. This greatly reduces computation and parameters. Moreover, because the architecture matches the image Swin Transformer, it can start from strong weights trained on images.
The main results of the paper are as follows.
It reached top-1 accuracy of 84.9% on Kinetics-400 and 86.1% on Kinetics-600, surpassing the previous best, ViViT-H (pretrained on JFT-300M, 647.5M parameters), by 0.1 and 0.3 points. Its pretraining data, ImageNet-21K, is about 1/20 the size, and the model, at 200.0M parameters, is about 1/3 the size.
On Something-Something v2 (SSv2), which relies heavily on temporal relations, it reached top-1 accuracy of 69.6%, 0.9 points above the previous best (MViT).
Architecture
Overall flow (Section 3.1, Figure 1; the left side of the figure at the top of the article)
The input is T frames (TรHรWร3). By default, 32 frames are sampled from the video every other frame and resized to 224 ร 224.
Split into 3D patches: each box of 2 in time ร 4 in height ร 4 in width (2ยท4ยท4ยท3 = 96 dimensions) becomes one token. There are 2Tโร4Hโร4Wโ tokens, which is 16 ร 56 ร 56 for the default input.
Stage 1: a linear embedding maps the tokens to C dimensions, followed by a stack of Video Swin Transformer blocks.
Stages 2 to 4: patch merging concatenates spatially neighboring 2 ร 2 tokens and halves the dimension with a linear layer (4Cโ2C), followed by a stack of blocks. Space is halved at each stage, but the time axis is not downsampled.
The final features go into a classification head (in the official implementation, global average pooling and a linear layer).
It keeps the four-stage hierarchy of the image Swin Transformer as is, and leaving the time axis undownsampled follows prior work.
Sizes (Section 3.3)
Variant
C
Blocks per stage
Approximate size
Swin-T
96
2, 2, 6, 2
About 0.25ร Swin-B
Swin-S
96
2, 2, 18, 2
About 0.5ร
Swin-B
128
2, 2, 18, 2
1ร
Swin-L
192
2, 2, 18, 2
About 2ร
The default window size is PรMรM=8ร7ร7 (8 in time, 7 in height and width), each head has dimension d=32, and the MLP hidden layer is 4ร wider.
Video Swin Transformer block (Sections 3.1 to 3.2, Eq. (1); the upper right of the figure at the top of the article)
It replaces the multi-head self-attention (MSA) of an ordinary Transformer layer with MSA over 3D shifted windows. Layer Normalization (LN) is placed before the MSA and the FFN (a 2-layer MLP with GELU in between), and a residual connection follows each. Blocks come in pairs: the first builds windows with the regular partition (3DW-MSA), and the second with the shifted partition (3DSW-MSA).
Computing only within non-overlapping 3D windows (Section 3.2)
The TโฒรHโฒรWโฒ tokens are evenly partitioned into non-overlapping 3D windows of size PรMรM, giving โTโฒ/PโรโHโฒ/MโรโWโฒ/Mโ windows. Multi-head self-attention is computed only among the tokens within each window.
In global self-attention, each token is compared with all TโฒHโฒWโฒ others, so computation grows with the square of the number of tokens. Within a window, the comparisons are limited to PM2 tokens, and computation grows only linearly with the number of tokens. For the default input (16 ร 56 ร 56 = 50,176 tokens) and window (8 ร 7 ร 7 = 392 tokens), the number of tokens each token is compared with drops to about 1/128.
Shifting the windows along time, height, and width (Section 3.2, Figure 3)
Computing only within windows means tokens in different windows cannot exchange information. So in the second of two consecutive blocks, the window partition is shifted by (2Pโ,2Mโ,2Mโ) tokens along time, height, and width.
In the paper's example (the lower right of the figure at the top of the article), partitioning 8 ร 8 ร 8 tokens with 4 ร 4 ร 4 windows gives 2ร2ร2=8 windows in layer l. Layer l+1 shifts by (2,2,2), splitting the tokens into 3ร3ร3=27 windows. With the shifted partition, tokens that were in different windows in layer l fall into the same window, so information spreads to neighboring windows as layers stack. The number of windows increases, but with the same efficient batching as the image Swin Transformer (cyclic shift and masking), the number of windows computed stays at 8.
As an everyday analogy, it is like dividing the seats in a classroom into groups that talk only among themselves, then shifting the group boundaries in the next period so that people can also talk with those who were in a different group before.
3D relative position bias (Section 3.2, Eq. (2))
As in the image Swin Transformer, a bias BโRP2รM2รM2 determined by the relative positions of tokens is added to each head's attention (relative position representations).
Attention(Q,K,V)=SoftMax(dโQKโคโ+B)V
Q,K,VโRPM2รd are the queries, keys, and values of the PM2 tokens in one window. Relative positions range over [โP+1,Pโ1] in time and [โM+1,Mโ1] in height and width, so what is actually learned is a small table B^โR(2Pโ1)ร(2Mโ1)ร(2Mโ1), from which the values of B are taken.
Initialization from image weights (Section 3.4)
Only two parts differ in shape from the image Swin Transformer: the linear embedding in stage 1 and the relative position bias.
Linear embedding: since input tokens now span 2 frames in time, the shape changes from 48รC to 96รC. The pretrained weights are duplicated twice and the whole is multiplied by 0.5 so that the mean and variance of the output stay the same (the same idea as the inflation in I3D).
Relative position bias: the shape changes from (2Mโ1,2Mโ1) to (2Pโ1,2Mโ1,2Mโ1). The pretrained table is duplicated 2Pโ1 times along time, so every time offset starts from the same bias as within a single frame.
In training, setting the learning rate of the backbone, initialized from image weights, to 0.1ร that of the randomly initialized classification head improved results (for Swin-B on Kinetics-400 with ImageNet-21K pretraining, 82.0% โ 82.6%). The paper reasons that the backbone generalizes better when it adapts to video while slowly forgetting the pretrained weights and data.
Why local windows work
1. Attending to space and time jointly does not increase computation (Swin-T, Kinetics-400; Table 4 of the paper)
The paper compared three ways of handling space and time.
Design
What it does
top-1
GFLOPs
Parameters
Joint (default)
A single 3D window self-attention attends to time and space simultaneously
78.8
88
28.2M
Split encoder
Adds two temporal Transformer layers on top of a spatial-only Swin Transformer (the same idea as ViViT's Model 2)
76.4
83
42.0M
Factorized self-attention
Adds a temporal-only MSA after every spatial-only MSA (the same idea as TimeSformer)
78.5
95
36.5M
With ViT as the base, the joint spatiotemporal design was too expensive to be practical, so factorized designs were chosen. Limiting the spatial extent with windows keeps the joint design cheap as well, and it gave the best balance of accuracy and parameters.
2. Time can be local too (Swin-T, Kinetics-400; Table 5 of the paper)
Temporal tokens
Window
top-1
GFLOPs
16
16 ร 7 ร 7 (global in time)
79.1
106
16
8 ร 7 ร 7 (default)
78.8
88
16
4 ร 7 ร 7
78.6
79
8
8 ร 7 ร 7 (global in time)
78.5
44
4
4 ร 7 ร 7 (global in time)
76.7
20
Shrinking the temporal window from 16 to 8 lowered accuracy by only 0.3 points and cut computation by 17%. The paper states that the benefit of temporal locality grows further when the input has very many frames. On the other hand, reducing the number of temporal tokens (shortening the input) lowers accuracy considerably.
3. Shifting in 3D helps (Swin-T, Kinetics-400; Table 6 of the paper)
Setting
top-1
Shift in 3D (default)
78.8
No shift along time
78.5
No shift
78.1
Shifting added 0.7 points, of which shifting along time accounted for 0.3 points.
Experimental results
Comparison on Kinetics-400 (excerpt from Table 1 of the paper. "Views" is temporal clips ร spatial crops, and GFLOPs are per view)
"384" denotes a spatial resolution raised to 384 ร 384. Swin-S (ImageNet-1K) beats X3D-XXL with similar computation and needs fewer views. Swin-L (384) with ImageNet-21K pretraining surpassed ViViT-L (320) with the same pretraining by 3.3 points at about half the computation. The ViViT and TimeSformer values are those listed in Table 1 of this paper and may differ from the tables in their original papers in aspects such as the number of views.
Kinetics-600 (excerpt from Table 2 of the paper)
Model
Pretraining
top-1
GFLOPs ร views
X3D-XL
โ
81.9
48 ร 30
MViT-B-24, 32ร3
โ
83.8
236 ร 5
ViViT-H/16x2
JFT-300M
85.8
8,316 ร 12
Swin-B
ImageNet-21K
84.0
282 ร 12
Swin-L (384)
ImageNet-21K
86.1
2,107 ร 50
Something-Something v2 (excerpt from Table 3 of the paper)
On SSv2, training started from weights trained on Kinetics-400, used a temporal window of 16, and applied stronger data augmentation (Section 4.1).
Practical considerations
Keep the following points in mind when using the Video Swin Transformer.
Use pretrained image weights: for Swin-B, ImageNet-21K pretraining gave 2.1 points more than ImageNet-1K (80.6% โ 82.7%). The less video data there is, the greater the benefit of starting from strong image weights.
Use different learning rates for the backbone and the head: set the learning rate of the pretrained backbone to 0.1ร that of the randomly initialized classification head (on Kinetics, 3ร10โ5 for the backbone and 3ร10โ4 for the head).
Training settings (Kinetics, Section 4.1): AdamW for 30 epochs, a cosine learning rate schedule with 2.5 epochs of warmup, and a mini-batch of 64. Larger models use stronger Stochastic Depth (0.1, 0.2, 0.3 for Swin-T, S, B) and weight decay (0.02, 0.02, 0.05). Inference averages 12 views of 4 clips ร 3 crops.
Change the settings for data with heavy temporal relations: on SSv2, training was extended to 60 epochs, Label Smoothing, RandAugment, and Random Erasing were added, and Stochastic Depth was set to 0.4.
The window size has a large effect on computation and accuracy. Widening the temporal window to the input length (16) raises accuracy slightly but increases computation by about 20% (Table 5). Also, Swin-L with the spatial resolution raised to 384 needs 2,107 GFLOPs per view, more than 7 times Swin-B (282 GFLOPs). The best accuracy figures come from such heavy settings.
Comparison with other models
Comparing models that handle video with Transformers or CNNs from the same viewpoints gives the following.
Model
Tokens and input
Range of self-attention or convolution
Hierarchy
Kinetics-400 top-1 (up to ImageNet-21K pretraining)
Global spatial encoder โ global temporal encoder, etc.
No
81.3
Video Swin Transformer
2ร4ร4 3D patches
Local 3D windows (shifted layer by layer)
Yes (4 stages)
84.9
The values for I3D, TimeSformer, and ViViT are taken from Table 1 of the Video Swin Transformer paper.
Rough guidelines for choosing are as follows.
High accuracy with publicly available image weights: the Video Swin Transformer is a good fit. With ImageNet-21K pretraining, it surpassed ViViT-H pretrained on JFT-300M.
Tasks with heavy temporal relations (such as SSv2): the Video Swin Transformer is strong, with the best result of 69.6% at the time of the paper.
A backbone for tasks needing multi-resolution features, such as detection or segmentation: since it has the same hierarchy as the image Swin Transformer, its per-stage feature maps can be used just like a CNN's.
Running with little computation and no pretraining: lightweight 3D CNNs such as X3D are a better fit.
PyTorch example
โถShow code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small example implementation of the 3D window self-attention of the Video Swin Transformer (Liu et al., Section 3.2, Eqs. (1)(2)).
x: tokens of shape (B, D, H, W, C). Self-attention is computed only within PรMรM windows,
and blocks with shift=True shift the partition by (P/2, M/2, M/2) (cyclic shift + mask).
"""
def window_partition(x, ws):
B, D, H, W, C = x.shape
x = x.view(B, D // ws[0], ws[0], H // ws[1], ws[1], W // ws[2], ws[2], C)
return x.permute(0, 1, 3, 5, 2, 4, 6, 7).reshape(-1, ws[0] * ws[1] * ws[2], C) # (num_windows*B, PMยฒ, C)
def window_reverse(w, ws, B, D, H, W):
x = w.view(B, D // ws[0], H // ws[1], W // ws[2], ws[0], ws[1], ws[2], -1)
return x.permute(0, 1, 4, 2, 5, 3, 6, 7).reshape(B, D, H, W, -1)
class WindowAttention3D(nn.Module):
def __init__(self, dim, heads, ws):
super().__init__()
self.h, self.ws, self.scale = heads, ws, (dim // heads) ** -0.5
self.qkv, self.proj = nn.Linear(dim, 3 * dim), nn.Linear(dim, dim)
# 3D relative position bias: look up B from a small table of (2P-1)(2M-1)(2M-1) x heads (Eq. (2))
self.table = nn.Parameter(torch.zeros((2 * ws[0] - 1) * (2 * ws[1] - 1) * (2 * ws[2] - 1), heads))
c = torch.stack(torch.meshgrid([torch.arange(s) for s in ws], indexing="ij")).flatten(1) # (3, PMยฒ)
r = (c[:, :, None] - c[:, None, :]).permute(1, 2, 0) + torch.tensor([ws[0] - 1, ws[1] - 1, ws[2] - 1])
idx = r[..., 0] * (2 * ws[1] - 1) * (2 * ws[2] - 1) + r[..., 1] * (2 * ws[2] - 1) + r[..., 2]
self.register_buffer("idx", idx)
def forward(self, x, mask=None): # x: (nW*B, N, C), N = PMยฒ
Bw, N, C = x.shape
q, k, v = self.qkv(x).reshape(Bw, N, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4)
attn = (q * self.scale) @ k.transpose(-2, -1) # QK^T / โd
attn = attn + self.table[self.idx].permute(2, 0, 1) # + B
if mask is not None: # when shifted, mask pairs of tokens that come from different windows
nW = mask.shape[0]
attn = attn.view(Bw // nW, nW, self.h, N, N) + mask[None, :, None]
attn = attn.view(Bw, self.h, N, N)
x = (attn.softmax(-1) @ v).transpose(1, 2).reshape(Bw, N, C)
return self.proj(x)
class VideoSwinBlock(nn.Module):
def __init__(self, dim=96, heads=3, ws=(8, 7, 7), shift=False):
super().__init__()
self.ws, self.shift = ws, tuple(s // 2 for s in ws) if shift else (0, 0, 0)
self.norm1, self.attn = nn.LayerNorm(dim), WindowAttention3D(dim, heads, ws)
self.norm2 = nn.LayerNorm(dim)
self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim)) # FFN: 2 layers, GELU, 4x
def make_mask(self, D, H, W, device):
img = torch.zeros(1, D, H, W, 1, device=device)
cnt = 0
for d in (slice(0, -self.ws[0]), slice(-self.ws[0], -self.shift[0]), slice(-self.shift[0], None)):
for h in (slice(0, -self.ws[1]), slice(-self.ws[1], -self.shift[1]), slice(-self.shift[1], None)):
for w in (slice(0, -self.ws[2]), slice(-self.ws[2], -self.shift[2]), slice(-self.shift[2], None)):
img[:, d, h, w] = cnt
cnt += 1
m = window_partition(img, self.ws).squeeze(-1) # (nW, N)
m = m[:, None, :] - m[:, :, None]
return m.masked_fill(m != 0, -100.0).masked_fill(m == 0, 0.0)
def forward(self, x): # x: (B, D, H, W, C). D, H, W are assumed to be multiples of the window
B, D, H, W, C = x.shape
s = x
x = self.norm1(x)
mask = None
if any(self.shift):
x = torch.roll(x, shifts=tuple(-v for v in self.shift), dims=(1, 2, 3)) # cyclic shift
mask = self.make_mask(D, H, W, x.device)
w = self.attn(window_partition(x, self.ws), mask)
x = window_reverse(w, self.ws, B, D, H, W)
if any(self.shift):
x = torch.roll(x, shifts=self.shift, dims=(1, 2, 3))
x = s + x # first line of Eq. (1)
return x + self.mlp(self.norm2(x)) # second line of Eq. (1)
# splitting into 2ร4ร4 3D patches plus the linear embedding equals a 3D convolution with kernel and stride 2ร4ร4
embed = nn.Conv3d(3, 96, kernel_size=(2, 4, 4), stride=(2, 4, 4))
blocks = nn.Sequential(VideoSwinBlock(shift=False), VideoSwinBlock(shift=True)) # a pair of blocks
blocks.eval() # if dropout or Stochastic Depth were added, they would be disabled here (use train() for training)
with torch.no_grad():
x = embed(torch.randn(1, 3, 32, 224, 224)).permute(0, 2, 3, 4, 1) # (1, 16, 56, 56, 96)
print(blocks(x).shape) # torch.Size([1, 16, 56, 56, 96])
FAQ
Q. How does the Video Swin Transformer differ from the image Swin Transformer?
A.
It extends the tokens and windows along the time axis as well. Tokens become 3D patches of 2 in time ร 4 in height ร 4 in width, windows become 3D boxes of 8 in time ร 7 in height ร 7 in width by default, and the window shift is applied along all three directions: time, height, and width. The relative position bias also becomes 3D. The stage hierarchy and patch merging (halving only space) are the same as in the Swin Transformer.
Q. Why is it more accurate than TimeSformer or ViViT even though it does not look at the whole video?
A.
In video, pixels that are close in time and space are more strongly related, so global self-attention can be well approximated with local windows. Since layers stack while the windows shift, information from a wide range still reaches the deeper layers. The lower computation makes it possible to use a design that attends to time and space jointly in the same layer, and in the paper the joint design (78.8%) beat designs that separate time and space (76.4% and 78.5%). Being able to start from the strong weights of the image Swin Transformer also helps.
Q. How are weights trained on images transferred to the video model?
A.
Only two places differ in shape. For the first linear embedding, since the input now spans 2 frames, the pretrained weights are duplicated twice and multiplied by 0.5. For the relative position bias, the pretrained table is duplicated 2Pโ1 times along time. All other weights can be used as is. The paper also tried the "center frame initialization" recommended by ViViT, but for Swin-T it gave the same 78.8% as inflation.