Hierarchical Vision Transformers
Shifted windows, multiscale features and dense prediction with transformers.
A plain ViT describes a 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 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, against , and evaluate both for Swin's first stage.
- Prove that alternating regular and shifted windows widens the region a token depends on by 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 ( 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.
| Input | Tokens | Query–key pairs per head, global () | Pairs with windows () |
|---|---|---|---|
| , 16-pixel patches | 196 | 38,416 | 9,604 |
| , 16-pixel patches | 4,200 | ||
| , 4-pixel patches | 66,800 |
Window attention and patch merging
The Swin Transformer (Liu et al., 2021) partitions an grid of tokens with channels into non-overlapping windows of tokens ( 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.
The query, key, value and output projections are four matrices applied to all tokens, whatever the attention pattern:
Global attention scores every token against every other, for , and the weighted sum of values costs the same:
With windows there are independent problems, each of tokens and cost . The quadratic term becomes linear in for fixed :
Swin-T's first stage has (a image in 4-pixel patches), and . The attention term shrinks by the factor , while the projections stay put:
For Swin-T's first stage (, , ), by what factor is one global attention layer more expensive than one window attention layer, projections included?
Show the answer
13.8 ×
million MACs either way. The attention term is million globally but million in windows. Totals: against million, a ratio of about . 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 group of neighboring tokens ( numbers) and maps them linearly to , which amounts to a convolution with stride 2. The four stages run at strides 4, 8, 16 and 32 with , , and channels, exactly the layout of a ResNet, so a Swin backbone can replace a ResNet in an existing detector or segmentation model. Swin-T (, 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 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 tokens in both directions, so that every shifted window straddles several regular ones.
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 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 tokens aligned with that partition.
Induction step. Suppose the token depends, through the last blocks, on an interval that is a union of consecutive windows of the partition used in block . The block before uses the other partition, whose window boundaries are offset from these by or by , never by . So the endpoints of fall strictly inside windows of the earlier partition, and meets exactly of them:
After blocks the interval has tokens, and the product of two such intervals is the claimed square. Without the shift, is a union of windows of the same partition that is used again, so it never grows past the first window.
So shifted-window attention widens a token's view by tokens per block, about as fast as a stack of stride-1 convolutions with kernels (whose receptive field is ), but with weights computed from content. Swin-T's first stage, two blocks with , already covers tokens, pixels, and every patch merging doubles the width of the patch each token stands for.
Four consecutive Swin blocks with alternate regular and shifted windows. How wide is the square of input tokens that one output token can depend on?
- 7 tokens
- 14 tokens
- 28 tokens
- 49 tokens
Show the answer
C. 28 tokens
Each block adds one window width: tokens across. Without the shift the answer would stay at 7 however many blocks were stacked.
Computing it efficiently. Displacing the partition creates windows, some of them smaller than : 81 instead of 64 in Swin-T's first stage, and instead of for a small map, 2.25 times the work if the small windows are padded. Swin instead rolls the whole map cyclically by 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.
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 rollCompared with attention computed directly on the displaced partition (with its smaller border windows), the result agrees to about on a grid with and , 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 to its scores, , read from a table 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 block of tokens is flattened, mapped linearly back to channels and layer-normalized, which cuts the cost of attention by . With at stride 4, the 3,136 queries of a 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 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, 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 window: local and fine, so it needs shifted windows and depth to see far. PVT's summarize 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 with a learned 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 pixels. The bias generator is fed log-spaced offsets, so that it can be reused when windows grow:
A continuous position bias computes from the offset between two tokens with a small network , so it is defined for offsets never seen in training. Swin V2 compresses large offsets before sees them:
Moving from windows (offsets in ) to windows () asks 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 pixels the stride-16 map has 4,096 tokens, so most blocks attend within non-overlapping windows of 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 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 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 instead of : for Swin-T's first stage, about against multiply–adds, after which the projections dominate.
- Alternating regular and shifted windows widens each token's view by tokens per block ( after 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 ; 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 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.
A stage has tokens of width . What does replacing global attention by window attention change in the cost ?
- The quadratic term becomes ; the projection term is unchanged
- Both terms shrink by the factor
- Only the projection term shrinks, because each window has fewer tokens to project
- Nothing: windows change which tokens interact, not how many multiply–adds are done
Show the answer
A. The quadratic term becomes ; the projection term is unchanged
Each of the windows costs for scores and weighted sums, in total, linear in . Every token is still projected once, so stays, and at Swin's first stage it becomes most of the cost.
What would happen inside a Swin stage if every block used the same regular window partition?
- The cost would become quadratic in the number of tokens
- The relative position bias would no longer be defined
- The stage would become invariant to permutations of its tokens
- No information would cross window borders in that stage: each token's view would stay its own window
Show the answer
D. No information would cross window borders in that stage: each token's view would stay its own 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 per block.
PVT's spatial-reduction attention with ratio cuts the cost of attention by . What does each query attend to?
- Only the tokens around it
- Keys and values covering the whole image, each summarizing an block of tokens
- A random subset of of the tokens, redrawn every step
- Only the class token, which summarizes the image
Show the answer
B. Keys and values covering the whole image, each summarizing an block of tokens
Keys and values are computed from flattened blocks mapped back to channels, so there are times fewer of them, but together they still cover every position. Attention stays global, at a coarser resolution than the queries.
Which recipe did ViTDet find sufficient to make a plain ViT a competitive detection backbone?
- A full feature pyramid network over four artificially divided stages of the ViT
- Global attention in every block, since windows lose too much context
- Window attention without shifting plus a few global propagation blocks, a simple pyramid from the last stride-16 map, and MAE pretraining
- 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 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).