Swin Transformer

Also known as: shifted window transformer

On this page 7

Swin Transformer (short for shifted window transformer) is a hierarchical vision transformer backbone that computes self-attention inside non-overlapping local windows and shifts those windows between consecutive layers so that information flows across window borders. In computer vision, it was introduced in 2021 to make transformers practical for dense prediction tasks such as object detection and semantic segmentation, where the original vision transformer struggled with high-resolution inputs.

The design combines two ideas that convolutional networks made standard: multi-scale feature maps and local receptive fields. Because attention is restricted to windows of fixed size, the cost grows linearly with image size instead of quadratically, which allows the same backbone to serve image classification, detection, instance segmentation and video understanding.

How shifted window attention works

Swin Transformer processes an image as a grid of small patches and applies window-based multi-head self-attention (W-MSA) within each window rather than across the whole image. The input is first split into 4 x 4 pixel patches, which a linear layer projects into token embeddings; tokens are then grouped into windows of 7 x 7 tokens in the standard configuration.

Pure window attention would isolate each window, so every second block uses shifted window attention (SW-MSA). The window grid is displaced by half a window, typically three tokens in each direction, so the new windows straddle the borders of the previous ones. An efficient implementation applies a cyclic shift to the feature map and an attention mask that prevents tokens from unrelated regions from attending to each other, which keeps the number of windows constant.

Each block also adds a relative position bias to the attention logits. This learned bias depends on the offset between two tokens inside a window and generalizes better than the absolute position embeddings used in the original vision transformer. The table below summarizes the main components of one Swin block pair.

ComponentFunctionEffect on the model
Patch partitionSplits the image into 4 x 4 patchesSets the finest token resolution
W-MSA blockAttention within regular windowsLocal modeling at linear cost
SW-MSA blockAttention within shifted windowsConnects neighboring windows
Relative position biasLearned offset-dependent termEncodes spatial layout inside a window
Patch mergingConcatenates 2 x 2 neighborsHalves resolution, doubles channels
Components of a Swin Transformer block pair

Hierarchical stages and model variants

The backbone is organized into four stages whose feature maps have strides of 4, 8, 16 and 32 relative to the input. Between stages, a patch merging layer concatenates each 2 x 2 group of neighboring tokens and projects them to twice the channel width. The result is a feature pyramid with the same shape as the outputs of a ResNet, so Swin can replace a convolutional backbone in existing detection and segmentation frameworks without architectural changes.

The original paper defined four sizes that differ in channel width and the number of blocks in the third stage. Approximate parameter counts and compute figures below refer to 224 x 224 inputs for classification.

VariantBase channelsBlocks per stageParametersCompute (GFLOPs)
Swin-T962, 2, 6, 2About 28 MAbout 4.5
Swin-S962, 2, 18, 2About 50 MAbout 8.7
Swin-B1282, 2, 18, 2About 88 MAbout 15.4
Swin-L1922, 2, 18, 2About 197 MAbout 34.5
Standard Swin Transformer variants

A later version, Swin Transformer V2, scaled the design to about 3 billion parameters and higher input resolutions. It replaced dot-product attention with scaled cosine attention, moved layer normalization after the residual branch for training stability, and introduced a log-spaced continuous position bias so that models pretrained with small windows transfer to larger ones.

Swin Transformer compared with ViT and CNNs

Swin Transformer sits between the global attention of ViT and the local convolutions of CNNs. ViT applies attention across all tokens of a single-scale map, which captures global context but scales quadratically with token count. Convolutional networks scale linearly and build hierarchies naturally but rely on fixed kernels. Swin borrows the hierarchy and locality of CNNs while keeping content-dependent attention weights.

PropertyVision transformer (ViT)Swin TransformerCNN such as ResNet
Attention or kernel scopeGlobal, all tokensLocal windows, shiftedFixed local kernel
Cost versus image sizeQuadraticLinearLinear
Feature mapsSingle scaleFour-scale pyramidMulti-scale pyramid
Inductive biasWeakModerateStrong
Fit for dense tasksNeeds adaptationNativeNative
Backbone families in computer vision

Later work showed that much of the advantage comes from training recipes and macro design rather than attention alone: ConvNeXt, a modernized CNN, matched Swin on several benchmarks. Hybrid and plain-ViT detectors have also narrowed the gap, so the choice of backbone now depends on available pretrained weights, hardware support and the downstream framework.

Where Swin is used and how to configure it

Swin is most valuable as a general-purpose backbone for dense prediction. It became a common choice in Mask R-CNN and Cascade R-CNN detectors, in UperNet segmentation heads, and in Video Swin Transformer, which extends windows to three dimensions for action recognition. It also appears in medical imaging models such as Swin-UNet and in image restoration networks such as SwinIR.

Configuration decisions center on window size, model size and pretraining data. Larger windows add context but raise the per-window cost, and the input resolution must be divisible by the product of patch size, window size and total downsampling, or the pipeline must pad the input.

SituationRecommended choiceReason
Limited GPU memorySwin-T with 7 x 7 windowsLowest compute, ResNet-50 class cost
High-accuracy detectionSwin-B or Swin-L with ImageNet-22K weightsLarge pretraining improves transfer
High-resolution segmentationLarger windows or Swin V2More context per window
Small labeled datasetPretrained weights, frozen early stagesReduces overfitting risk
Edge deploymentA lightweight CNN insteadWindow shifts and masks are less optimized
Configuration choices for typical projects

Limitations and common mistakes

Swin Transformer has practical costs that benchmark tables do not show. The cyclic shift and masking add memory operations that some inference runtimes and accelerators handle poorly, so measured latency can be worse than the FLOP count suggests. Receptive fields grow only gradually through shifts and merging, which means truly global context arrives in the deeper stages.

  • Ignoring resolution constraints: inputs that do not divide evenly into windows require padding that can shift object boundaries.
  • Reusing position bias tables across window sizes without interpolation, which degrades accuracy after transfer.
  • Training from scratch on small datasets, where weak inductive bias leads to overfitting compared with CNNs.
  • Comparing backbones under different recipes, which attributes gains from augmentation and schedules to the architecture.

The short version

A Swin Transformer is a way for a computer to look at a picture piece by piece. It does not compare every part of the image with every other part. Instead, it looks closely at small square neighborhoods. Then it slides those squares a little, so neighboring pieces can share what they found.

As the model goes deeper, it zooms out step by step. First it sees fine details, then larger shapes, then whole objects. This layered view is why it works well for finding and outlining objects in large photos, not only for naming what a picture shows.

Where it makes a difference

A team building an aerial inspection system for solar farms needs to outline cracked panels in drone images of 2,048 x 2,048 pixels. A plain vision transformer at that resolution would create about 16,000 tokens per image, and global attention would exhaust the memory of a single 24 GB GPU during training.

The team chooses Swin-B pretrained on ImageNet-22K as the backbone of a Mask R-CNN detector and keeps 7 x 7 windows. Because attention cost grows linearly, training fits on the available hardware with a batch of two images per GPU. The four-stage pyramid feeds a feature pyramid network, so small hairline cracks are detected at the high-resolution stage while whole damaged panels are recognized in the deeper stages. Compared with the previous ResNet-50 backbone, the team measures a clear gain in mask precision on its validation set, at the cost of roughly double the inference time per image, which is acceptable for offline inspection.