Swin Transformer is a hierarchical vision Transformer that splits an image into small windows, computes self-attention only within each window, and shifts the window positions from layer to layer to connect the windows. It was published in 2021 by Liu et al. at Microsoft Research Asia. The name Swin comes from Shifted windows.
ViT and DeiT matched CNNs in image classification, but using them as the foundation (backbone) for object detection and segmentation posed two problems.
Computation grows quadratically with image size: Self-attention in which every patch attends to every other patch requires computation proportional to the square of the number of patches. For tasks that need per-pixel predictions, high-resolution inputs become intractable.
Feature maps have only one coarse resolution: ViT keeps 16×16 patches from start to finish. To find objects of varying sizes, it is easier to have stage-wise feature maps from fine to coarse resolution, as in ResNet.
Swin Transformer solved both with the following ideas.
Self-attention only within windows: Computing attention within windows of 7×7 patches makes computation grow only linearly with image size.
Shifting windows: The next layer shifts the windows by half a window, mixing information between windows that were separate in the previous layer.
Merging patches to build a hierarchy: At each stage, adjacent 2×2 patches are merged, reducing resolution to 1/4, 1/8, 1/16, and 1/32. Because the feature maps have the same shape as a CNN's, they plug directly into existing frameworks such as FPN and U-Net.
It substantially surpassed the state of the art at the time of publication: 87.3% on ImageNet classification (Swin-L pretrained on large-scale data), 58.7 box AP on COCO object detection, and 53.5 mIoU on ADE20K semantic segmentation. The paper received the ICCV 2021 best paper award (Marr Prize).
Architecture
Swin Transformer stacks Swin Transformer blocks in each of four stages while reducing the resolution from stage to stage. The left side of the figure at the top of the article shows the overall flow of Swin-T, and the right side shows the inside of the pair of consecutive blocks and how windows are partitioned.
An image flows through the network as follows (Swin-T with a 224×224 input).
Split into patches: The image is split into 4×4 patches. There are 56×56 patches, each with a feature of 4×4×3=48 dimensions. The patches are finer than ViT's 16×16.
Stage 1: A linear layer projects the features to C=96 dimensions (linear embedding), followed by two Swin Transformer blocks. The number of tokens (56×56) stays the same.
Stages 2–4: Patch merging concatenates the features of adjacent 2×2 patches into 4C dimensions and a linear layer reduces them to 2C dimensions. The number of tokens drops to 1/4 (half in each direction) and the number of channels doubles. Blocks are then stacked.
Classification: Global average pooling is applied to the output of the last stage, and a linear layer predicts the class. ViT's [class] token is not used, and the paper reports comparable accuracy.
The feature map sizes at each stage match those of typical CNNs (such as ResNet).
Stage
Resolution (224 input)
Channels
Downsampling factor
1
56×56
C
1/4
2
28×28
2C
1/8
3
14×14
4C
1/16
4
7×7
8C
1/32
Swin Transformer block
This block replaces the multi-head attention in ViT's encoder layer with attention computed only within windows. Everything else is the same: layer normalization is placed before each sub-layer and a residual connection after it. The MLP has two layers with a GELU in between and expands the hidden layer by 4x.
Blocks are always used in pairs. The first computes self-attention with regular window partitioning (W-MSA), and the second with shifted window partitioning (SW-MSA) (Eq. (3) of the paper). z^l is the output after attention and zl the output after the MLP.
As a result, the number of blocks in each stage is even (such as 2, 2, 6, 2).
Model sizes (Section 3.3 and Table 1 of the paper; window size M=7, 32 dimensions per head, 224×224 input)
Model
C
Blocks per stage
Parameters
FLOPs
Throughput (images/s)
Swin-T
96
2, 2, 6, 2
29M
4.5G
755.2
Swin-S
96
2, 2, 18, 2
50M
8.7G
436.9
Swin-B
128
2, 2, 18, 2
88M
15.4G
278.1
Swin-L
192
2, 2, 18, 2
197M
103.9G (384 input)
42.1 (384 input)
The computational cost of Swin-T and Swin-S is matched to ResNet-50 (DeiT-S) and ResNet-101, and Swin-B to ViT-B and DeiT-B.
Theory: Shifted Window Self-Attention
Computing only within windows makes cost linear in image size
For a feature map of h×w patches with C channels, the computational cost of global self-attention (MSA) and of self-attention within M×M windows only (W-MSA) is as follows (Eqs. (1)(2) of the paper, excluding softmax).
Ω(MSA)=4hwC2+2(hw)2C,Ω(W-MSA)=4hwC2+2M2hwC
The first term covers the Q, K, V and output projections and is the same in both. The difference is the second term, computing the attention matrix: quadratic in the number of patches hw for the global case, but linear in hw for windows when M is fixed. For stage 1 of Swin-T (56×56=3136 patches, M=7), the second term becomes hw/M2=64 times smaller.
Connecting windows with shifted windows
Computing only within windows eliminates information exchange across window boundaries. Swin Transformer compensates by alternating the partitioning between two consecutive blocks.
Regular partitioning (W-MSA): The feature map is partitioned from the top-left into non-overlapping M×M windows, and self-attention is computed in each window.
Shifted partitioning (SW-MSA): In the next block, the windows are shifted by (⌊M/2⌋,⌊M/2⌋) patches vertically and horizontally. Each new window spans several windows of the previous block, so information mixes among them.
Repeat: Stacking blocks while alternating the partitioning widens the visible range with every layer.
As an analogy, it is like splitting desks into several islands for a discussion, then shifting the island boundaries by half for the next round. Each discussion stays small, but by the second round, opinions from people on other islands have been passed along.
Computing shifted windows efficiently with cyclic shift and masking
Shifted partitioning increases the number of windows from ⌈h/M⌉×⌈w/M⌉ to (⌈h/M⌉+1)×(⌈w/M⌉+1), and windows at the edges become smaller than M×M. Padding the small windows to M×M would increase computation by 2.25x when 2×2 windows become 3×3.
Instead, Swin Transformer cyclically shifts the entire feature map toward the top-left by ⌊M/2⌋ (wrapping the parts that fall off to the opposite side) and then partitions it with the regular partitioning. The number of windows is the same as with regular partitioning. Since a window may contain parts that were not adjacent in the original feature map, a mask ensures that attention is computed only between patches that belonged to the same window in their original positions. After computation, a reverse cyclic shift restores the original positions.
Relative position bias
Rather than adding position embeddings to the input as ViT does, Swin Transformer adds a per-head bias B∈RM2×M2 determined by the relative positions of patches to the attention scores (Eq. (4) of the paper).
Attention(Q,K,V)=SoftMax(dQK⊤+B)V
Q,K,V∈RM2×d are the queries, keys, and values within a window. Since relative positions within a window range from −M+1 to M−1 along each axis, what is learned is a small (2M−1)×(2M−1) table B^, and the values of B are taken from it. The idea belongs to the same family as T5's relative position bias and relative position representations.
Relative position bias changes the weights based on "how far apart" rather than "where", so an object of the same shape is treated the same wherever it appears in the image (translation invariance). The paper says this property is particularly effective for object detection and segmentation. Indeed, adding absolute position embeddings to the input slightly improved classification but lowered detection and segmentation.
Training
When training on ImageNet-1K alone, the DeiT training recipe is used almost as is (Appendix A2.1 of the paper).
Unlike DeiT, repeated augmentation and an exponential moving average of the weights are not used, because they did not improve accuracy. In DeiT, repeated augmentation was key to stabilizing ViT training, but Swin Transformer did not need it.
For 384×384 images, a model trained at 224×224 is fine-tuned for only 30 epochs. When the window size changes, the learned relative position bias table is resized with bicubic interpolation.
For pretraining on large-scale data, the model is trained on ImageNet-22K (about 14.2 million images, 22,000 classes) for 90 epochs and then fine-tuned on ImageNet-1K for 30 epochs.
Experimental Results
Image classification (ImageNet-1K top-1 accuracy %; throughput on one V100; Table 1 of the paper)
It is about 1.5 points higher than DeiT at similar computational cost, and on par with or slightly better than RegNet and EfficientNet, which were found by architecture search, in the speed–accuracy trade-off. With ImageNet-22K pretraining, Swin-B (384) reached 86.4% and Swin-L (384) 87.3%. Under the same conditions, ViT-B/16 reaches 84.0% and ViT-L/16 85.2%.
Object detection (COCO val2017, comparing backbones only within Cascade Mask R-CNN; Table 2(b) of the paper)
Backbone
box AP
mask AP
Parameters
FPS
ResNet-50
46.3
40.1
82M
18.0
DeiT-S (hierarchy built with deconvolution)
48.0
41.4
80M
10.4
Swin-T
50.5
43.7
86M
15.3
ResNeXt-101 64x4d
48.3
41.7
140M
10.4
Swin-B
51.9
45.0
145M
11.6
Because DeiT has only one feature map resolution, deconvolution layers are added to build a hierarchy. Even so, Swin-T is 2.5 points higher, and it runs faster because its computation does not grow quadratically with image size. Swin-L, combined with large-scale pretraining and an improved detector (HTC++), achieved 58.7 box AP and 51.1 mask AP on COCO test-dev.
Semantic segmentation (ADE20K val, UperNet; Table 3 of the paper): DeiT-S scored 44.0 mIoU and ResNet-101 44.9, while Swin-T scored 46.1 and Swin-S 49.3. Swin-L pretrained on ImageNet-22K reached 53.5.
Effect of shifted windows and position handling (Swin-T; Table 4 of the paper)
Setting
ImageNet
COCO box AP
COCO mask AP
ADE20K mIoU
No shift (regular partitioning in all layers)
80.2
47.7
41.5
43.3
Shifted (default)
81.3
50.5
43.7
46.1
No position information
80.1
49.2
42.6
43.8
Absolute position embedding
80.5
49.0
42.4
43.2
Absolute position + relative position bias
81.3
50.2
43.4
44.0
Relative position bias (default)
81.3
50.5
43.7
46.1
Shifting alone raised classification by 1.1 points, detection by 2.8 points, and segmentation by 2.8 points.
Speed (FPS of the whole Swin-T on a V100; Tables 5 and 6 of the paper; variants differing only in implementation of the same computation have the same accuracy)
Accuracy is nearly the same as sliding windows, which take a window around each patch, while speed is 1.5x higher (compared with the custom kernel). With sliding windows, each query has a different set of keys, so memory access is inefficient; with shifted windows, all queries in a window share the same keys.
Practical Considerations
Keep the following points in mind when using Swin Transformer.
The input size must be divisible by the window size: If the height or width of a stage's feature map is not a multiple of M=7, padding is added at the bottom-right. With a 224×224 input, every stage is designed to be a multiple of 7 (56, 28, 14, 7).
Interpolate the relative position bias when changing the window size: The learned (2M−1)×(2M−1) table is resized with bicubic interpolation to the new window size.
Use blocks in pairs: The design assumes alternating regular and shifted partitioning, so each stage needs an even number of blocks. Removing shifted windows clearly lowers accuracy.
Use the outputs of all four stages for detection and segmentation: Classification uses only the last stage, but frameworks such as FPN and UperNet receive the outputs of stages 1–4 (1/4 to 1/32 resolution) directly.
Where to get it in PyTorch: torchvision provides swin_t, swin_s, and swin_b, with ImageNet-trained weights available. The official implementation and ImageNet-22K pretrained weights are in the microsoft/Swin-Transformer repository.
Computing only within windows means distant patches are not directly connected within a single layer. Shifted windows and patch merging widen the visible range as layers stack, but shallow layers cannot directly see relationships between distant locations. Also, the cyclic shift and masking implementation is complex, and building the mask is error-prone if you write it yourself. In general, use a library implementation.
Comparison with Other Models
Swin Transformer brings the CNN properties of "looking locally" and "reducing resolution in stages" into ViT's self-attention. Compared on the same terms:
As a backbone for object detection or segmentation: Swin Transformer outputs feature maps of the same shape as ResNet, so it plugs directly into existing detectors. In the paper's comparisons, it was 3–4 points higher in box AP than ResNe(X)t of similar size.
Classification only, prioritizing architectural simplicity: ViT and DeiT, with global self-attention, are simpler to implement. Weights pretrained on large-scale data are also plentiful.
Similar accuracy without Transformer components: ConvNeXt, proposed later, redesigned a CNN with reference to Swin Transformer's design and matches or exceeds its accuracy at similar computational cost. Since it uses only convolutions, it is less restrictive about the inference environment.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import swin_t, Swin_T_Weights
"""
1) Classify images with torchvision's pretrained Swin-T
2) A small implementation of Section 3.2 of the paper (window self-attention, cyclic shift and masking, relative position bias)
"""
# ---- 1) Use the pretrained model ----
weights = Swin_T_Weights.IMAGENET1K_V1
model = swin_t(weights=weights).eval() # eval() for inference (disables Stochastic Depth)
preprocess = weights.transforms() # resize, crop, and normalize (224×224 input)
# logits = model(preprocess(img).unsqueeze(0))
# ---- 2) A small implementation following the paper's equations ----
def window_partition(x, M):
"""[B, H, W, C] → [B*(H/M)*(W/M), M*M, C]. H and W are assumed to be multiples of M"""
B, H, W, C = x.shape
x = x.view(B, H // M, M, W // M, M, C).permute(0, 1, 3, 2, 4, 5)
return x.reshape(-1, M * M, C)
def window_reverse(w, M, H, W):
"""Inverse of window_partition"""
B = w.shape[0] // ((H // M) * (W // M))
x = w.view(B, H // M, W // M, M, M, -1).permute(0, 1, 3, 2, 4, 5)
return x.reshape(B, H, W, -1)
class WindowAttention(nn.Module):
"""Multi-head self-attention within a window + relative position bias (Eq. (4))"""
def __init__(self, dim, M, heads):
super().__init__()
self.M, self.heads = M, heads
self.scale = (dim // heads) ** -0.5
self.qkv = nn.Linear(dim, 3 * dim)
self.proj = nn.Linear(dim, dim)
# What is learned is a small (2M-1)×(2M-1) table B^ (per head)
self.bias_table = nn.Parameter(torch.zeros((2 * M - 1) ** 2, heads))
nn.init.trunc_normal_(self.bias_table, std=0.02)
# Relative position of two patches in a window → table index
coords = torch.stack(torch.meshgrid(torch.arange(M), torch.arange(M), indexing="ij")).flatten(1) # [2, M*M]
rel = (coords[:, :, None] - coords[:, None, :]).permute(1, 2, 0) + (M - 1) # 0..2M-2
self.register_buffer("rel_index", rel[..., 0] * (2 * M - 1) + rel[..., 1]) # [M*M, M*M]
def forward(self, x, mask=None):
Bw, N, C = x.shape # Bw = batch × number of windows, N = M*M
q, k, v = self.qkv(x).view(Bw, N, 3, self.heads, C // self.heads).permute(2, 0, 3, 1, 4)
attn = (q * self.scale) @ k.transpose(-2, -1) # [Bw, heads, N, N]
bias = self.bias_table[self.rel_index].permute(2, 0, 1) # B: [heads, N, N]
attn = attn + bias.unsqueeze(0)
if mask is not None: # mask for shifted windows [nW, N, N]
nW = mask.shape[0]
attn = attn.view(-1, nW, self.heads, N, N) + mask[None, :, None]
attn = attn.view(Bw, self.heads, N, N)
out = attn.softmax(-1) @ v
return self.proj(out.transpose(1, 2).reshape(Bw, N, C))
class SwinBlock(nn.Module):
"""Swin Transformer block (Pre-LN). shift=0 gives W-MSA, shift=M//2 gives SW-MSA"""
def __init__(self, dim, H, W, heads, M=7, shift=0):
super().__init__()
self.H, self.W, self.M, self.shift = H, W, M, shift
self.norm1, self.norm2 = nn.LayerNorm(dim), nn.LayerNorm(dim)
self.attn = WindowAttention(dim, M, heads)
self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
mask = None
if shift > 0:
# Give the same ID to patches that were in the same window originally (prevents mixing regions after the cyclic shift)
region = torch.zeros(1, H, W, 1)
cnt = 0
for hs in (slice(0, -M), slice(-M, -shift), slice(-shift, None)):
for ws in (slice(0, -M), slice(-M, -shift), slice(-shift, None)):
region[:, hs, ws, :] = cnt
cnt += 1
r = window_partition(region, M).squeeze(-1) # [nW, M*M]
mask = (r[:, None, :] != r[:, :, None]).float() * -100.0 # patches in different regions do not attend to each other
self.register_buffer("mask", mask)
def forward(self, x): # x: [B, H*W, C]
B, L, C = x.shape
h = self.norm1(x).view(B, self.H, self.W, C)
if self.shift > 0: # cyclic shift toward the top-left
h = torch.roll(h, shifts=(-self.shift, -self.shift), dims=(1, 2))
h = window_partition(h, self.M)
h = self.attn(h, self.mask)
h = window_reverse(h, self.M, self.H, self.W)
if self.shift > 0: # restore with the reverse cyclic shift
h = torch.roll(h, shifts=(self.shift, self.shift), dims=(1, 2))
x = x + h.reshape(B, L, C) # residual connection
return x + self.mlp(self.norm2(x))
class PatchMerging(nn.Module):
"""Concatenate adjacent 2×2 patches into 4C dimensions → linear layer to 2C dimensions (resolution halved in each direction)"""
def __init__(self, dim, H, W):
super().__init__()
self.H, self.W = H, W
self.norm = nn.LayerNorm(4 * dim)
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
def forward(self, x):
B, L, C = x.shape
x = x.view(B, self.H, self.W, C)
x = torch.cat([x[:, 0::2, 0::2], x[:, 1::2, 0::2], x[:, 0::2, 1::2], x[:, 1::2, 1::2]], dim=-1)
return self.reduction(self.norm(x.view(B, -1, 4 * C)))
# The two blocks of stage 1 (Swin-T: 56×56 tokens, C = 96, 3 heads)
stage1 = nn.Sequential(SwinBlock(96, 56, 56, heads=3, shift=0), # W-MSA
SwinBlock(96, 56, 56, heads=3, shift=3)) # SW-MSA (shift by M // 2 = 3)
merge = PatchMerging(96, 56, 56)
x = torch.randn(2, 56 * 56, 96)
y = merge(stage1(x))
print(y.shape) # torch.Size([2, 784, 192]): 28×28 tokens, 2C = 192 dimensions
FAQ
Q. What is the main difference between Swin Transformer and ViT?
A.
The scope of self-attention and the shape of the feature maps. In ViT, patches across the whole image attend to each other, so computation grows quadratically with image size, and there is only one feature map at 1/16 resolution. Swin Transformer computes attention only within 7×7 windows and connects them by shifting the windows from layer to layer, so computation grows linearly with image size. It also merges patches to produce four stages of feature maps from 1/4 to 1/32 resolution, so it can be used directly as a backbone for object detection and segmentation.
Q. What happens if the windows are not shifted?
A.
Information can no longer flow across window boundaries, and accuracy drops. In the paper's comparison (Swin-T), using regular partitioning in all layers lowered ImageNet accuracy from 81.3% to 80.2%, COCO box AP from 50.5 to 47.7, and ADE20K mIoU from 46.1 to 43.3. The difference in speed was small.
Q. Why use relative position bias instead of position embeddings?
A.
Because in the paper's comparison, relative position bias performed better, especially for detection and segmentation. Relative position bias changes attention scores based on "how far apart" patches are, so objects are treated the same wherever they appear in the image. Adding absolute position embeddings as in ViT slightly improved classification but lowered results on COCO and ADE20K.