Simple Algorithm
Deep Learning · Emergence · 26 min

Hierarchical Vision Transformers

Shifted windows, multiscale features and dense prediction with transformers.

A plain ViT describes a 224×224224\times224 image with 196 tokens at a single scale: enough for one label, awkward for boxes and masks. Detectors want fine features at several scales, and at the 800×1,333800\times1{,}333 pixels they typically see, a grid of 4-pixel patches has 66,800 tokens, about 4.5 billion query–key pairs per head in every layer. Hierarchical vision transformers rebuild the convolutional pyramid out of attention: local windows that shift, tokens that merge between stages, and keys that are pooled. Then plain ViTs, pretrained the right way, turned out to need less of this than expected.

What you’ll learn

  • Derive the cost of global and window self-attention, 4hwC2+2(hw)2C4hwC^2+2(hw)^2C against 4hwC2+2M2hwC4hwC^2+2M^2hwC, and evaluate both for Swin's first stage.
  • Prove that alternating regular and shifted windows widens the region a token depends on by MM tokens per block, and that the cyclic-shift implementation with masks computes exactly the shifted partition.
  • Compare the ways hierarchical transformers make attention affordable (windows, spatially reduced keys, pooling attention) and the changes that let Swin V2 scale.
  • Explain how plain ViTs became competitive detectors again (ViTDet, Hiera), and weigh what this says about which priors must be built in.

One scale is not enough

A CNN backbone hands an object detector a pyramid: feature maps at strides 4, 8, 16 and 32, fine maps for small objects and coarse, semantically strong maps for large ones, which a feature pyramid network combines (Detection, Segmentation & Video). A ViT-B/16 offers one map, at stride 16, and its attention cost grows with the square of the token count. Both limits bite at detection resolutions.

Hierarchical vision transformers keep the transformer block but change three things: they start from small patches (4×44\times4 pixels), so the first stage is fine-grained; they restrict or reduce attention so that its cost grows linearly with the number of tokens; and between stages they merge neighboring tokens, halving the resolution and doubling the width, as a strided convolution does in a ResNet.

InputTokens NNQuery–key pairs per head, global (N2N^2)Pairs with 7×77\times7 windows (49N49N)
224×224224\times224, 16-pixel patches19638,4169,604
800×1,333800\times1{,}333, 16-pixel patches4,2001.8×1071.8\times10^72.1×1052.1\times10^5
800×1,333800\times1{,}333, 4-pixel patches66,8004.5×1094.5\times10^93.3×1063.3\times10^6
Token grids are rounded up to whole patches (⌈1,333/16⌉=84\lceil1{,}333/16\rceil=84, ⌈1,333/4⌉=334\lceil1{,}333/4\rceil=334). Global attention on a stride-4 grid is out of reach; windows make the count proportional to NN.

Window attention and patch merging

The Swin Transformer (Liu et al., 2021) partitions an h×wh\times w grid of tokens with CC channels into non-overlapping windows of M×MM\times M tokens (M=7M=7 by default) and computes self-attention inside each window only. Its cost follows from counting multiply–adds (MACs), as the paper does, leaving out the softmax.

DerivationGlobal against window attention
  1. projections:4hwC2\text{projections:}\qquad 4hwC^2

    The query, key, value and output projections are four C×CC\times C matrices applied to all hwhw tokens, whatever the attention pattern:

  2. Ω(MSA)=4hwC2+2(hw)2C\Omega(\text{MSA})=4hwC^2+2(hw)^2C

    Global attention scores every token against every other, (hw)2C(hw)^2C for QK⊤QK^\top, and the weighted sum of values costs the same:

  3. Ω(W-MSA)=4hwC2+hwM2⋅2(M2)2C=4hwC2+2M2hwC\Omega(\text{W-MSA})=4hwC^2+\frac{hw}{M^2}\cdot2(M^2)^2C=4hwC^2+2M^2hwC

    With windows there are hw/M2hw/M^2 independent problems, each of M2M^2 tokens and cost 2(M2)2C2(M^2)^2C. The quadratic term becomes linear in hwhw for fixed MM:

  4. Ω(MSA)≈2.00×109,Ω(W-MSA)=1.16×108+0.30×108≈1.45×108\Omega(\text{MSA})\approx2.00\times10^9,\qquad\Omega(\text{W-MSA})=1.16\times10^8+0.30\times10^8\approx1.45\times10^8

    Swin-T's first stage has h=w=56h=w=56 (a 224×224224\times224 image in 4-pixel patches), C=96C=96 and M=7M=7. The attention term shrinks by the factor hw/M2=64hw/M^2=64, while the projections stay put:

Predict before you look

For Swin-T's first stage (h=w=56h=w=56, C=96C=96, M=7M=7), by what factor is one global attention layer more expensive than one window attention layer, projections included?

Show the answer

13.8 ×

4hwC2=115.64hwC^2=115.6 million MACs either way. The attention term is 2(hw)2C=1,8882(hw)^2C=1{,}888 million globally but 2M2hwC=29.52M^2hwC=29.5 million in windows. Totals: 2,0042{,}004 against 145145 million, a ratio of about 13.813.8. The attention term alone shrinks 64-fold, but after windowing the projections are four-fifths of the layer's cost, so further savings must come from elsewhere.

Patch merging. Between stages, Swin concatenates the features of each 2×22\times2 group of neighboring tokens (4C4C numbers) and maps them linearly to 2C2C, which amounts to a 2×22\times2 convolution with stride 2. The four stages run at strides 4, 8, 16 and 32 with CC, 2C2C, 4C4C and 8C8C channels, exactly the layout of a ResNet, so a Swin backbone can replace a ResNet in an existing detector or segmentation model. Swin-T (C=96C=96, stages of 2, 2, 6 and 2 blocks, heads of size 32) has 29 million parameters, costs 4.5 GFLOPs at 224 pixels and reached 81.3% ImageNet top-1. At that resolution its last stage is a single 7×77\times7 grid, one window, so attention there is global after all.

Shifted windows

Windows that never change never talk to each other: a token in one window cannot learn anything about the next, however deep the stack. Swin alternates two partitions in consecutive blocks, the regular one and one displaced by s=⌊M/2⌋s=\lfloor M/2\rfloor tokens in both directions, so that every shifted window straddles several regular ones.

DerivationProof
  1. I1=one window of partition L,∣I1∣=MI_1=\text{one window of partition }L,\qquad\abs{I_1}=M

    MLPs, norms and residual connections act on each token separately, so only attention spreads influence between tokens. Both partitions are products of 1-D partitions of the rows and of the columns, so it suffices to show that the region is an interval of LMLM tokens in one dimension. Work backward from the output: through the last block, a token depends on the window of the last partition that contains it, an interval of MM tokens aligned with that partition.

  2. Iℓ+1=⋃{windows of the earlier partition meeting Iℓ},∣Iℓ+1∣=(ℓ+1)MI_{\ell+1}=\bigcup\{\text{windows of the earlier partition meeting }I_\ell\},\qquad\abs{I_{\ell+1}}=(\ell+1)M

    Induction step. Suppose the token depends, through the last ℓ\ell blocks, on an interval IℓI_\ell that is a union of ℓ\ell consecutive windows of the partition used in block L−ℓ+1L-\ell+1. The block before uses the other partition, whose window boundaries are offset from these by ss or by M−sM-s, never by 00. So the endpoints of IℓI_\ell fall strictly inside windows of the earlier partition, and IℓI_\ell meets exactly ℓ+1\ell+1 of them:

  3. shifted: LM×LMunshifted: M×M\text{shifted: }LM\times LM\qquad\text{unshifted: }M\times M

    After LL blocks the interval has LMLM tokens, and the product of two such intervals is the claimed square. Without the shift, IℓI_\ell is a union of windows of the same partition that is used again, so it never grows past the first window. □\square

So shifted-window attention widens a token's view by MM tokens per block, about as fast as a stack of stride-1 convolutions with (M+1)×(M+1)(M+1)\times(M+1) kernels (whose receptive field is 1+LM1+LM), but with weights computed from content. Swin-T's first stage, two blocks with M=7M=7, already covers 14×1414\times14 tokens, 56×5656\times56 pixels, and every patch merging doubles the width of the patch each token stands for.

Check your understanding

Four consecutive Swin blocks with M=7M=7 alternate regular and shifted windows. How wide is the square of input tokens that one output token can depend on?

  1. 7 tokens
  2. 14 tokens
  3. 28 tokens
  4. 49 tokens
Show the answer

C. 28 tokens

Each block adds one window width: 4×7=284\times7=28 tokens across. Without the shift the answer would stay at 7 however many blocks were stacked.

Computing it efficiently. Displacing the partition creates (⌈h/M⌉+1)(⌈w/M⌉+1)(\lceil h/M\rceil+1)(\lceil w/M\rceil+1) windows, some of them smaller than M×MM\times M: 81 instead of 64 in Swin-T's first stage, and 3×33\times3 instead of 2×22\times2 for a small map, 2.25 times the work if the small windows are padded. Swin instead rolls the whole map cyclically by ss toward the top left, partitions it regularly, and masks attention between tokens that the roll brought together from opposite borders. Inside each rolled window, tokens then attend only to tokens from the same displaced window (a window at the border holds pieces of up to four), so the result equals attention within the shifted partition, computed with the regular number of windows.

python
import torch
import torch.nn.functional as F

def windows(x, M):                    # (B, H, W, C) -> (B * H/M * W/M, M*M, C)
    B, H, W, C = x.shape
    x = x.view(B, H // M, M, W // M, M, C).transpose(2, 3)
    return x.reshape(-1, M * M, C)

def shifted_window_attention(x, M, s):  # one head, projections omitted for brevity
    B, H, W, C = x.shape
    region = torch.zeros(1, H, W, 1)      # label the 3 x 3 blocks the roll will bring together
    cuts = (slice(0, -M), slice(-M, -s), slice(-s, None))
    for i, (a, b) in enumerate([(a, b) for a in cuts for b in cuts]):
        region[:, a, b] = i
    r = windows(region, M).squeeze(-1)    # (n_windows, M*M)
    mask = (r[:, :, None] == r[:, None, :]).repeat(B, 1, 1)
    xw = windows(torch.roll(x, shifts=(-s, -s), dims=(1, 2)), M)
    out = F.scaled_dot_product_attention(xw, xw, xw, attn_mask=mask)
    out = out.view(B, H // M, W // M, M, M, C).transpose(2, 3).reshape(B, H, W, C)
    return torch.roll(out, shifts=(s, s), dims=(1, 2))   # undo the roll

Compared with attention computed directly on the displaced partition (with its smaller border windows), the result agrees to about 10−610^{-6} on a 56×5656\times56 grid with M=7M=7 and s=3s=3, using 64 windows instead of 81. In Swin the mask is precomputed rather than rebuilt on every call, and each head also adds a learned relative position bias to its scores.

Position as a bias. Swin uses no absolute position embedding. Each head adds a bias B∈RM2×M2B\in\R^{M^2\times M^2} to its scores, softmax⁡(QK⊤/d+B)V\softmax(QK^\top/\sqrt d+B)V, read from a table B^∈R(2M−1)×(2M−1)\hat B\in\R^{(2M-1)\times(2M-1)} indexed by the relative offset of the two tokens. The ablations on Swin-T say what each piece buys: without shifting, ImageNet top-1 fell from 81.3% to 80.2%, COCO box AP from 50.5 to 47.7 and ADE20K mIoU from 46.1 to 43.3; without any position information top-1 was 80.1%. ViT-style absolute embeddings, compared with none, raised top-1 by 0.4 points but lowered COCO AP by 0.2 and ADE20K mIoU by 0.6, and the relative bias alone was at least as good as every alternative on all three tasks. On a V100 GPU the cyclic version ran Swin-T at 755 images per second, against 770 without shifting, 670 with padded windows and 183 for a naive sliding-window attention, whose overlapping neighborhoods map poorly onto memory.

Other ways to build the pyramid

Windows are one way to make attention linear in the number of tokens. Two others keep every query global but shrink what it attends to.

  • Spatial-reduction attention (PVT). The Pyramid Vision Transformer (Wang et al., 2021) has four stages at strides 4, 8, 16 and 32, each opening with its own patch embedding and position embeddings. Inside a stage the queries keep full resolution, but keys and values are reduced first: every Ri×RiR_i\times R_i block of tokens is flattened, mapped linearly back to CiC_i channels and layer-normalized, which cuts the cost of attention by Ri2R_i^2. With R1=8R_1=8 at stride 4, the 3,136 queries of a 224×224224\times224 image attend to 49 keys.
  • Pooling attention (MViT). Multiscale Vision Transformers (Fan et al., 2021), designed for video as well as images, pool queries, keys and values with strided pooling kernels before attending. Pooled keys and values shorten what each query reads; pooled queries shrink the output itself, which is how MViT passes from one stage to the next while it expands the channels.
Think first For a 224×224224\times224 image, PVT's first stage and Swin's first stage both let each of 3,136 queries attend to 49 keys. Do they cost the same, and do they compute the same kind of thing?

Their attention terms cost the same, 2⋅49⋅hwC2\cdot49\cdot hwC multiply–adds; PVT also pays for the linear maps that build its reduced keys and values. What the 49 keys are differs completely. Swin's are the full-resolution neighbors in the query's 7×77\times7 window: local and fine, so it needs shifted windows and depth to see far. PVT's summarize 8×88\times8 blocks of tokens covering the whole image: global but coarse, so a query cannot compare itself with the fine detail of a distant patch.

Scaling up (Swin V2). Liu et al. (2022) found that very large Swin models trained unstably: in pre-norm blocks the activations grew from layer to layer. Swin V2 normalizes each block's output before adding it to the residual path ("res-post-norm"); because some heads then came to be dominated by a few pairs of tokens, it also replaces dot products by scaled cosine similarities cos⁡(qi,kj)/τ+Bij\cos(\mathbf q_i,\mathbf k_j)/\tau+B_{ij} with a learned τ>0.01\tau>0.01 per head and layer, and generates the relative bias with a small MLP of the offsets. With these changes, and SimMIM masked-image pretraining, it trained a 3-billion-parameter model on images up to 1,536×1,5361{,}536\times1{,}536 pixels. The bias generator is fed log-spaced offsets, so that it can be reused when windows grow:

DerivationWhy log-spaced offsets extrapolate better
  1. Δ^=sign⁡(Δ) ln⁡(1+∣Δ∣),B(Δx,Δy)=G(Δ^x,Δ^y)\hat\Delta=\sign(\Delta)\,\ln\big(1+\abs\Delta\big),\qquad B(\Delta x,\Delta y)=G\big(\hat\Delta x,\hat\Delta y\big)

    A continuous position bias computes BB from the offset between two tokens with a small network GG, so it is defined for offsets never seen in training. Swin V2 compresses large offsets before GG sees them:

  2. 15−77≈1.14againstln⁡16−ln⁡8ln⁡8=2.773−2.0792.079≈0.33\frac{15-7}{7}\approx1.14\qquad\text{against}\qquad\frac{\ln16-\ln8}{\ln8}=\frac{2.773-2.079}{2.079}\approx0.33

    Moving from 8×88\times8 windows (offsets in [−7,7][-7,7]) to 16×1616\times16 windows ([−15,15][-15,15]) asks GG to extrapolate beyond its trained range by 1.14 times that range in raw coordinates, but by only 0.33 times in log coordinates, about four times less:

Plain backbones strike back

Hierarchical designs ask how to make a transformer look like a CNN. Li, Mao, Girshick & He (2022) asked the opposite question: how little must change to use a plain ViT, pretrained as usual, as a detection backbone? Their ViTDet left pretraining alone and changed three things in fine-tuning:

  • A simple feature pyramid. From the last map alone, at stride 16, parallel layers produce maps at strides 32, 16, 8 and 4: a stride-2 downsampling, the identity, and deconvolutions upsampling by 2 and by 4. No lateral connections between stages, which a plain ViT does not have anyway.
  • Windows without shifting. At 1,024×1,0241{,}024\times1{,}024 pixels the stride-16 map has 4,096 tokens, so most blocks attend within non-overlapping windows of 14×1414\times14 tokens, the size of the pretraining grid. Information crosses windows only in four propagation blocks, one at the end of each quarter of the network, which attend globally; adding a small residual convolution block after each quarter instead worked about as well. For a ViT-L with Mask R-CNN, four global blocks raised box AP from 52.9 (windows only) to 54.6, shifting the windows Swin-style during fine-tuning only to 54.0, and global attention in all 24 blocks to 55.1, at the price of memory checkpointing.
  • The right pretraining. With Mask R-CNN on COCO, supervised ImageNet-1k pretraining was slightly worse than random initialization, while masked-autoencoder pretraining on the same images, without their labels, gained 3.1 box AP over random initialization for ViT-B and 4.6 for ViT-L.

With MAE pretraining on ImageNet-1k alone, ViTDet with a ViT-H backbone reached 61.3 box AP on COCO, competitive with the leading detectors built on hierarchical backbones.

Ryali et al. (2023) drew the same lesson for hierarchical models. Starting from MViTv2, they removed or simplified every non-transformer component and let MAE pretraining teach the spatial bias instead, leaving none of what they called bells and whistles: no convolutions, no shifted or cross-shaped windows, no decomposed relative position embeddings. Their Hiera is a stack of standard ViT blocks, with local attention inside "mask units" in its first two stages, global attention after, and 2×22\times2 max pooling of the queries and skip connections at each stage transition. It was 2.4 times faster on images and 5.1 times faster on video than the MViTv2 it started from, and more accurate.

Key takeaways

  • Plain ViTs give one stride-16 map and a cost quadratic in the number of tokens; hierarchical transformers start from 4×44\times4 patches, make attention linear in the token count and merge tokens between stages, giving maps at strides 4 to 32 like a ResNet.
  • Window attention costs 4hwC2+2M2hwC4hwC^2+2M^2hwC instead of 4hwC2+2(hw)2C4hwC^2+2(hw)^2C: for Swin-T's first stage, about 1.45×1081.45\times10^8 against 2.0×1092.0\times10^9 multiply–adds, after which the projections dominate.
  • Alternating regular and shifted windows widens each token's view by MM tokens per block (LM×LMLM\times LM after LL blocks), while unshifted windows never connect; a cyclic roll with masks computes the shifted partition exactly with the regular number of windows.
  • PVT keeps queries global but reduces keys and values by R2R^2; MViT pools queries, keys and values; Swin V2's post-norm residuals, cosine attention and log-spaced continuous bias let it scale to 3 billion parameters and 1,536×1,5361{,}536\times1{,}536 images.
  • ViTDet (a plain ViT, a simple pyramid from one stride-16 map, unshifted windows with four global blocks, MAE pretraining) reached 61.3 box AP on COCO, and Hiera stripped a hierarchical ViT to standard blocks: with strong pretraining, much of the spatial bias can be learned rather than built in.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A stage has h×wh\times w tokens of width CC. What does replacing global attention by M×MM\times M window attention change in the cost 4hwC2+2(hw)2C4hwC^2+2(hw)^2C?

  1. The quadratic term 2(hw)2C2(hw)^2C becomes 2M2hwC2M^2hwC; the projection term 4hwC24hwC^2 is unchanged
  2. Both terms shrink by the factor hw/M2hw/M^2
  3. Only the projection term shrinks, because each window has fewer tokens to project
  4. Nothing: windows change which tokens interact, not how many multiply–adds are done
Show the answer

A. The quadratic term 2(hw)2C2(hw)^2C becomes 2M2hwC2M^2hwC; the projection term 4hwC24hwC^2 is unchanged

Each of the hw/M2hw/M^2 windows costs 2(M2)2C2(M^2)^2C for scores and weighted sums, 2M2hwC2M^2hwC in total, linear in hwhw. Every token is still projected once, so 4hwC24hwC^2 stays, and at Swin's first stage it becomes most of the cost.

Question 2

What would happen inside a Swin stage if every block used the same regular window partition?

  1. The cost would become quadratic in the number of tokens
  2. The relative position bias would no longer be defined
  3. The stage would become invariant to permutations of its tokens
  4. No information would cross window borders in that stage: each token's view would stay its own M×MM\times M window
Show the answer

D. No information would cross window borders in that stage: each token's view would stay its own M×MM\times M window

Only attention mixes tokens, and with one fixed partition it mixes only within windows. The union of a window with itself is the window, however many blocks are stacked. Alternating with a shifted partition is what widens the view by MM per block.

Question 3

PVT's spatial-reduction attention with ratio RR cuts the cost of attention by R2R^2. What does each query attend to?

  1. Only the R×RR\times R tokens around it
  2. Keys and values covering the whole image, each summarizing an R×RR\times R block of tokens
  3. A random subset of 1/R21/R^2 of the tokens, redrawn every step
  4. Only the class token, which summarizes the image
Show the answer

B. Keys and values covering the whole image, each summarizing an R×RR\times R block of tokens

Keys and values are computed from flattened R×RR\times R blocks mapped back to CC channels, so there are R2R^2 times fewer of them, but together they still cover every position. Attention stays global, at a coarser resolution than the queries.

Question 4

Which recipe did ViTDet find sufficient to make a plain ViT a competitive detection backbone?

  1. A full feature pyramid network over four artificially divided stages of the ViT
  2. Global attention in every block, since windows lose too much context
  3. Window attention without shifting plus a few global propagation blocks, a simple pyramid from the last stride-16 map, and MAE pretraining
  4. Supervised ImageNet-1k pretraining, which beat masked-autoencoder pretraining by several AP
Show the answer

C. Window attention without shifting plus a few global propagation blocks, a simple pyramid from the last stride-16 map, and MAE pretraining

ViTDet built its pyramid from the single last map with strided and transposed convolutions, used 14×1414\times14 windows with four global propagation blocks, and relied on MAE pretraining, which added 3.1 to 4.6 box AP while supervised ImageNet-1k pretraining slightly hurt.

Further reading

  • Z. Liu, Y. Lin, Y. Cao, H. Hu, Y. Wei, Z. Zhang, S. Lin & B. Guo, "Swin Transformer: Hierarchical vision transformer using shifted windows," ICCV (2021).
  • W. Wang, E. Xie, X. Li, D.-P. Fan, K. Song, D. Liang, T. Lu, P. Luo & L. Shao, "Pyramid vision transformer: A versatile backbone for dense prediction without convolutions," ICCV (2021).
  • H. Fan, B. Xiong, K. Mangalam, Y. Li, Z. Yan, J. Malik & C. Feichtenhofer, "Multiscale vision transformers," ICCV (2021).
  • Y. Li, H. Mao, R. Girshick & K. He, "Exploring plain vision transformer backbones for object detection," ECCV (2022).
  • C. Ryali et al., "Hiera: A hierarchical vision transformer without the bells-and-whistles," ICML (2023).