Search

Search papers and lessons

Shifted Window Attention

Level 4 · 10 min read

Shifted window attention lets each image patch attend only within a local window, then moves the window grid by half a window in the next layer, so information spreads at a cost that grows linearly with image size.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

Shifted window attention is a way to run a Transformer over an image without every patch looking at every other patch. The image's patch grid is cut into small square windows, and each patch attends only to the patches in its own window. In the next layer the window grid is moved by half a window, so patches that were separated by a window edge now share one.

The result is that the cost of attention grows in proportion to the number of patches, not with the square of it, while information still travels across the whole image as the layers stack up.

Builds on: Multi-Head Attention, Vision Transformer (ViT) · Leads to: the Swin Transformer backbone, used for classification, detection and segmentation

Where it's used

Image classification backbones. The Swin Transformer (Liu and colleagues, 2021) uses shifted windows in every stage of its network and reached strong accuracy on ImageNet classification. Because the backbone is a general feature extractor, the same network was then reused for other tasks.

Object detection and segmentation. The Swin paper reports results on COCO object detection and ADE20K semantic segmentation. These tasks need dense, high-resolution feature maps, where a global attention over all patches would be expensive, so the local windows are what make the model practical.

High-resolution images. A 448 by 448 image split into 4 by 4 pixel patches has 112×112=12,544112 \times 112 = 12{,}544 patches. Global attention would compare every patch with every other, which is over 157 million pairs for one attention map. Windows cut that to about 615 thousand pairs, as the worked examples show.

How it works

Here is one tiny instance. Take a grid of 4×4=164 \times 4 = 16 patches, numbered by row and column from (0,0)(0, 0) to (3,3)(3, 3). Use windows of size 2×22 \times 2.

  1. Layer one: cut the grid into four windows. The top-left window holds (0,0),(0,1),(1,0),(1,1)(0,0), (0,1), (1,0), (1,1), and the other three windows are the same size. Each patch attends only to the patches in its own window, itself included. Check: each of the 16 patches attends to 4 tokens, not 16.
  2. Count the work for layer one. Global attention scores all 16 patches against all 16, which is 16×16=25616 \times 16 = 256 pairs. Windowed attention scores 4 windows, each with 4×4=164 \times 4 = 16 pairs, which is 64 pairs. Check: 64/256=1/464 / 256 = 1/4, which is 1 divided by the 4 windows.
  3. Layer two: shift the window grid by one row and one column. The new windows now cover the centre of the old boundaries. One of them holds (1,1),(1,2),(2,1),(2,2)(1,1), (1,2), (2,1), (2,2). Check: (1,1)(1,1) and (2,2)(2,2) were in different windows in layer one, and they now share a window.
  4. Wrap-around and masks: patches on the far edges that the shift brings together are not really neighbours. The implementation moves the grid cyclically and then sets the attention scores between patches that should not see each other to a very negative value, so they get zero weight after the Softmax.
  5. Information flow: in layer one, patch (0,0)(0,0) sends information to (1,1)(1,1). In layer two, (1,1)(1,1) sends information to (2,2)(2,2). So after two layers, (0,0)(0,0) has influenced (2,2)(2,2), a patch it could never reach in one layer.
flowchart LR
  L1[Layer 1: windows at the grid origin] --> L2[Layer 2: windows shifted by half a window]
  L2 --> L3[Layer 3: back to the origin grid]
  L3 --> L4[Layer 4: shifted again]

The math

Definition: Windowed self-attention

Let the feature map be an h×wh \times w grid of tokens, each a vector of width dd. Partition the grid into non-overlapping M×MM \times M windows. Within one window with tokens X∈RM2×dX \in \mathbb{R}^{M^2 \times d}, compute Attn(X)=softmax ⁣(QK⊤d)V,Q=XWQ,  K=XWK,  V=XWV,\text{Attn}(X) = \text{softmax}\!\left(\frac{Q K^\top}{\sqrt{d}}\right) V, \qquad Q = X W_Q,\; K = X W_K,\; V = X W_V, and apply it to every window separately. Tokens in different windows never interact within one layer.

Step 1 in symbols

There are hM⋅wM\frac{h}{M} \cdot \frac{w}{M} windows, each with M2M^2 tokens. Each window computes an M2×M2M^2 \times M^2 score matrix, the matrix product of QQ and K⊤K^\top. The total number of pairs scored is hwM2⋅(M2)2=hw⋅M2.\frac{hw}{M^2} \cdot (M^2)^2 = hw \cdot M^2. Global attention scores (hw)2(hw)^2 pairs. The ratio of global to windowed pairs is (hw)2hw⋅M2=hwM2\frac{(hw)^2}{hw \cdot M^2} = \frac{hw}{M^2}. In the tiny example hw=16hw = 16 and M2=4M^2 = 4, so the ratio is 44, and the windowed count is 6464 against 256256.

Step 2 in symbols: the shift

In the shifted layer the grid is rolled cyclically by (⌊M/2⌋,⌊M/2⌋)\left(\lfloor M/2 \rfloor, \lfloor M/2 \rfloor\right). For M=2M = 2 that is (1,1)(1, 1). The windows are then applied to the rolled grid, which makes them straddle the old boundaries. The masking step sets the scores between patches that came from opposite edges of the grid to −∞-\infty before the softmax.

Step 3 in symbols: how far information travels

Stack layers that alternate regular and shifted windows. Each pair of layers lets information move across roughly one window boundary in each direction. The receptive field therefore grows with depth, while every single layer stays local. In the tiny example, two layers were enough for patch (0,0)(0,0) to reach (2,2)(2,2).

Worked examples

Example
Tiny: a 4 by 4 grid with 2 by 2 windows

Setup: h=w=4h = w = 4, M=2M = 2, so hw=16hw = 16 tokens and M2=4M^2 = 4 tokens per window.

  1. Number of windows: 42×42=4\frac{4}{2} \times \frac{4}{2} = 4.
  2. Pairs per window: 4×4=164 \times 4 = 16.
  3. Total windowed pairs: 4×16=644 \times 16 = 64.
  4. Global pairs: 16×16=25616 \times 16 = 256.
  5. Ratio: 256/64=4256 / 64 = 4, which matches hw/M2=16/4hw / M^2 = 16 / 4.
  6. Interpretation: windowing saved a factor of 4 here. The saving is larger on bigger grids, because the global count grows with the square of the number of tokens.
Example
Standard: a 224 by 224 image in the Swin stage-one layout

Setup: a 224×224224 \times 224 image with 4×44 \times 4 patches gives a grid of 56×5656 \times 56, so hw=3,136hw = 3{,}136 tokens. The window size is M=7M = 7, so each window has 4949 tokens.

  1. Number of windows: 567×567=8×8=64\frac{56}{7} \times \frac{56}{7} = 8 \times 8 = 64.
  2. Global pairs: 3,1362=9,834,4963{,}136^2 = 9{,}834{,}496.
  3. Windowed pairs: 3,136×49=153,6643{,}136 \times 49 = 153{,}664.
  4. Ratio: 9,834,496/153,664=649{,}834{,}496 / 153{,}664 = 64. Check: 153,664×64=9,834,496153{,}664 \times 64 = 9{,}834{,}496.
  5. Interpretation: the ratio equals the number of windows, because each window is 1/641/64 of the grid. The windowed layer does about 64 times less attention work than a global layer on this image.
Example
Realistic: a 448 by 448 image for segmentation

Setup: dense prediction such as segmentation needs a larger input, here 448×448448 \times 448 with 4×44 \times 4 patches. The grid is 112×112112 \times 112, so hw=12,544hw = 12{,}544 tokens. The window size is M=7M = 7.

  1. Global pairs per attention map: 12,5442=157,351,93612{,}544^2 = 157{,}351{,}936.
  2. Windowed pairs per attention map: 12,544×49=614,65612{,}544 \times 49 = 614{,}656.
  3. Ratio: 157,351,936/614,656=256157{,}351{,}936 / 614{,}656 = 256. Check: 614,656×256=157,351,936614{,}656 \times 256 = 157{,}351{,}936.
  4. Alternatively, the ratio is hw/M2=12,544/49=256hw / M^2 = 12{,}544 / 49 = 256.
  5. Interpretation: doubling the side length of the image quadruples the number of tokens, so global attention cost goes up sixteen-fold. Windowed cost goes up only four-fold. For a dense task the difference decides whether the model fits in memory.

Try it: the same model on an 896×896896 \times 896 image with 4×44 \times 4 patches and M=7M = 7. How many times fewer pair scores does windowed attention compute than global attention, for one attention map? Answer: the grid is 224×224224 \times 224, so hw=50,176hw = 50{,}176. The ratio is hw/M2=50,176/49=1,024hw / M^2 = 50{,}176 / 49 = 1{,}024.

Common mistakes and tradeoffs

It is tempting to think that a windowed layer can see the whole image. In fact it sees only its own window. Global information arrives only after several layers, which is why the window grid is shifted in alternate layers and why the network is built as a stack.

It is tempting to think that every layer should use the shifted grid. In fact the regular and shifted layers alternate. The pair of grids is what lets a patch exchange information with neighbours on both sides of a window edge; a stack of shifted layers alone would repeat the same boundary pattern, so the design uses the two grids in turn.

It is tempting to think that the cyclic shift can be implemented without masks. In fact the shift wraps patches from opposite edges into the same window. Without masks those patches would attend to each other, which is wrong. The masks make the wrap-around invisible to the attention.

Use shifted windows when the input is large, the task needs dense outputs, and you want cost that grows linearly with the number of patches. Do not use them when a single layer must relate patches that are far apart, such as a short global summary of a small image; then global attention is simpler, and for small inputs its cost is acceptable. The window size is also a design choice: a bigger MM sees more in each layer but costs more.

History

Transformers were first built for text, where every token attends to every other. The Vision Transformer (ViT) (Dosovitskiy and colleagues, 2020) showed that the same design works on images if the image is cut into patches and each patch is treated as a token. That model used global attention, so its cost grew with the square of the number of patches, which is costly at high resolution.

Swin (Liu and colleagues, 2021) answered this problem with local windows and a shift between layers. It also merged neighbouring patches between stages to build a hierarchy, similar to the feature maps of convolutional networks. The shifted window idea caught on because it kept the flexibility of attention while making dense image tasks practical.

Recap

  • A window is a small square of patches; attention inside it costs far less than attention over the whole image.
  • Shifting the window grid by half a window in alternate layers lets information cross window boundaries.
  • Masks are needed because the shift wraps patches from opposite edges into one window.
  • For a grid of hwhw tokens and window size MM, the saving over global attention is hw/M2hw / M^2.
  • Read next: Sliding Window Attention, which uses a similar local idea for text, and the Swin Transformer, where the idea is used as a full backbone.

Check yourself

QuestionIn one windowed layer, which other tokens can a token attend to?Show answer

Only the tokens in its own window, itself included. Tokens in other windows are invisible in that layer, so information must cross window boundaries over several layers.

QuestionA grid has 36 tokens and windows of size 3 by 3. How many tokens are in each window, and how many windows are there?Show answer

Each window holds 3×3=93 \times 3 = 9 tokens. There are 36/9=436 / 9 = 4 windows, arranged as a 2×22 \times 2 grid of windows.

QuestionFor the grid in the previous question, how many pair scores does one windowed layer compute, compared with a global layer?Show answer

Windowed: 44 windows, each with 9×9=819 \times 9 = 81 pairs, giving 324324. Global: 36×36=1,29636 \times 36 = 1{,}296. The ratio is 1,296/324=41{,}296 / 324 = 4, which equals hw/M2=36/9hw / M^2 = 36 / 9.

QuestionWhy does the shifted layer need attention masks, and what goes wrong without them?Show answer

The cyclic shift places patches from opposite edges of the grid into the same window. They are not neighbours in the image, so letting them attend to each other would mix unrelated regions. The masks set those scores to a very negative value so the softmax gives them zero weight.

QuestionA detection model takes 800 by 800 images with 4 by 4 patches and uses 7 by 7 windows. Roughly how many times fewer pair scores does one windowed layer compute than one global layer?Show answer

The grid is 200×200200 \times 200, so hw=40,000hw = 40{,}000 tokens. The ratio is hw/M2=40,000/49≈816hw / M^2 = 40{,}000 / 49 \approx 816, so windowed attention computes about 816 times fewer pair scores.

Sources