Skip to content
AI.info

Deep architectures

Vision Transformers and Hierarchical Visual Attention

Explain patch tokenization, global and windowed visual attention, hierarchical stages, and the trade-offs between learned flexibility and visual inductive bias.

By the end you can

Example

One image, several possible tokenizations

How tokens are built determines what detail is available before attention begins.

Two papers fix the numbers behind the first two bullets. Sixteen pixels a side was the original choice: cut the image into 16x16 patches, flatten them, feed the sequence to a plain transformer. Dosovitskiy and eleven co-authors showed in 2021 that this is enough. Their finding was that “a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks”, provided it is “pre-trained on large amounts of data”. Swin Transformer went four times finer, the same year. It uses “a patch size of 4 × 4 and thus the feature dimension of each patch is 4 × 4 × 3 = 48”. Attention is then confined to windows whose size “is set to M = 7 by default”. Sixteen pixels a side or four is not a detail for the engineer to settle later. It is the scale at which the model performs its first irreversible averaging.

The third bullet has a measured price. Replace ViT's default stride-16 16x16 patchify stem with a small stack of stride-two 3x3 convolutions. Drop one transformer block so that flops and runtime stay constant. The model then gets better on both axes at once: “Using a convolutional stem in ViT dramatically increases optimization stability and also improves peak performance (by ∼1-2% top-1 accuracy on ImageNet-1k), while maintaining flops and runtime.” Xiao and five co-authors reported that in 2021.

The stability half carries the larger number. For the patchify-stem baseline the AdamW-versus-SGD accuracy gap reaches up to 10 points, and training sometimes diverges outright. For the convolutional-stem models at large sizes and long schedules it falls below 0.2 points, and sensitivity to learning rate and weight decay moves 'closer to that of modern CNNs'. The gain is not a special case. It holds from 1G to 36G flops and from ImageNet-1k to ImageNet-21k. Note what it is not. The fragility is sharply reduced, not eliminated.

  • Large patches reduce sequence length but can hide thin cracks or small objects inside one token.
  • Small patches preserve detail while increasing attention cost and activation memory.
  • Convolutional stems inject local processing before tokens enter Transformer blocks: Xiao and co-authors price the swap at roughly 1-2 top-1 points on ImageNet-1k, at equal flops and runtime.
  • Overlapping patches reduce hard boundary effects but complicate the interpretation of token count.
  • Multiscale tokenization can represent both global context and fine structure at different stages.

The original Vision Transformer is deliberately simple

A Vision Transformer splits an image into patches, projects each patch to an embedding, adds positional information, and processes the sequence with Transformer encoder blocks.

A classification token or pooled representation feeds the output head. The architecture offers global interaction early. What it lacks is the strong locality and translation bias built into convolution.

Patch size is an architectural decision about resolution, cost, and which patterns can be represented early.

Comparison

Flat and hierarchical visual Transformers solve different scaling problems

The choice affects feature resolution. It also affects detection interfaces and computational shape.

Two of these four options have a published exchange rate rather than a hedge. Stack depthwise convolution stages under attention stages and you get CoAtNet: “Without extra data, CoAtNet achieves 86.0% ImageNet top-1 accuracy; When pre-trained with 13M images from ImageNet-21K, our CoAtNet achieves 88.56% top-1 accuracy, matching ViT-huge pre-trained with 300M images from JFT-300M while using 23x less data”. Dai and three co-authors reported that in 2021. Scaled further with JFT-3B, the same family reaches 90.88%. So the hybrid column is not a vague suitability for moderate data. Thirteen million images bought what 300 million bought a pure ViT. That is a factor of 23.

Token merging has its own rate. Combine similar tokens gradually inside an already-trained ViT, with no retraining at all, and the throughput doubles for almost nothing: “Off-the-shelf, ToMe can 2x the throughput of state-of-the-art ViT-L @ 512 and ViT-H @ 518 models on images and 2.2x the throughput of ViT-L on video with only a 0.2-0.3% accuracy drop in each case.” Bolya and five co-authors reported that in 2023. Two times the throughput for two or three tenths of a point, on a named model at a named resolution. That is the sentence the trade-off column should be read against.

FigureComparison · 4 columns

Flat global ViT

Maintains one token scale and allows broad interaction.

  • Simple repeated block
  • Global receptive field
  • Quadratic token interaction
  • Needs sufficient data or pretraining

Windowed hierarchy

Restricts attention locally and changes resolution across stages.

  • Lower cost at high resolution
  • Natural multiscale outputs
  • Window boundaries require communication
  • More architectural machinery

Convolution–attention hybrid

Uses local operators and attention in complementary stages.

  • Strong early visual bias
  • Flexible global mixing later
  • Extra design choices
  • May fit moderate-data regimes

Token pruning or merging

Reduces computation by discarding or combining visual tokens.

  • Adaptive efficiency
  • Can focus on salient regions
  • Risks losing small evidence
  • Routing decisions need validation

Visual

A hierarchical visual backbone

Resolution falls. Channel capacity and semantic abstraction usually rise.

The last stage is where the pyramid is paid for. Put a convolution-free hierarchical backbone with a progressive shrinking pyramid under an off-the-shelf detector and the score moves: “For example, with a comparable number of parameters, PVT+RetinaNet achieves 40.4 AP on the COCO dataset, surpassing ResNet50+RetinNet (36.3 AP) by 4.1 absolute AP.” That is the Pyramid Vision Transformer, from Wang and eight co-authors in 2021. The spelling of RetinNet is the published abstract's own.

The detector and the parameter budget were held comparable. Only the backbone changed. Exposing several scales to a dense-prediction head was worth 4.1 absolute AP. That is a number, not an argument that hierarchy ought to help detection.

FigureProcess · 5 steps
  1. 1

    Patch or stem stage

    Construct high-resolution visual tokens.

  2. 2

    Local interaction stage

    Model edges, textures, and nearby parts.

  3. 3

    Merge or downsample

    Reduce token count and expand receptive coverage.

  4. 4

    Higher-level stages

    Represent objects, scenes, and long-range relations.

  5. 5

    Task-specific neck or head

    Expose one or several scales to classification, detection, or segmentation.

Analogy

Reading a mural through movable frames

A mural can be studied through square frames. Small frames preserve brushwork. Large frames reveal composition. Moving and overlapping them lets neighboring regions exchange context.

A frame holds a literal crop of the wall. Visual tokens are learned vectors after the first projection. Frame size and communication pattern still shape what the model can recover.

Visual attention still depends on the resolution and geometry established before the first attention score.

Key idea

Weak visual bias transfers burden to data and training

A flexible global architecture can learn useful visual regularities. It may also need more examples, stronger augmentation, or large-scale pretraining than a convolutional baseline.

That has been measured rather than asserted. Train ConViT-S and DeiT-S under the identical DeiT recipe on subsampled ImageNet-1k, and the premium for built-in locality turns into a curve. At 5% of the images per class the soft-convolutional model scored 47.8% top-1 against DeiT-S's 34.8%, a relative gain of 37%. At 10% it was 59.6% against 48.0%. On the full dataset it was 81.4% against 79.9%, a relative gain of 2%. The table is d'Ascoli and five co-authors, 2021. Its caption states the finding in six words: “The convolutional inductive bias strongly improves sample efficiency.” Now read the premium down the column. The advantage of built-in locality shrinks toward nothing as the data arrives.

The far end of the same curve is also on the record. Scale ViT models and data up and down, chart error rate against data and compute, and the top of that chart reads: “As a result, we successfully train a ViT model with two billion parameters, which attains a new state-of-the-art on ImageNet of 90.45% top-1 accuracy. The model also performs well for few-shot transfer, for example, reaching 84.86% top-1 accuracy on ImageNet with only 10 examples per class.” Zhai and three co-authors published that in 2022. Ten labelled examples per class and 84.86% together locate the burden. It sits in pre-training scale, not in the downstream label count.

Do not read this as a universal ranking. Dataset size, label quality, resolution, objective, and optimization recipe can reverse the result. In the ConViT table, run under one fixed recipe, the reversal is visible between the 5% row and the 100% row.

Compare architectures under matched pretraining, augmentation, resolution, and compute.

Case

DeiT reached 83.1 per cent on ImageNet alone, with the same backbone

The data appetite might belong to the architecture. It might belong to the training recipe. DeiT tested which. The answer came back on the side of the recipe: “we produce competitive convolution-free transformers trained on ImageNet only using a single computer in less than 3 days”. An 86-million-parameter reference model reached “top-1 accuracy of 83.1% (single-crop) on ImageNet with no external data”. It rose to 85.2% once a convnet teacher is distilled through an added token. Touvron and five co-authors published that in 2021.

The backbone did not change between that result and the ones that needed hundreds of millions of pre-training images. The training procedure did.

Figure

Two routes past the vision transformer’s data appetite — hierarchy on one side, distillation on the other — and the margins each reports. Swin is Liu and co-authors, ICCV 2021; DeiT is Touvron and co-authors, PMLR 139.

Steps

Design a visual Transformer around the smallest evidence

The decisive feature may be a tiny lesion, a whole-scene relation, or both.

Swin Transformer is the worked example of steps two through four. Its shifted-window scheme “brings greater efficiency by limiting self-attention computation to non-overlapping local windows while also allowing for cross-window connection”. That gives the architecture “linear computational complexity with respect to image size”. Its stagewise merging exposes the several scales that dense prediction heads consume. The reported numbers cover all three head types. ImageNet-1K top-1 accuracy is 87.3. COCO test-dev reaches 58.7 box AP and 51.1 mask AP. ADE20K val reaches 53.5 mIoU. That surpasses the previous state of the art “by a large margin of +2.7 box AP and +2.6 mask AP on COCO, and +3.2 mIoU on ADE20K”.

Step five is where the earlier numbers return. A stem choice worth 1-2 top-1 points. A pyramid worth 4.1 absolute AP on COCO. A merging schedule worth 2x throughput for 0.2-0.3 points. Each is small enough to be lost in an unmatched comparison. Each is large enough to decide the system.

FigureProcess · 5 steps
  1. 1. Quantify target scale

    Measure the smallest and largest structures that affect the decision.

  2. 2. Choose token resolution

    Preserve enough detail before merging or pooling.

  3. 3. Plan cross-window communication

    Use shifting, overlap, global tokens, or later global stages.

  4. 4. Expose required scales

    Connect appropriate stages to dense prediction or detection heads.

  5. 5. Test geometric shifts

    Evaluate crops, translations, scale changes, and altered aspect ratios.

Attention maps do not automatically explain visual decisions

A high attention weight is one routing coefficient inside a multilayer computation. Residual paths, value vectors, later blocks, and the task head all affect the final output.

Raw attention is the weakest of the attention-based explanation methods, and there is a benchmark that says so. Scored against the ImageNet-Segmentation ground truth, it reaches 67.84% pixel accuracy, 80.24 mAP and 46.37 mIoU. Attention rollout reaches 73.54 / 84.76 / 55.42. The relevance-propagation method proposed by Chefer and two co-authors in 2021 reaches 79.70 / 86.03 / 61.95. Twelve points of pixel accuracy separate the prettiest heatmap from the method that follows the value paths and skip connections it ignores.

The sharper fact is procedural. Two of the methods could not be entered in the target-class perturbation test at all: “Notice that because rollout and raw attention produce constant visualization given an input image, we omit their scores in the target-class test.” A map that comes out the same whichever class you query it about cannot be an explanation of any particular class.

Use counterfactual masking, feature interventions, localization metrics, and failure slices alongside attention visualization. A compelling heatmap is not sufficient evidence of causal reliance.

Visual interpretability requires interventions and task-linked validation, not attractive attention plots alone.

Key takeaways