# Swin Transformer: Hierarchical Vision Transformer using Shifted Windows

Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang and 2 more · arXiv · 2021-3-25

- **Problem** Global self-attention costs grow quadratically with image size and a plain Transformer yields one low-resolution feature map, so it is hard to use as a backbone for dense vision tasks at high resolution.
- **Method** Self-attention runs inside windows of 7×7 patches, the window grid is shifted between consecutive blocks so neighbouring windows exchange information, and the shifted windows are batched with a cyclic shift and mask instead of padding.
- **Results** Swin-T reached 81.3 top-1 on ImageNet-1K at 224 input, against 79.8 for DeiT-S. Swin-L pre-trained on ImageNet-22K reached 87.3 top-1 at 384 input.

![Figure 2: An illustration of the shifted window approach for com- puting self-attention in the proposed Swin Transformer architec- ture. In layer l (left), a r…](https://refivu.com/papers/d2c6b7fa-f256-44cf-9328-c55d713768da/figures/figure-0512e888f1418f79aecf67c685c8e910.png?thumb=512)

**Figure 2** . An illustration of the shifted window approach for com- puting self-attention in the proposed Swin Transformer architec- ture. In layer l (left), a regular window partitioning scheme is adopted, and self-attention is computed within each window. In the next layer l + 1 (right), the window partitioning is shifted, re- sulting in new windows. The self-attention computation in the new windows crosses the boundaries of the previous windows in layer l, providing connections among them.

[Original paper](https://arxiv.org/abs/2103.14030v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo · Swin Transformer: Hierarchical Vision Transformer using Shifted Windows · Original paper figure · Extracted the figure area from page 2 of the original PDF.

## Why global attention does not fit dense vision

The Transformer succeeded in language by modelling long-range dependencies with attention, and the open question is whether that design carries over to vision as a general backbone. The authors point to two gaps between the domains. Visual entities vary widely in scale, whereas the tokens of earlier vision Transformers all share one fixed scale, and an image holds far more pixels than a passage holds words.

Global self-attention relates every token to every other token, so its cost depends on the square of the number of patches. For an h×w patch grid with C channels, the paper writes the global cost and the window-based cost as follows. \\\[ \\Omega(\\text{MSA}) = 4hwC^2 + 2(hw)^2C, \\qquad \\Omega(\\text{W-MSA}) = 4hwC^2 + 2M^2hwC \\\] With the window size M fixed, the window-based cost grows linearly in hw, which is why the authors treat global attention as unaffordable for large hw.

The window size M is set to 7 by default.

Windows alone cut off every path between neighbouring windows, which limits what a block can model, so the design needs a way to reconnect them. Dense prediction also needs feature maps at several resolutions, which a single-resolution Transformer does not provide.

Figure 1 contrasts the two designs: Swin builds maps by merging patches in deeper layers, while earlier vision Transformers keep one resolution with quadratic cost.

## How the hierarchy is built

The image is split into non-overlapping patches of 4×4 pixels, so each patch feature has 4×4×3 = 48 raw values. A linear embedding projects each patch to a width C. Swin Transformer blocks then act on these tokens without changing their number, and this part together with the embedding forms Stage 1 at H/4 × W/4 tokens.

Each later stage starts with a patch merging layer that concatenates each 2×2 group of neighbouring patch features into a 4C-dimensional vector and projects it linearly to 2C. Every merge halves the resolution, giving H/8 × W/8 in Stage 2, H/16 × W/16 in Stage 3 and H/32 × W/32 in Stage 4.

Inside each stage, a Swin Transformer block replaces the standard multi-head self-attention of a Transformer block with the shifted window module, and keeps the other parts of the block unchanged. A block is a shifted window MSA module followed by a two-layer MLP with GELU between the layers. Layer normalization comes before each module and a residual connection after each module.

Figure 3 shows the four-stage Swin-T layout and the two successive blocks whose regular and shifted attention alternate.

The stages give the same feature map resolutions as convolutional networks such as VGG and ResNet, so the design can replace their backbones in existing detection and segmentation pipelines.

## Shifted windows connect neighbouring windows

Figure 2 illustrates the idea. In layer l the feature map is partitioned into regular windows, and in the next layer the partition is displaced, so the new windows cross the borders of the earlier ones. In the worked example, an 8×8 feature map is split into 2×2 windows of size 4×4 (M = 4). The next block displaces the partition by \\(\\lfloor M/2 \\rfloor\\) pixels along each axis.

Consecutive blocks alternate between the regular module W-MSA and the shifted module SW-MSA, each with a residual connection and an MLP that is also preceded by layer normalization. \\\[ \\hat z^{l} = \\text{W-MSA}(\\text{LN}(z^{l-1})) + z^{l-1}, \\quad z^{l} = \\text{MLP}(\\text{LN}(\\hat z^{l})) + \\hat z^{l} \\\] \\\[ \\hat z^{l+1} = \\text{SW-MSA}(\\text{LN}(z^{l})) + z^{l}, \\quad z^{l+1} = \\text{MLP}(\\text{LN}(\\hat z^{l+1})) + \\hat z^{l+1} \\\] Here \\(\\hat z^{l}\\) and \\(z^{l}\\) are the outputs of the (S)W-MSA module and of the MLP module of block l.

The shifted partition is not only a modelling device. Every query patch in a window shares one key set, so memory access is regular in hardware. Sliding-window self-attention, by contrast, gives each query pixel a different key set, which the authors report as high latency on general hardware. The ablation shows that removing the shift lowers accuracy on all three tasks, so the shift contributes to the result.

## Batching shifted windows with a cyclic shift

Figure 4 illustrates the batched computation. The shifted partition produces more windows than the regular one, from ⌈h/M⌉×⌈w/M⌉ to (⌈h/M⌉+1)×(⌈w/M⌉+1), and some of these windows are smaller than M×M. Padding the small windows to M×M and masking the padded values is the simple fix, but with a 2×2 regular grid it enlarges the computation from 2×2 to 3×3 windows, which is 2.25 times more.

The authors instead cyclically shift the feature map toward the top-left, so the number of batched windows stays the same as in regular partitioning.

## Relative position bias inside each head

Each head adds a relative position bias B to the scaled dot-product logits before the softmax. The paper writes the attention as follows. \\\[ \\text{Attention}(Q,K,V) = \\text{SoftMax}(QK^T/\\sqrt{d} + B)V \\\] Here \\(Q, K, V \\in \\mathbb{R}^{M^2 \\times d}\\) are the query, key and value matrices of one window, d is the query/key dimension, and M² is the number of patches in a window.

The bias B has size M²×M².

The relative offset along each axis lies in the range from −M+1 to M−1, so the method learns a smaller matrix \\(\\hat B \\in \\mathbb{R}^{(2M-1)\\times(2M-1)}\\), and the entries of B are read from \\(\\hat B\\). The learned bias can initialize a model fine-tuned at a different window size through bi-cubic interpolation.

Adding an absolute position embedding to the input drops performance slightly, so the authors did not adopt it.

## Model variants

Swin-B is sized to have a model size and computation similar to ViT-B and DeiT-B. Swin-T, Swin-S and Swin-L are about 0.25×, 0.5× and 2× its size and cost. The query dimension is d = 32 and the MLP expansion ratio is α = 4 in all experiments.

The four variants differ in the channel number C of the first stage and in the block counts per stage. Swin-T uses C = 96 with {2, 2, 6, 2} blocks, Swin-S uses C = 96 with {2, 2, 18, 2}, Swin-B uses C = 128 with {2, 2, 18, 2} and Swin-L uses C = 192 with {2, 2, 18, 2}. Swin-S therefore keeps the width of Swin-T and deepens the third stage, while Swin-B and Swin-L widen the channels.

## ImageNet-1K classification results

ImageNet-1K has 1.28M training images and 50K validation images from 1,000 classes, and top-1 accuracy is reported on a single crop.

At 224 input, Swin-T reached 81.3 top-1, against 79.8 for DeiT-S, a gain of +1.5%. Against ConvNets such as RegNet and EfficientNet, the authors report a slightly better speed-accuracy trade-off. They note that those two families were found by architecture search, while Swin was adapted from the standard Transformer.

For Swin-B, pre-training on ImageNet-22K, which has 14.2 million images and 22K classes, adds about 1.8% to 1.9% over training on ImageNet-1K alone.

## COCO detection and instance segmentation

COCO 2017 has 118K training, 5K validation and 20K test-dev images. Ablations use the validation set and system results use test-dev. Four frameworks are used for the ablations, Cascade Mask R-CNN, ATSS, RepPoints v2 and Sparse R-CNN. All use multi-scale training, AdamW with learning rate 0.0001, weight decay 0.05, batch size 16 and a 3x schedule of 36 epochs.

Changing only the backbone, Swin-T gave +3.4 to 4.2 box AP over ResNet-50 across the four frameworks, with slightly larger model size, FLOPs and latency. With Cascade Mask R-CNN, Swin-T reached 50.5 box AP against 46.3 for ResNet-50. The authors attribute the slower DeiT inference to its quadratic complexity in input size.

For the system-level comparison, an improved HTC (HTC++) is used with ImageNet-22K pre-training, a 6x schedule and multi-scale testing for the strongest model. Swin-L (HTC++) with multi-scale testing reached 58.7 box AP and 51.1 mask AP on COCO test-dev. Against the Copy-paste result without external data, this is +2.7 box AP, and against DetectoRS it is +2.6 mask AP.

## ADE20K semantic segmentation

Swin-S reached 49.3 mIoU against 44.0 for DeiT-S, +5.3 mIoU at similar computation. Swin-S is also 4.4 mIoU above ResNet-101 and 2.4 mIoU above ResNeSt-101.

Swin-L pre-trained on ImageNet-22K reached 53.5 mIoU on the val set, 3.2 mIoU above the 50.3 of SETR, which has a larger model size.

## What shifting and position bias contribute

All ablations use Swin-T. Removing the shift, so that every block keeps regular partitioning, gives 80.2 top-1 against 81.3 with shifted windows, a 1.1% gain. On COCO, shifted windows give 50.5 box AP and 43.7 mask AP against 47.7 and 41.5 without shifting, which is +2.8 box AP and +2.2 mask AP. On ADE20K, mIoU rises from 43.3 to 46.1, +2.8.

With no position encoding, Swin-T reached 80.1 top-1; with the relative position bias it reached 81.3, a gain of 1.2%.

Keeping the bias but removing the first scaled dot-product term, labelled w/o app., gives 79.3 top-1 and 44.1 mIoU, so that term is also part of the gain.

## Real speed of the self-attention implementations

Table 5 measures per-stage attention time and whole-model throughput on a V100 GPU. For Swin-T, the sliding window naive version runs at 183 FPS and the sliding window kernel version at 488 FPS, while the shifted window with cyclic shift runs at 755 FPS. Stage 1 takes 3.0 ms with the cyclic shift and 3.3 ms with padding, against 122.5 ms for the naive sliding window.

Within the shifted window method, the cyclic implementation gives a 13%, 18% and 18% speed-up on Swin-T, Swin-S and Swin-B against naive padding. Over sliding windows, the Swin variants with shifted windows are 4.1 times faster for Swin-T, 4.0 times for Swin-S and 3.6 times for Swin-B in the naive setting, and 1.5 times faster in the kernel setting.

Performer runs at 638 FPS on Swin-T in Table 5, which is slower than the cyclic shift, and reached 79.0 top-1 against 81.3 for shifted windows. These speed numbers come from the V100 measurements of Table 5, and the accuracies in Table 6 come from separately trained models.

## Swin-Mixer on an all-MLP backbone

Swin-Mixer applies the hierarchical design and the shifted window approach to the MLP-Mixer architecture. Swin-Mixer-B/D24 with shifted windows reached 81.3 top-1 on ImageNet-1K with 10.4G FLOPs. The MLP-Mixer-B/16 row in the same table, cited from its original work, is at 76.4 with 12.7G FLOPs.

## Limitations

The authors leave kernel-level optimization out of scope. Their architecture uses built-in PyTorch functions, while ResNe(X)t is built on highly optimized cuDNN functions, so the latency reported for Swin is not fully optimized.

DeiT produces a single resolution of feature maps, so for detection and segmentation it needs deconvolution layers to build hierarchical maps, and these layers are marked with a dagger in the tables.

The component ablations are run on Swin-T only, and the speed measurements are taken on a V100 GPU.

## Paper info

- **Authors**: Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo
- **Venue**: arXiv · Preprint
- **First published**: 2021-3-25
- **Added**: 2026-10-20
- **Updated**: 2021-8-17
- **Version**: v2
- **arXiv**: 2103.14030
- **Category**: cs.CV · cs.LG
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2103.14030v2) · [PDF ↗](https://arxiv.org/pdf/2103.14030v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Abstract

This paper presents a new vision Transformer, called Swin Transformer, that capably serves as a general-purpose backbone for computer vision. Challenges in adapting Transformer from language to vision arise from differences between the two domains, such as large variations in the scale of visual entities and the high resolution of pixels in images compared to words in text. To address these differences, we propose a hierarchical Transformer whose representation is computed with \\textbf{S}hifted \\textbf{win}dows. The shifted windowing scheme brings greater efficiency by limiting self-attention computation to non-overlapping local windows while also allowing for cross-window connection. This hierarchical architecture has the flexibility to model at various scales and has linear computational complexity with respect to image size. These qualities of Swin Transformer make it compatible with a broad range of vision tasks, including image classification (87.3 top-1 accuracy on ImageNet-1K) and dense prediction tasks such as object detection (58.7 box AP and 51.1 mask AP on COCO test-dev) and semantic segmentation (53.5 mIoU on ADE20K val). Its performance surpasses the previous state-of-the-art by a large margin of +2.7 box AP and +2.6 mask AP on COCO, and +3.2 mIoU on ADE20K, demonstrating the potential of Transformer-based models as vision backbones. The hierarchical design and the shifted window approach also prove beneficial for all-MLP architectures. The code and models are publicly available at~\\url{https://github.com/microsoft/Swin-Transformer}.

## Quote from the paper

Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo (2021). Swin Transformer: Hierarchical Vision Transformer using Shifted Windows. arXiv:2103.14030v2. https://arxiv.org/abs/2103.14030v2

**BibTeX**

```
@misc{liu2021swin,
  title = {{Swin Transformer: Hierarchical Vision Transformer using Shifted Windows}},
  author = {Ze Liu and Yutong Lin and Yue Cao and Han Hu and Yixuan Wei and Zheng Zhang and Stephen Lin and Baining Guo},
  year = {2021},
  eprint = {2103.14030},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2103.14030v2}
}
```

## Other paper commentary

- [Learning Transferable Visual Models From Natural Language Supervision](https://refivu.com/en/papers/c2ad57ff-fd96-4ad1-af27-4195a16c557d-learning-transferable-visual-models-from-natural-language.md)
- [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://refivu.com/en/papers/8a112940-90e3-4c6b-8fa0-d576b3ebd5d1-an-image-is-worth-16x16-words-transformers-for.md)
- [Deep Residual Learning for Image Recognition](https://refivu.com/en/papers/19d6446d-fd9a-4e80-b535-a4e333cad216-deep-residual-learning-for-image-recognition.md)
- [ArcFace: Additive Angular Margin Loss for Deep Face Recognition](https://refivu.com/en/papers/c413067c-e2eb-43a0-8011-b952f120296a-arcface-additive-angular-margin-loss-for-deep-face.md)
- [Memory as Dynamics: Learning Reliability-Guided Predictive Models for Online Video Perception](https://refivu.com/en/papers/9edb7769-5017-4985-b695-21eab77d07d7-memory-as-dynamics-learning-reliability-guided-predictive.md)
- [Breaking Semantic Artifacts for Generalized AI-generated Image Detection](https://refivu.com/en/papers/4e046749-44ad-45fe-a59b-ca849df10c45-breaking-semantic-artifacts-for-generalized-ai-generated.md)
- [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://refivu.com/en/papers/70da27bf-5c2f-4e05-bfe2-7c145011b0d9-distilbert-a-distilled-version-of-bert-smaller-faster.md)
- [QLoRA: Efficient Finetuning of Quantized LLMs](https://refivu.com/en/papers/27d2d955-4f1a-4d56-aef7-766870813fe4-qlora-efficient-finetuning-of-quantized-llms.md)
- [The Power of Scale for Parameter-Efficient Prompt Tuning](https://refivu.com/en/papers/b52e4465-a64e-4e31-94a8-52b414c956c9-the-power-of-scale-for-parameter-efficient-prompt.md)
- [ReAct: Synergizing Reasoning and Acting in Language Models](https://refivu.com/en/papers/332bb0c8-840f-4238-89c1-dfa32572b3d8-react-synergizing-reasoning-and-acting-in-language-models.md)
- [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://refivu.com/en/papers/7a3fbf64-0a8d-440d-a8cf-5d65c573adde-albert-a-lite-bert-for-self-supervised-learning.md)
- [Parameter-Efficient Transfer Learning for NLP](https://refivu.com/en/papers/617c096f-a488-458f-9a8f-89779c96eda7-parameter-efficient-transfer-learning-for-nlp.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [Object detection](https://refivu.com/en/terms/113bfdb14049-object-detection)
- [COCO](https://refivu.com/en/terms/41f3215c4f4a-coco)
- [Semantic segmentation](https://refivu.com/en/terms/00dfce7ec404-semantic-segmentation)
- [mIoU](https://refivu.com/en/terms/901dcc5384c2-miou)
- [self-attention](https://refivu.com/en/terms/426589b81077-self-attention)
- [ImageNet-1K](https://refivu.com/en/terms/d8d6444bd460-imagenet-1k)
- [DeiT](https://refivu.com/en/terms/24b9f164881b-deit)
- [box AP](https://refivu.com/en/terms/850b2f2111cb-box-ap)
- [UPerNet](https://refivu.com/en/terms/d07802fe3627-upernet)
- [W-MSA](https://refivu.com/en/terms/31f5c71e4403-w-msa)
- [Cascade Mask R-CNN](https://refivu.com/en/terms/91bd24b3f04f-cascade-mask-r-cnn)
- [mask AP](https://refivu.com/en/terms/302e59e40633-mask-ap)
- [SW-MSA](https://refivu.com/en/terms/bb0e29a8b2d6-sw-msa)
- [Performer](https://refivu.com/en/terms/5662fbc9040b-performer)
- [relative position bias](https://refivu.com/en/terms/8975496c1e25-relative-position-bias)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/d2c6b7fa-f256-44cf-9328-c55d713768da-swin-transformer-hierarchical-vision-transformer-using)
