Skip to content

Attention over space and time: non-local blocks and video transformers

Let every space-time position attend to every other (non-local blocks), then attend more cheaply: across time then space (TimeSformer), in tubelets (ViViT), with pooled keys (MViT) or in shifted windows.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write a non-local block and say what it costs
  • Compare full, divided and windowed space-time attention by the number of token pairs
  • Explain tubelet tokens and what a large tubelet averages away
  • Say why attention to a distant frame isn't proof the model reasons about time

Read first

01

Every position, every frame

Read
Reference · VID007 · Explained hereNon-local Neural Networks for VideoAdds interactions between distant space-time positions so evidence need not travel only through local convolutional neighborhoods.

A convolution only sees a neighborhood. A non-local blockNon-local blockA layer where every position in a clip takes a weighted average of all positions, in every frame, then adds it back. lets each position ii in a clip average the features of all positions jj, in every frame, weighted by how similar they are:

yi=1C(x)∑jf(xi,xj) g(xj),y_i = \frac{1}{C(x)} \sum_j f(x_i, x_j)\, g(x_j),

and adds the result back through a residual connection. With softmax weights this is self-attentionSelf-attentionEach token builds its next value as a weighted mix of all tokens, with weights from how well their keys match its query.. In the reference's three-position toy, the position that resembles both others ends up with 0.788 in both features: an even mix.

Attention weights, masks and heads on a handful of tokens.

DExplorable · Attention: scores, masks and heads

Where does each word look, and what do the scaling and the masks change?

With this mask, how much of each word's attention lands on <pad>?

How sure?
6
2

How many of the positions are <pad>.

Width d

Heads

Mask

Without masks or positions the output rows shuffle the same way.

.51.22.16.11.00.00.27.55.07.10.00.00.02.10.59.28.00.00.26.71.02.01.00.00.09.09.69.13.00.00.42.54.03.01.00.00thecatsaton<pad><pad>thecatsaton<pad><pad>
  • Little weight
  • Most weight
  • Masked: score set to −∞

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Count the pairs

Read

A clip of TT frames, each cut into PP patches, gives TPTP tokens. Full attention compares every token with every other: (TP)2(TP)^2 pairs.

Divided space-time attentionDivided space-time attentionAttend across time at each patch location, then across space within each frame, instead of over all tokens at once. (TimeSformer) splits that in two. First each token attends to the same patch location in the other frames (TT partners); then to the other patches in its own frame (PP partners). That costs TP(T+P)TP(T + P) pairs.

Reference · VID010 · Explained hereTimeSformerApplies transformer attention to video patches, with divided temporal and spatial attention as an effective design.
03

How much cheaper?

Predict

Predict first

A clip has 16 frames of 196 patches each. Roughly how many fewer token pairs does divided attention compare than full attention?

About the sameAbout 2 times fewer pairsAbout 15 times fewer pairsAbout 200 times fewer pairs
Reveal

About 15 times fewer. Full attention compares (16⋅196)2(16 \cdot 196)^2 pairs, close to ten million. Divided attention compares 16⋅196⋅(16+196)16 \cdot 196 \cdot (16 + 196), about two-thirds of a million. The ratio is TP/(T+P)TP/(T+P): it grows as clips get longer.

04

Divided attention in the toy

Read

In the reference's program, a two-frame, two-patch clip passes through temporal attention and then spatial attention; the first token comes out as 0.411 and 0.536.

A patch location isn't an object. When a hand moves, it crosses patch locations, and temporal attention at one location follows the location, not the hand.

05

Tubelets as tokens

Read
Reference · VID011 · Explained hereViViTUses video tubelets and transformer factorization strategies to encode space-time information. It offers a systematic family of video-transformer designs, including separate spatial and temporal processing, for studying…

ViViT cuts the clip into tubeletsTubeletA small block of pixels spanning a few frames, flattened and projected into one token for a video transformer.: small blocks of pixels spanning several frames, each flattened and projected to one token, plus a position embedding. It then compares factorized designs, such as a spatial encoder followed by a temporal one.

In the reference's toy, two-frame tubelets are projected by averaging matching pixels: the first token is 1 and 2, the mean of its two frames. Fewer tokens, less memory, but motion within a tubelet is averaged away.

Patches become tokens; positions keep their order.

DExplorable · Vision transformer patches

How does a transformer read an image, and what does it lose without positions?

Image

Image size

Patch size P

A patch size that doesn't divide the image cuts off its border.

8

Each patch becomes a vector of this many numbers.

16 patches

The sequence the transformer reads; numbers are each patch's place in the image

0123456789101112131415

Attention pairs for each patch size (log scale)

2 × 265,5364 × 44,0967 × 72568 × 825616 × 1616

Score 1.5622 · change when shuffled 0.1421

Tokens
16
Attention pairs
256
Embedding weights
520
Pixels dropped
0
Score
1.5622
Change when shuffled
0.1421
  • Puzzle: Pick an image size and patch size that cut off part of the image.
32 × 32 pixels in 8 × 8 patches make 16 tokens, so attention compares 256 pairs. With position embeddings, shuffling the patches changes the score by 0.1421.

32 × 32 pixels in 8 × 8 patches make 16 tokens, so attention compares 256 pairs. With position embeddings, shuffling the patches changes the score by 0.1421.

06

Pooled keys and shifted windows

Read
Reference · VID012 · Explained hereMultiscale Vision Transformers (MViT)Builds a hierarchical video representation by reducing token resolution while increasing channel capacity. Pooling inside attention creates multiple scales, making long space-time inputs more manageable than a…

Pooling attentionPooling attentionAverage-pool the queries, keys or values inside attention, so later layers work on fewer, wider tokens. (MViT) pools keys and values before attention: in the reference's toy, 4 queries attend to only 2 pooled keys. Stages trade resolution for channels.

Reference · VID013 · Explained hereVideo Swin TransformerRestricts attention to local 3D windows and alternates shifted windows so information crosses window boundaries.

Shifted 3D window attentionShifted 3D window attentionAttention inside small space-time windows, with the windows shifted every other layer so information crosses their borders. (Video Swin) attends inside small space-time windows and shifts them every other layer. The shift wraps around: the reference's last shifted window pairs token 7 with token 0, the two ends of the clip. An attention maskAttention maskBlocks some query–key pairs before the softmax, such as future tokens (causal) or padding, so they get zero weight. must keep them apart.

07

Attention isn't an explanation

Read

A video transformer that attends to a frame far away hasn't proved it reasons about time. Background shortcuts are still available, and attention weights are one quantity inside a large computation.

Two checks are worth more:

  • a shuffled-frame controlShuffled-frame controlScore the model again on clips with their frames in random order. If accuracy barely drops, it isn't using motion.: score clips with frames in random order;
  • memory and accuracy at several clip lengths, since costs and sampling interact.
08

What runs here

Read
EntryIn CodeSplash
VID007 · Non-local Neural Networks for VideoExplained here
VID010 · TimeSformerExplained here
VID011 · ViViTExplained here
VID012 · Multiscale Vision Transformers (MViT)Explained here
VID013 · Video Swin TransformerExplained here
09

Check: video transformers

Checkpoint

Check yourself

What does a non-local block add to a convolutional video network?

Show the answer

Answer: a

It lets distant frames and places interact in one layer, at a cost that grows with the square of the number of positions.

Check yourself

How would you show that a non-local block helps?

Show the answer

Answer: b

The fair comparison is the same network with and without the block, at the same budget.

Check yourself

In divided space-time attention, what does the temporal step attend over?

Show the answer

Answer: b

Temporal attention links one location across frames; spatial attention then mixes patches within a frame.

Check yourself

Temporal attention in TimeSformer links one patch location across frames. Is that tracking an object?

Show the answer

Answer: b

It follows places, not things. Moving objects pass through different patches.

Check yourself

A ViViT model uses tubelets that span eight frames. What is a risk?

Show the answer

Answer: b

Longer tubelets mean fewer tokens and lose fine motion within each one.

Check yourself

How should two ViViT factorizations be compared?

Show the answer

Answer: a

Budgets must match, and motion-heavy and appearance-heavy datasets show different things.

Check yourself

What does MViT pool, and what can it cost?

Show the answer

Answer: b

Fewer tokens save memory, but pooling early can remove the small, fast things you want to recognize.

Check yourself

As an MViT network goes deeper, how do its tokens change?

Show the answer

Answer: b

Pooling shrinks resolution stage by stage while widening features, like a CNN's pyramid. Report memory and accuracy at several clip lengths to see what it buys.

Check yourself

Video Swin shifts its windows every other layer. Why does it need an attention mask?

Show the answer

Answer: b

Without a mask, the wrapped window mixes the first and last frames, which aren't neighbors.

Check yourself

What limits a windowed video transformer, even with shifted windows?

Show the answer

Answer: b

Windows keep cost down by keeping attention local; long-range structure must be built up layer by layer. Test it with long-range action controls.

10

Recap

Recap
  • A non-local block is attention over all space-time positions, with a residual.
  • Full attention costs (TP)2(TP)^2 pairs; divided attention TP(T+P)TP(T+P); windows and pooling cut it further.
  • Tubelets make fewer tokens and average away fast motion inside them.
  • Shifted windows need a mask; attention maps aren't explanations. Use shuffled-frame controls.

Concepts in this lesson