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 patches, the attention matrix has entries, so doubling the image side quadruples the number of patches and multiplies the attention cost by sixteen. A 224 by 224 image with patches gives 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 pixel image, with patches and window size . 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]
- Split the image into patches. Each pixel patch has raw numbers. The image becomes a grid of tokens. Check: numbers in total, which is the number of pixel values, .
- Embed the patches. A linear layer maps each 48-number patch to channels. The grid stays . Check: the token count is unchanged by embedding.
- Attend inside windows. Divide the grid into windows, each holding tokens. Each token attends only to the four tokens in its window. Check: a window contributes attention pairs, and there are four windows, so pairs in total. Global attention would need .
- 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.
- Merge patches. Concatenate each group of neighbouring tokens, giving numbers per location, and apply a linear layer to reduce this to . The grid becomes . Check: four tokens become one, so the resolution halves in each direction.
- 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 tokens with channels, and let each window hold 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. counts the multiply-add operations of a module. The cost of global multi-head self-attention, dropping the softmax, is
The cost of window-based attention is
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 is fixed.
Step 3 in symbols
Within a window, attention is computed on tokens. Here , and are the query, key and value matrices of the window's tokens, and is the dimension of the queries and keys. The relative position bias is an matrix, but it is gathered from a smaller learned table of size , because the relative offset along each axis lies between and . Attention in a window is
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
The residual connections carry the input forward through each module, as in residual networks.
Worked examples
A token grid with windows of .
- Tokens in the grid: .
- Global attention pairs: .
- Windows: , each of size tokens.
- Pairs per window: .
- Total windowed pairs: .
- Interpretation: windowing cuts the attention pairs by a factor of four in this tiny case, and the factor grows with the image size.
Use , which is the first stage of Swin-T for a by image with patches, with and . Then .
- Projection term, shared by both: .
- Global attention term: .
- Window attention term: .
- Global total: .
- Window total: .
- Ratio: .
- Interpretation: for this stage, global attention would cost about fourteen times as many operations, and the gap widens at larger image sizes.
The paper's COCO table compares Cascade Mask R-CNN with a ResNet-50 backbone and with Swin-T. The reported box AP is for ResNet-50 and for Swin-T. The FLOPs are G for ResNet-50 and G for Swin-T.
- AP gain: points.
- Extra FLOPs: G.
- Relative extra cost: , about percent.
- 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 token grid uses windows of tokens. How many attention pairs does windowed attention need in total, and how many times fewer is that than global attention?
Answer: there are windows, each with tokens and pairs, giving pairs. Global attention needs pairs, which is 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 percent top-1 accuracy at input against for DeiT-S. Swin-B reaches and percent at and input, against and for DeiT-B. With pre-training on ImageNet-22K, Swin-B reaches percent top-1 at 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 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 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 points of top-1 accuracy on ImageNet, box AP on COCO and mIoU on ADE20K. Relative position bias adds about points of top-1 accuracy over no position encoding and about 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 , 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 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.
- Section 1, Introduction. Motivates a general-purpose backbone and the cost of global attention. Needs Vision Transformer (ViT) and Convolutional Neural Network.
- Section 2, Related work. Covers ViT, DeiT and efficient attention. Needs Multi-Head Attention.
- Section 3.1, Overall architecture. Patch splitting, stages and patch merging. Needs Image Pyramid.
- Section 3.2, Shifted window self-attention. The core method and the complexity formulas. Needs Shifted Window Attention and Gaussian Error Linear Unit (GELU).
- Section 3.3, Architecture variants. The sizes Swin-T, S, B and L. Needs Layer Normalization and Residual Connection.
- Section 4, Experiments. ImageNet, COCO and ADE20K results. Needs Object Detection and Image Segmentation.
- Section 4.4, Ablations. Shifted windows and relative position bias. Read after Section 3.2.
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 tokens and windows of . How many attention pairs does windowed attention compute, and how many would global attention compute?Show answer
Windows: . Each window has tokens, so pairs per window, and in total. Global attention on tokens needs 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 , the attention term is proportional to the number of tokens . Global attention has the term , 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 points while FLOPs rise by about 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.