Foundations to Frontier
Tests
G. Computer Vision and Remote Sensing › G3 Modern Vision Architectures

Swin Transformer: hierarchical backbones, Swin V2 and dense prediction

The Swin Transformer (Liu and colleagues, ICCV 2021) made Transformers practical for detection and segmentation. It attends within shifted local windows and merges patches between stages, producing CNN-like feature maps at strides 4 to 32. This page builds on the basic Swin page and looks at what came next. Swin V2 (CVPR 2022) scaled to 3 billion parameters and 1536 × 1536 inputs with post-normalisation, scaled cosine attention and a log-spaced continuous position bias that transfers to larger windows. Competing hierarchical designs followed: ConvNeXt, MViTv2, Hiera (the SAM 2 encoder) and plain ViTs with a simple feature pyramid (ViTDet). In the exercises you compute window versus global attention cost (13.81× at Swin-T's first stage), relative-position indices, log-spaced coordinates and cosine attention. You then learn a position bias at window 8 and transfer it to windows 16 and 24 four ways. A log-spaced MLP beat a linear-coordinate MLP in every case. With a distance penalty in the true bias it was best (attention error 0.058 at window 24, against 0.192 for Swin V1's stretched table). For purely local biases, simply reusing the edge value was better (0.064 against 0.111): no extrapolation rule wins everywhere.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Windows, stages and growing images

A Swin Transformer looks at an image through small windows, like reading a map one grid square at a time, and shifts the grid so neighbouring squares talk to each other. Between stages it zooms out, merging four squares into one, so it ends up with a pyramid of maps: fine detail at the bottom, the big picture at the top. Detection and segmentation need exactly that pyramid. Swin V2 asked how to grow such a model to huge images and windows. One trick is to describe how far apart two patches are on a logarithmic scale, so that a model trained with small windows is not surprised by large ones. The demo compares linear and logarithmic distance scales.

Vision architecture lab
Pretrained window 8 (offsets up to 7, dashed line), run at window 16. Linear coordinates (teal) must extrapolate to 2.14× the trained range; log-spaced coordinates (orange) only to 1.32×.
Why engineers care

Hierarchical backbones such as Swin, ConvNeXt and Hiera power detectors and segmenters for aerial and satellite imagery, where objects range from a few pixels (vehicles) to thousands (airfields).

📝 Quick check (Level 0)
0/3 answered
  1. 1. Swin computes attention…
  2. 2. A hierarchical backbone outputs…
  3. 3. Log-spaced coordinates help when…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Hierarchical vision backbones after Swin

  • Swin recap (e12-24): 4 × 4 patches, 7 × 7 windows shifted by 3 in alternate blocks, patch merging between four stages (strides 4, 8, 16, 32; channels C, 2C, 4C, 8C), a learned relative position bias table of (2M − 1)² entries per head. Swin-T: C = 96, depths 2-2-6-2, 28M parameters, 4.5 GMACs at 224 px.
  • Cost: attention on an h × w map costs 4hwC² + 2(hw)²C globally and 4hwC² + 2M²hwC in windows, linear in image area.
  • Swin V2 (Liu et al., CVPR 2022): residual post-normalisation (LayerNorm after each block, to stop activations growing with depth); scaled cosine attention, cos(q, k)/τ with learned τ ≥ 0.01; a continuous position bias (CPB) from a small MLP on log-spaced offsets; SimMIM masked pre-training. SwinV2-G: 3B parameters, up to 1536 × 1536 inputs with correspondingly larger windows.
  • ConvNeXt (Liu et al., CVPR 2022): a ResNet modernised with Swin’s design choices (7 × 7 depthwise convolutions, LayerNorm, GELU, inverted bottlenecks) matches Swin; ConvNeXt V2 (2023) adds masked pre-training.
  • Other hierarchies: PVT (2021), MViTv2 (CVPR 2022), Hiera (Ryali et al., ICML 2023), a stripped-down hierarchical ViT pre-trained with MAE, used as SAM 2’s image encoder.
  • Plain backbones for detection: ViTDet (Li et al., ECCV 2022) builds a simple feature pyramid from a plain ViT’s last map and uses window attention with a few global blocks; this made MAE- or DINO-pre-trained ViTs competitive detectors.
  • Heads: FPN and UperNet for multi-scale features; Mask R-CNN, Cascade R-CNN, DINO-DETR and Mask2Former for detection and segmentation.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Swin V2 replaces dot-product attention with…
  2. 2. SAM 2's image encoder is…
  3. 3. ViTDet gets multi-scale features from a plain ViT by…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Backbones for dense prediction

Exercise 1.

  • Window vs global attention cost.
  • The relative-position index of a window.
  • Swin V2 log-spaced coordinates and cosine attention scores.

Practice.

  • For detection and segmentation pick a backbone with multi-scale outputs (Swin, ConvNeXt, Hiera) or a plain ViT with a simple feature pyramid; frameworks (MMDetection, Detectron2, timm features_only=True) expose strides 4–32.
  • When fine-tuning at a larger window or resolution, prefer models with continuous or relative position schemes (Swin V2 CPB, RoPE); old bias tables must be interpolated.
  • Window size should divide the token map; pad otherwise and mask the padding.
  • Compare backbones at equal compute and with the same head and schedule; much of a reported gain comes from recipes.
  • For very large images (whole satellite scenes) combine windowed backbones with sliding-window inference and overlap.
import timm, torch
# Swin V2 at a larger window than pre-training: the log-spaced CPB MLP produces biases for the new offsets
m = timm.create_model("swinv2_base_window12to24_192to384.ms_in22k_ft_in1k", pretrained=True, features_only=True)
feats = m(torch.randn(1, 3, 384, 384))
for f in feats: print(f.shape)       # 4 maps at strides 4, 8, 16, 32 (channels-last in timm)
🐍 Exercise 1: windows, indices and coordinates
Compute attention costs, the relative-position index of a window, log-spaced coordinates and cosine attention scores.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Detection heads such as FPN need…
  2. 2. The timm option that returns stage outputs is…
  3. 3. A fair backbone comparison keeps fixed…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why windows scale. Global attention scores cost 2(hw)²C, windows 2M²hwC: the ratio is hw/M², 64 for Swin-T’s 56 × 56 first stage with M = 7. Including the 4hwC² projections, the whole block is 13.81× cheaper.

Relative bias and window transfer. Swin adds B[Δy, Δx] to the attention logits, a table over the (2M − 1)² possible offsets. A model pre-trained with M₀ = 8 and fine-tuned with M = 24 needs biases for offsets up to 23 it has never seen. Swin V1 resized the table like an image (bicubic), which maps offset 23 onto offset 7: every distance is shrunk by a factor of about 3. Swin V2 instead computes the bias with a small MLP G(Δ) on log-spaced coordinates x̂ = sign(x)·log₂(1 + |x|)/log₂ 8 with x = 8Δ/(M₀ − 1). The trained range is |x̂| ≤ 1.057; offset 23 maps to 1.590, an extrapolation of 1.50× instead of 23/7 = 3.29× in linear coordinates.

Extrapolation needs an assumption. Any rule for unseen offsets encodes a belief about the bias there: edge extension assumes it flattens, a linear-coordinate MLP continues its last slope, a log-coordinate MLP continues a slope in log-distance. Only fine-tuning at the new window can check the belief.

Cosine attention. Dot-product logits grow with activation norms, which in large models let a few heads and tokens dominate; cos(q, k)/τ bounds logits to ±1/τ.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Resizing a bias table from window 8 to 24 like an image…
  2. 2. Log-spaced coordinates reduce the extrapolation range at window 24 from 3.29× to…
  3. 3. Cosine attention bounds logits to…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How should a relative position bias learned at one window size be transferred to a larger window?

History.

  • Z. Liu et al., “Swin Transformer” (ICCV 2021): bias tables resized by bicubic interpolation for larger windows.
  • Z. Liu et al., “Swin Transformer V2: scaling up capacity and resolution” (CVPR 2022): log-spaced continuous position bias.
  • B. Heo et al., “Rotary position embedding for vision transformer” (ECCV 2024): RoPE as an alternative that extrapolates.

Exercise 2. Position-only attention in a window.

  • True biases: random smooth functions of the offset, two anisotropic exponential bumps with random heights (0.5–2) and length scales (1–6); in a second family, also a distance penalty −0.15·|Δ| (ALiBi-like) that keeps growing.
  • Learning: the bias table at window 8 (15 × 15 offsets) is observed with noise 0.1; a 2-layer ReLU MLP (32 hidden units, Adam, 300 steps) is fitted on linear or log-spaced coordinates.
  • Transfer to windows 16 and 24: stretch the table (Swin V1), extend it with edge values, or evaluate either MLP.
  • Measure: mean total-variation distance between the position-only attention rows softmax(b(k − q)) produced by the transferred and the true bias, over every query in the window (0 = identical); 3 functions per setting.
true bias window stretched table edge extension MLP, linear MLP, log-spaced
local bumps 16 0.065 0.045 0.090 0.060
local bumps 24 0.114 0.064 0.195 0.111
bumps + distance penalty 16 0.136 0.090 0.119 0.045
bumps + distance penalty 24 0.192 0.202 0.105 0.058
  • Log-spaced beat linear coordinates in all four settings on all three seeds: the network extrapolates over a 1.5× rather than 3.3× range.
  • Stretching the table (Swin V1) was never best: it shrinks distances.
  • No rule wins everywhere: when the true bias flattens beyond the trained range, edge extension was best (seeds 1 and 2 at window 24: 0.054 and 0.045, against 0.097 and 0.111 for the log MLP; at window 16 the two were close, and seed 1 favoured log 0.046 against 0.049). When the bias keeps falling, the log MLP was best on every seed (window 24: 0.056 and 0.072).
  • Caveat: synthetic biases and position-only attention; real models fine-tune after transfer, which repairs much of the error.
🐍 Exercise 2 (research): how should a relative position bias learned at one window size be transferred to a larger window?
Learn a relative position bias at window 8 and compare four ways of transferring it to windows 16 and 24.

Hierarchical backbones in AI, robotics and aerospace

  • Earth observation: SatlasPretrain (Bastani et al., ICCV 2023) trained Swin backbones on Sentinel-2 and NAIP imagery for many dense tasks; windowed backbones with sliding-window inference handle full scenes.
  • Robotics: segmenters such as SAM 2 (Hiera encoder) and Mask2Former give object masks for grasping and navigation.
  • Inspection: crack and defect segmentation on airframes and solar panels needs stride-4 features for thin structures.

References

  1. Z. Liu et al. (2021). “Swin Transformer: hierarchical vision transformer using shifted windows.” ICCV.
  2. Z. Liu et al. (2022). “Swin Transformer V2: scaling up capacity and resolution.” CVPR.
  3. Z. Liu et al. (2022). “A ConvNet for the 2020s.” CVPR.
  4. Y. Li, H. Mao, R. Girshick and K. He (2022). “Exploring plain vision transformer backbones for object detection.” ECCV.
  5. C. Ryali et al. (2023). “Hiera: a hierarchical vision transformer without the bells-and-whistles.” ICML.
  6. Y. Li et al. (2022). “MViTv2: improved multiscale vision transformers for classification and detection.” CVPR.
  7. B. Cheng et al. (2022). “Masked-attention mask transformer for universal image segmentation.” CVPR.
  8. F. Bastani et al. (2023). “SatlasPretrain: a large-scale dataset for remote sensing image understanding.” ICCV.