Search

Search papers and lessons

Swin Transformer: Hierarchical Vision Transformer using Shifted Windows

Ze Liu, Yutong Lin, Yue Cao et al. · 2021

Liu et al. (2021) make a vision transformer hierarchical and local: attention runs inside small windows that shift between layers, so cost grows linearly with image size.

On this page

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

TL;DR

The Swin Transformer is a vision backbone built from transformer blocks, but its attention runs only inside small local windows, and the windows shift between consecutive blocks so that neighbouring windows can exchange information. Its feature maps are also hierarchical: patches are merged as the network gets deeper, as in a CNN. Together these make the cost grow linearly with image size instead of quadratically, and let one backbone serve classification, detection and segmentation. It improved on DeiT at similar cost and reached state-of-the-art detection results on COCO at the time.

Builds on: Vision Transformer (ViT), Multi-Head Attention, Gaussian Error Linear Unit (GELU), Layer Normalization · Leads to: Object Detection, Image Segmentation

Why it mattered

The Vision Transformer (ViT) showed that a plain transformer applied to image patches could match convolutional networks on large datasets, but it produced one low-resolution feature map with attention over every pair of patches. That design suits classification and is awkward for dense tasks such as Object Detection and Image Segmentation, which need several resolutions and large images.

Swin brought the two ideas together. Its hierarchy resembles the feature pyramids that detectors use, so it can replace a ResNet backbone in standard detection frameworks without redesigning them. Its local attention keeps the cost manageable at high resolution. Swin became one of the most widely used backbones for vision tasks after 2021.

History

ViT was posted in 2020 and showed that transformers could classify images when trained on large data. DeiT in 2021 made the same architecture trainable on ImageNet alone with distillation and heavy augmentation. Both used global attention with a single feature resolution. Swin was posted to arXiv in March 2021 and appeared at ICCV 2021, and it showed that a hierarchical, locally attentive design could beat DeiT on the same tasks at similar cost.

The problem

Global self-attention compares every token with every other token. For an image split into NN patches, the attention matrix has N×NN \times N entries, so doubling the image side quadruples the number of patches and multiplies the attention cost by sixteen. A 224 by 224 image with 4×44 \times 4 patches gives 31363136 tokens, which makes global attention costly in both time and memory. Dense tasks run at larger sizes still.

Two further problems follow. A single low-resolution map loses the fine detail that detection of small objects needs. And windowed attention, which computes attention only inside fixed blocks, is cheap but leaves the blocks isolated from each other, so information cannot cross a block boundary. Swin keeps the cheapness of windows and adds a mechanism for crossing them.

How it works

The walkthrough uses a tiny 16×1616 \times 16 pixel image, with 4×44 \times 4 patches and window size M=2M = 2. It follows the data through one stage, one merge and one pair of blocks. Each "block" is a multi-head self-attention layer followed by a small feed-forward network, both wrapped in residual connections.

flowchart LR
  A[16 by 16 image] --> B[Split into 4 by 4 patches: 4 by 4 grid]
  B --> C[Linear embedding to C channels]
  C --> D[Block: window attention]
  D --> E[Block: shifted window attention]
  E --> F[Patch merging to 2 by 2 grid]
  F --> G[Stage 2 blocks at lower resolution]
  1. Split the image into patches. Each 4×44 \times 4 pixel patch has 4×4×3=484 \times 4 \times 3 = 48 raw numbers. The image becomes a 4×44 \times 4 grid of 1616 tokens. Check: 16×48=76816 \times 48 = 768 numbers in total, which is the number of pixel values, 16×16×316 \times 16 \times 3.
  2. Embed the patches. A linear layer maps each 48-number patch to CC channels. The grid stays 4×44 \times 4. Check: the token count is unchanged by embedding.
  3. Attend inside windows. Divide the 4×44 \times 4 grid into 2×22 \times 2 windows, each holding 2×2=42 \times 2 = 4 tokens. Each token attends only to the four tokens in its window. Check: a window contributes 4×4=164 \times 4 = 16 attention pairs, and there are four windows, so 6464 pairs in total. Global attention would need 16×16=25616 \times 16 = 256.
  4. Shift the windows. The next block moves the window grid by one token in each direction (half a window), so the new windows straddle the old boundaries. This is the shifted window step. Check: a token on the edge of one old window now shares a window with tokens from the neighbouring old window.
  5. Merge patches. Concatenate each 2×22 \times 2 group of neighbouring tokens, giving 4C4C numbers per location, and apply a linear layer to reduce this to 2C2C. The grid becomes 2×22 \times 2. Check: four tokens become one, so the resolution halves in each direction.
  6. Repeat at the next stage. The same blocks run on the smaller grid with twice the channels, which keeps the cost per stage roughly similar.

The shifted windows in step 4 are the paper's key idea. Without them, a token would only ever attend to tokens inside its own fixed window, and information would cross a window boundary only through the merging layers, which are few and far apart. The shift gives cross-window information in every second block.

The math

Let the feature map have h×wh \times w tokens with CC channels, and let each window hold M×MM \times M tokens. MSA is multi-head self-attention, W-MSA is the same operation run inside windows, and SW-MSA is W-MSA on shifted windows. Ω(⋅)\Omega(\cdot) counts the multiply-add operations of a module. The cost of global multi-head self-attention, dropping the softmax, is

Ω(MSA)=4hwC2+2(hw)2C.\Omega(\text{MSA}) = 4hwC^2 + 2(hw)^2 C.

The cost of window-based attention is

Ω(W-MSA)=4hwC2+2M2hwC.\Omega(\text{W-MSA}) = 4hwC^2 + 2M^2 hwC.

The first term covers the linear projections, and the second covers the attention matrix. The attention term grows as the square of the token count for global attention and linearly for windows when MM is fixed.

Step 3 in symbols

Within a window, attention is computed on M2M^2 tokens. Here QQ, KK and VV are the query, key and value matrices of the window's tokens, and dd is the dimension of the queries and keys. The relative position bias BB is an M2×M2M^2 \times M^2 matrix, but it is gathered from a smaller learned table B^\hat{B} of size (2M−1)×(2M−1)(2M - 1) \times (2M - 1), because the relative offset along each axis lies between −M+1-M + 1 and M−1M - 1. Attention in a window is

Attention(Q,K,V)=SoftMax ⁣(QK⊤d+B)V.\text{Attention}(Q, K, V) = \text{SoftMax}\!\left(\frac{QK^\top}{\sqrt{d}} + B\right) V.

Step 4 in symbols

Blocks come in consecutive pairs. The first uses regular windows and the second uses shifted windows. Here LN is layer normalisation, and MLP is the two-layer feed-forward network with GELU between its layers. A pair of blocks is

z^l=W-MSA(LN(zl−1))+zl−1,zl=MLP(LN(z^l))+z^l,z^l+1=SW-MSA(LN(zl))+zl,zl+1=MLP(LN(z^l+1))+z^l+1.\begin{aligned} \hat{\mathbf{z}}^{l} &= \text{W-MSA}\big(\text{LN}(\mathbf{z}^{l-1})\big) + \mathbf{z}^{l-1}, \\ \mathbf{z}^{l} &= \text{MLP}\big(\text{LN}(\hat{\mathbf{z}}^{l})\big) + \hat{\mathbf{z}}^{l}, \\ \hat{\mathbf{z}}^{l+1} &= \text{SW-MSA}\big(\text{LN}(\mathbf{z}^{l})\big) + \mathbf{z}^{l}, \\ \mathbf{z}^{l+1} &= \text{MLP}\big(\text{LN}(\hat{\mathbf{z}}^{l+1})\big) + \hat{\mathbf{z}}^{l+1}. \end{aligned}

The residual connections carry the input forward through each module, as in residual networks.

Worked examples

Example
1. Attention pairs in the tiny grid (tiny)

A 4×44 \times 4 token grid with windows of 2×22 \times 2.

  1. Tokens in the grid: 4×4=164 \times 4 = 16.
  2. Global attention pairs: 16×16=25616 \times 16 = 256.
  3. Windows: (4/2)2=4(4 / 2)^2 = 4, each of size 2×2=42 \times 2 = 4 tokens.
  4. Pairs per window: 4×4=164 \times 4 = 16.
  5. Total windowed pairs: 4×16=644 \times 16 = 64.
  6. Interpretation: windowing cuts the attention pairs by a factor of four in this tiny case, and the factor grows with the image size.
Example
2. Cost of one stage at Swin-T size (standard)

Use h=w=56h = w = 56, which is the first stage of Swin-T for a 224224 by 224224 image with 4×44 \times 4 patches, with C=96C = 96 and M=7M = 7. Then hw=3136hw = 3136.

  1. Projection term, shared by both: 4hwC2=4×3136×9216=115,605,5044hwC^2 = 4 \times 3136 \times 9216 = 115{,}605{,}504.
  2. Global attention term: 2(hw)2C=2×31362×96=1,888,223,2322(hw)^2 C = 2 \times 3136^2 \times 96 = 1{,}888{,}223{,}232.
  3. Window attention term: 2M2hwC=2×49×3136×96=29,503,4882M^2 hwC = 2 \times 49 \times 3136 \times 96 = 29{,}503{,}488.
  4. Global total: 115,605,504+1,888,223,232=2,003,828,736115{,}605{,}504 + 1{,}888{,}223{,}232 = 2{,}003{,}828{,}736.
  5. Window total: 115,605,504+29,503,488=145,108,992115{,}605{,}504 + 29{,}503{,}488 = 145{,}108{,}992.
  6. Ratio: 2,003,828,736/145,108,992≈13.82{,}003{,}828{,}736 / 145{,}108{,}992 \approx 13.8.
  7. Interpretation: for this stage, global attention would cost about fourteen times as many operations, and the gap widens at larger image sizes.
Example
3. Backbone choice in a detector (realistic)

The paper's COCO table compares Cascade Mask R-CNN with a ResNet-50 backbone and with Swin-T. The reported box AP is 46.346.3 for ResNet-50 and 50.550.5 for Swin-T. The FLOPs are 739739 G for ResNet-50 and 745745 G for Swin-T.

  1. AP gain: 50.5−46.3=4.250.5 - 46.3 = 4.2 points.
  2. Extra FLOPs: 745−739=6745 - 739 = 6 G.
  3. Relative extra cost: 6/739≈0.00816 / 739 \approx 0.0081, about 0.80.8 percent.
  4. Interpretation: most of the detection gain comes at almost no extra computation, which is why the backbone swap is attractive in practice.

Try it: a 32×3232 \times 32 token grid uses windows of 4×44 \times 4 tokens. How many attention pairs does windowed attention need in total, and how many times fewer is that than global attention?

Answer: there are (32/4)2=64(32/4)^2 = 64 windows, each with 1616 tokens and 16×16=25616 \times 16 = 256 pairs, giving 64×256=16,38464 \times 256 = 16{,}384 pairs. Global attention needs 10242=1,048,5761024^2 = 1{,}048{,}576 pairs, which is 1,048,576/16,384=641{,}048{,}576 / 16{,}384 = 64 times more.

Results

Swin comes in four sizes, Swin-T, -S, -B and -L (tiny, small, base and large). On ImageNet-1K with regular training, Swin-T reaches 81.381.3 percent top-1 accuracy at 2242224^2 input against 79.879.8 for DeiT-S. Swin-B reaches 83.583.5 and 84.584.5 percent at 2242224^2 and 3842384^2 input, against 81.881.8 and 83.183.1 for DeiT-B. With pre-training on ImageNet-22K, Swin-B reaches 86.486.4 percent top-1 at 3842384^2 input after fine-tuning.

On COCO, Swin-T improves box AP (average precision for bounding boxes) over a ResNet-50 backbone in four detection frameworks. With Cascade Mask R-CNN the improvement is 4.24.2 points, as in the worked example. On ADE20K segmentation, Swin beats DeiT under the same segmentation head, and the largest model with ImageNet-22K pre-training reaches 53.553.5 mIoU (mean intersection over union) on the validation set.

The ablations isolate the design choices. Shifted windows, compared with a single fixed partition at each stage, add 1.11.1 points of top-1 accuracy on ImageNet, 2.82.8 box AP on COCO and 2.82.8 mIoU on ADE20K. Relative position bias adds about 1.21.2 points of top-1 accuracy over no position encoding and about 0.80.8 over absolute position embedding.

The limits are stated or implied in the paper. The strongest results need large-scale pre-training. The window size is a fixed design choice, set to 77, and the relative position table must be interpolated when fine-tuning at a different window size. Speed numbers depend on the GPU and implementation used.

Common mistakes and tradeoffs

It is tempting to think Swin is a convolutional network because it has a hierarchy and local windows. In fact it is built from attention blocks and multi-layer perceptrons, and the locality comes from the window partition, not from a learned convolution kernel.

It is tempting to think the shifted windows are a sliding window, computed at every position. In fact the paper uses a cyclic shift of the feature map, which keeps the number of windows the same as in the regular partition. A true sliding window, with a fresh window centred on every token, would multiply the work and is what the cyclic shift avoids.

It is tempting to think patch merging is simple pooling. In fact it is a learned linear layer over the concatenated features of each 2×22 \times 2 group, so the network chooses how to combine them.

It is tempting to think global attention is always better because it sees everything. In fact the paper finds that the locality and the hierarchy help on dense tasks, and the translation-like inductive bias of local windows helps detection and segmentation.

When to use Swin: dense prediction, high-resolution images, and tasks that need a multi-scale backbone. When not to use it: when data and pre-training are too scarce for a transformer, or when a small, fast CNN is the right tool. Alternatives include ViT for classification at a single scale, and convolutional backbones such as ResNet when deployment cost matters most.

Reading guide

Read the paper in this order, with the lessons that cover what each section needs.

Check yourself

QuestionWhy does the Swin Transformer alternate regular and shifted windows between consecutive blocks?Show answer

Attention inside a fixed window never sees tokens in neighbouring windows. Shifting the partition by half a window in the next block makes the new windows straddle the old boundaries, so information can cross between neighbouring windows in every second block, without paying for global attention.

QuestionA feature map has h=w=8h = w = 8 tokens and windows of M=4M = 4. How many attention pairs does windowed attention compute, and how many would global attention compute?Show answer

Windows: (8/4)2=4(8/4)^2 = 4. Each window has 1616 tokens, so 16×16=25616 \times 16 = 256 pairs per window, and 4×256=10244 \times 256 = 1024 in total. Global attention on 6464 tokens needs 64×64=409664 \times 64 = 4096 pairs, which is four times as many.

QuestionWhy does the cost of window attention grow linearly with image size, while global attention grows quadratically?Show answer

With a fixed window size MM, the attention term 2M2hwC2M^2 hwC is proportional to the number of tokens hwhw. Global attention has the term 2(hw)2C2(hw)^2 C, which is proportional to the square of the number of tokens, so doubling the image side quadruples the token count and multiplies the global attention cost by sixteen.

QuestionIn the paper's Swin-T detection comparison, the box AP rises by 4.24.2 points while FLOPs rise by about 0.80.8 percent. Why is this a useful result for choosing a backbone?Show answer

It shows that most of the accuracy gain does not come from more computation. A backbone with a similar cost and a large accuracy gain is a strong practical choice, which is why the swap is attractive in detection frameworks that were built around ResNet backbones.

Sources

Read the full paper

Ze Liu, Yutong Lin, Yue Cao et al., 2021. arXiv:2103.14030