AI Logic

Architectures

Swin Transformer

Updated:

Swin Transformer architecture. Left: the overall flow of Swin-T (split into 4×4 patches, then four stages of patch merging and blocks that reduce resolution from 56×56 to 7×7). Right: a pair of blocks (W-MSA with regular window partitioning and SW-MSA with shifted window partitioning) and how the window partitioning differs on an 8×8 grid of patches

Background and Overview

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).

  1. Split into patches: The image is split into 4×4 patches. There are 56×5656 \times 56 patches, each with a feature of 4×4×3=484 \times 4 \times 3 = 48 dimensions. The patches are finer than ViT's 16×16.
  2. Stage 1: A linear layer projects the features to C=96C = 96 dimensions (linear embedding), followed by two Swin Transformer blocks. The number of tokens (56×5656 \times 56) stays the same.
  3. Stages 2–4: Patch merging concatenates the features of adjacent 2×2 patches into 4C4C dimensions and a linear layer reduces them to 2C2C dimensions. The number of tokens drops to 1/4 (half in each direction) and the number of channels doubles. Blocks are then stacked.
  4. 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).

StageResolution (224 input)ChannelsDownsampling factor
156×5656 \times 56CC1/4
228×2828 \times 282C2C1/8
314×1414 \times 144C4C1/16
47×77 \times 78C8C1/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\hat{z}^l is the output after attention and zlz^l the output after the MLP.

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{z}^{l} &= \text{W-MSA}(\mathrm{LN}(z^{l-1})) + z^{l-1}, & z^{l} &= \mathrm{MLP}(\mathrm{LN}(\hat{z}^{l})) + \hat{z}^{l},\\ \hat{z}^{l+1} &= \text{SW-MSA}(\mathrm{LN}(z^{l})) + z^{l}, & z^{l+1} &= \mathrm{MLP}(\mathrm{LN}(\hat{z}^{l+1})) + \hat{z}^{l+1} \end{aligned}

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=7M = 7, 32 dimensions per head, 224×224 input)

ModelCCBlocks per stageParametersFLOPsThroughput (images/s)
Swin-T962, 2, 6, 229M4.5G755.2
Swin-S962, 2, 18, 250M8.7G436.9
Swin-B1282, 2, 18, 288M15.4G278.1
Swin-L1922, 2, 18, 2197M103.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×wh \times w patches with CC channels, the computational cost of global self-attention (MSA) and of self-attention within M×MM \times 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\Omega(\text{MSA}) = 4hwC^2 + 2(hw)^2 C, \qquad \Omega(\text{W-MSA}) = 4hwC^2 + 2M^2 hwC

The first term covers the QQ, KK, VV 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 hwhw for the global case, but linear in hwhw for windows when MM is fixed. For stage 1 of Swin-T (56×56=313656 \times 56 = 3136 patches, M=7M = 7), the second term becomes hw/M2=64hw / M^2 = 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.

  1. Regular partitioning (W-MSA): The feature map is partitioned from the top-left into non-overlapping M×MM \times M windows, and self-attention is computed in each window.
  2. Shifted partitioning (SW-MSA): In the next block, the windows are shifted by (⌊M/2⌋,⌊M/2⌋)(\lfloor M/2 \rfloor, \lfloor M/2 \rfloor) patches vertically and horizontally. Each new window spans several windows of the previous block, so information mixes among them.
  3. 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⌉\lceil h/M \rceil \times \lceil w/M \rceil to (⌈h/M⌉+1)×(⌈w/M⌉+1)(\lceil h/M \rceil + 1) \times (\lceil w/M \rceil + 1), and windows at the edges become smaller than M×MM \times M. Padding the small windows to M×MM \times 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⌋\lfloor M/2 \rfloor (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×M2B \in \mathbb{R}^{M^2 \times M^2} determined by the relative positions of patches to the attention scores (Eq. (4) of the paper).

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

Q,K,V∈RM2×dQ, K, V \in \mathbb{R}^{M^2 \times d} are the queries, keys, and values within a window. Since relative positions within a window range from −M+1-M+1 to M−1M-1 along each axis, what is learned is a small (2M−1)×(2M−1)(2M-1) \times (2M-1) table B^\hat{B}, and the values of BB 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).

ItemSetting
OptimizationAdamW, learning rate 0.001, weight decay 0.05
Epochs and batch size300 epochs, 1024
Learning rate schedule20 epochs of warmup, then cosine decay
Gradient clippingMax norm 1
Data augmentationRandAugment, Mixup, CutMix, Random Erasing
RegularizationStochastic Depth (0.2, 0.3, 0.5 for Swin-T, S, B)

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)

ModelResolutionParametersFLOPsThroughputAccuracy
RegNetY-4G22421M4.0G1156.780.0
EfficientNet-B330012M1.8G732.181.6
DeiT-S22422M4.6G940.479.8
DeiT-B22486M17.5G292.381.8
Swin-T22429M4.5G755.281.3
Swin-S22450M8.7G436.983.0
Swin-B22488M15.4G278.183.5
Swin-B38488M47.0G84.784.5

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)

Backbonebox APmask APParametersFPS
ResNet-5046.340.182M18.0
DeiT-S (hierarchy built with deconvolution)48.041.480M10.4
Swin-T50.543.786M15.3
ResNeXt-101 64x4d48.341.7140M10.4
Swin-B51.945.0145M11.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)

SettingImageNetCOCO box APCOCO mask APADE20K mIoU
No shift (regular partitioning in all layers)80.247.741.543.3
Shifted (default)81.350.543.746.1
No position information80.149.242.643.8
Absolute position embedding80.549.042.443.2
Absolute position + relative position bias81.350.243.444.0
Relative position bias (default)81.350.543.746.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)

Self-attention computationFPSImageNet
Sliding window (naive implementation)18381.4
Sliding window (custom kernel)48881.4
Performer63879.0
Shifted window (computed with padding)67081.3
Shifted window (computed with cyclic shift)75581.3

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=7M = 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)(2M-1) \times (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:

ModelSelf-attention scopeFeature mapsCost (relative to image size)Ease of use for detection and segmentation
ViT, DeiTWhole imageOne (1/16)QuadraticRequires extra layers to build a hierarchy
Swin TransformerWithin windows (connected by shifting)Four stages (1/4–1/32)LinearDrop-in replacement
ResNetNone (convolution)Four stages (1/4–1/32)LinearDrop-in replacement
ConvNeXtNone (convolution)Four stages (1/4–1/32)LinearDrop-in replacement

Rough guidelines for choosing:

  • 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.

References

  1. Liu, Z., Lin, Y., Cao, Y., Hu, H., Wei, Y., Zhang, Z., Lin, S., & Guo, B. (2021). Swin Transformer: Hierarchical Vision Transformer using Shifted Windows. ICCV 2021. arXiv:2103.14030.
  2. microsoft/Swin-Transformer (official implementation and pretrained weights).
  3. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  4. Touvron, H., et al. (2021). Training data-efficient image transformers & distillation through attention. ICML 2021. arXiv:2012.12877.
  5. torchvision.models.swin_t (official PyTorch documentation).