{"notes":[{"id":"vision-transformers/pvt","category":"vision-transformers","legacyPath":"vision-transformers/2102-pvt","legacySlug":"2102-pvt","legacyPaths":[],"title":"PVT","subtitle":"Spatial Reduction Attention Mechanism","author":"Z. Yuan","paperDate":"2021-02-24","publishedOn":"2024-07-03","paperTitle":"Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions","paperUrl":"https://arxiv.org/abs/2102.12122","bibliography":{"title":"Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions","authors":["Wenhai Wang","Enze Xie","Xiang Li","Deng-Ping Fan","Kaitao Song","Ding Liang","Tong Lu","Ping Luo","Ling Shao"],"url":"https://arxiv.org/abs/2102.12122","pdfUrl":"https://arxiv.org/pdf/2102.12122","codeUrl":null,"preprint":{"id":"2102.12122","submittedOn":"2021-02-24","url":"https://arxiv.org/abs/2102.12122"},"publication":{"venue":"ICCV","year":2021,"kind":"conference","url":"https://arxiv.org/abs/2102.12122"},"citation":"@misc{visiontransformerspvt2021,\n  title = {{Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions}},\n  author = {Wenhai Wang and Enze Xie and Xiang Li and Deng-Ping Fan and Kaitao Song and Ding Liang and Tong Lu and Ping Luo and Ling Shao},\n  year = {2021},\n  eprint = {2102.12122},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2102.12122}\n}\n","citationPath":"/content/papers/citations/vision-transformers/pvt.c8c991637878.bib"},"thumbnail":{"src":"/content/papers/assets/0784052802290bf5595ec58a783a2cd29da20872dafa1be2fdf9d3ebd6813fbb.jpg","width":1368,"height":676},"locale":"en","path":"/content/papers/en/vision-transformers/pvt.f8ce86e06615.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"hierarchical-structure","text":"Hierarchical Structure","depth":3},{"id":"spatial-reduction-attention-sra","text":"Spatial Reduction Attention (SRA)","depth":3},{"id":"model-configuration","text":"Model Configuration","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"imagenet-performance","text":"ImageNet Performance","depth":3},{"id":"object-detection-performance","text":"Object Detection Performance","depth":3},{"id":"contribution-of-the-pyramid-structure","text":"Contribution of the Pyramid Structure","depth":3},{"id":"depth-vs-width-trade-off","text":"Depth vs. Width Trade-off","depth":3},{"id":"addressing-but-not-solving-the-core-issue","text":"Addressing but Not Solving the Core Issue","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"vision-transformers/swin-transformer","relation":"comparison","topic":"Multiscale visual Transformers"},{"id":"vision-transformers/vit","relation":"comparison","topic":"Multiscale visual Transformers"}]},{"id":"vision-transformers/swin-transformer","category":"vision-transformers","legacyPath":"vision-transformers/2103-swin-transformer","legacySlug":"2103-swin-transformer","legacyPaths":[],"title":"Swin Transformer","subtitle":"The Dance Begins","author":"Z. Yuan","paperDate":"2021-03-25","publishedOn":"2024-08-04","paperTitle":"Swin Transformer: Hierarchical Vision Transformer using Shifted Windows","paperUrl":"https://arxiv.org/abs/2103.14030","bibliography":{"title":"Swin Transformer: Hierarchical Vision Transformer using Shifted Windows","authors":["Ze Liu","Yutong Lin","Yue Cao","Han Hu","Yixuan Wei","Zheng Zhang","Stephen Lin","Baining Guo"],"url":"https://arxiv.org/abs/2103.14030","pdfUrl":"https://arxiv.org/pdf/2103.14030","codeUrl":null,"preprint":{"id":"2103.14030","submittedOn":"2021-03-25","url":"https://arxiv.org/abs/2103.14030"},"publication":{"venue":"ICCV","year":2021,"kind":"conference","url":"https://openaccess.thecvf.com/content/ICCV2021/html/Liu_Swin_Transformer_Hierarchical_Vision_Transformer_Using_Shifted_Windows_ICCV_2021_paper.html"},"citation":"@misc{visiontransformersswintransformer2021,\n  title = {{Swin Transformer: Hierarchical Vision Transformer using Shifted Windows}},\n  author = {Ze Liu and Yutong Lin and Yue Cao and Han Hu and Yixuan Wei and Zheng Zhang and Stephen Lin and Baining Guo},\n  year = {2021},\n  eprint = {2103.14030},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2103.14030}\n}\n","citationPath":"/content/papers/citations/vision-transformers/swin-transformer.f6a161083008.bib"},"thumbnail":{"src":"/content/papers/assets/8b4ce387b40cac8be3a6a99545bbe6a5e87126f19c80c24a7de318e32d5f626b.jpg","width":1596,"height":468},"locale":"en","path":"/content/papers/en/vision-transformers/swin-transformer.89422680b5fc.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"multi-scale-detection-capability","text":"Multi-scale Detection Capability","depth":3},{"id":"quadratic-complexity","text":"Quadratic Complexity","depth":3},{"id":"solutions","text":"Solutions","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"sliding-windows","text":"Sliding Windows","depth":3},{"id":"new-challenges","text":"New Challenges","depth":3},{"id":"cyclic-shift","text":"Cyclic Shift","depth":3},{"id":"special-masking","text":"Special Masking","depth":3},{"id":"reverse-shift","text":"Reverse Shift","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"performance-on-imagenet-1k","text":"Performance on ImageNet-1K","depth":3},{"id":"object-detection-settings","text":"Object Detection Settings","depth":3},{"id":"swin-vs-resnext","text":"Swin vs ResNe(X)t","depth":3},{"id":"swin-vs-deit","text":"Swin vs DeiT","depth":3},{"id":"swin-vs-sota","text":"Swin vs SOTA","depth":3},{"id":"ablation-studies","text":"Ablation Studies","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"vision-transformers/pvt","relation":"comparison","topic":"Multiscale visual Transformers"},{"id":"vision-transformers/vit","relation":"comparison","topic":"Multiscale visual Transformers"}]},{"id":"vision-transformers/vit","category":"vision-transformers","legacyPath":"vision-transformers/2010-vit","legacySlug":"2010-vit","legacyPaths":[],"title":"ViT","subtitle":"Pioneering a New World","author":"Z. Yuan","paperDate":"2020-10-22","publishedOn":"2024-07-01","paperTitle":"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale","paperUrl":"https://arxiv.org/abs/2010.11929","bibliography":{"title":"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale","authors":["Alexey Dosovitskiy","Lucas Beyer","Alexander Kolesnikov","Dirk Weissenborn","Xiaohua Zhai","Thomas Unterthiner","Mostafa Dehghani","Matthias Minderer","Georg Heigold","Sylvain Gelly","Jakob Uszkoreit","Neil Houlsby"],"url":"https://arxiv.org/abs/2010.11929","pdfUrl":"https://arxiv.org/pdf/2010.11929","codeUrl":null,"preprint":{"id":"2010.11929","submittedOn":"2020-10-22","url":"https://arxiv.org/abs/2010.11929"},"publication":{"venue":"ICLR","year":2021,"kind":"conference","url":"https://openreview.net/pdf?id=YicbFdNTTy"},"citation":"@misc{visiontransformersvit2020,\n  title = {{An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale}},\n  author = {Alexey Dosovitskiy and Lucas Beyer and Alexander Kolesnikov and Dirk Weissenborn and Xiaohua Zhai and Thomas Unterthiner and Mostafa Dehghani and Matthias Minderer and Georg Heigold and Sylvain Gelly and Jakob Uszkoreit and Neil Houlsby},\n  year = {2020},\n  eprint = {2010.11929},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2010.11929}\n}\n","citationPath":"/content/papers/citations/vision-transformers/vit.8a478b78ec38.bib"},"thumbnail":{"src":"/content/papers/assets/82fb5d2f7ce623daf8d9ce146f096d22f2fb17d2532c5c4d613206f0424904aa.jpg","width":1472,"height":772},"locale":"en","path":"/content/papers/en/vision-transformers/vit.ae37d64b0944.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solution","text":"Solution","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"patchify","text":"Patchify","depth":3},{"id":"and-then","text":"And Then?","depth":3},{"id":"lack-of-inductive-bias","text":"Lack of Inductive Bias","depth":3},{"id":"training-data-must-be-large","text":"Training Data Must Be Large","depth":3},{"id":"can-be-even-larger","text":"Can Be Even Larger","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"what-does-vit-see","text":"What Does ViT See?","depth":3},{"id":"predict-with-cls-or-gap","text":"Predict with [CLS] or GAP?","depth":3},{"id":"self-supervised-training","text":"Self-Supervised Training","depth":3},{"id":"other-considerations","text":"Other Considerations","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"vision-transformers/deit","relation":"next","topic":"Learning visual representations with Transformers"},{"id":"vision-transformers/pvt","relation":"comparison","topic":"Multiscale visual Transformers"},{"id":"vision-transformers/swin-transformer","relation":"comparison","topic":"Multiscale visual Transformers"}]}],"text":"ViT has achieved remarkable results in image classification.\n\nIt officially marked the Transformer architecture's advance into computer vision.\n\n## Defining the Problem\n\nViT linearly projects flattened 16×16-pixel patches, equivalently implemented by Conv2d with kernel and stride 16. A 224×224 image becomes a 14×14 token grid, not a 14×14-pixel image. This coarse output grid makes direct dense localization harder.\n\n- **A coarse output grid limits spatial localization; information within each patch depends on its feature representation.**\n\nObviously, we need more refined features for dense prediction tasks. So, what if we change the 16 x 16 convolution to a 2 x 2 convolution?\n\n- **Of course not!**\n\nLet's take a 224 x 224 image as an example:\n\n- Using a 16 x 16 patch size, we get 14 x 14, totaling 196 input tokens.\n- Using a 2 x 2 patch size, we get 112 x 112, totaling 12,544 input tokens.\n\n**Imagine calculating a 12,544 x 12,544 self-attention matrix...**\n\nClearly, no one would consider this a good idea.\n\n## Solving the Problem\n\n### Model Architecture\n\n![model architecture](/content/papers/assets/0784052802290bf5595ec58a783a2cd29da20872dafa1be2fdf9d3ebd6813fbb.jpg)\n\nThe above image shows the design of the PVT architecture. While it may look complex, it essentially follows the same principles as convolutional neural network (CNN) architectures.\n\n### Hierarchical Structure\n\nPVT has four stages with output strides 4, 8, 16 and 32. The first uses 4×4 patches; subsequent stage transitions halve each spatial dimension.\n\nEach transition groups non-overlapping patches and linearly projects them, equivalently implemented by Conv2d with matching kernel and stride. “Pure Transformer” describes the attention-based backbone, not a ban on Conv2d as an implementation primitive. A 3×224×224 input projected with kernel/stride 4 to 64 channels gives 64×56×56 features.\n\nSo, in the first stage, the input to the Transformer encoder is:\n\n- **Sequence Length**: 3136 (all image patches, i.e., 56 x 56)\n- **Feature Number**: 64 (features per patch, i.e., the number of channels)\n\n### Spatial Reduction Attention (SRA)\n\n![spatial reduction attention](/content/papers/assets/c223e5a72263d2009c8a19bff7b7580deef8977ce533fef6ea34342d9819695e.jpg)\n\nAfter obtaining the feature maps, we realize that a (56 x 56) x (56 x 56) self-attention matrix is still enormous and needs serious handling.\n\nThe authors propose \"Spatial Reduction Attention\" (SRA): keep the query (Q) token count, reduce the key (K) and value (V) token counts spatially, then project them back to the stage's channel dimension. For example, an attention map of (56 x 56) x (56 x 56) becomes 3136 x 49 if K and V are reduced to (7 x 7).\n\nThe attention matrix then has 1/64 as many elements. This lowers attention computation and memory use, although whole-model cost does not fall by the same factor.\n\nAs usual, let's look at the implementation. The highlighted code uses `sr_ratio=[8,4,2,1]` across the four stages; the last stage does not reduce K/V. In the example above, the first stage goes from 56 x 56 to 7 x 7. K/V token count falls by about $R^2$, while Q and output token counts stay unchanged. It requires `dim % num_heads == 0`; the reduction branch also requires `N == H * W`.\n\n```python {31-34,40-44}\n# Reference:\n#   - https://github.com/whai362/PVT/blob/v2/classification/pvt.py\n\nimport torch\nimport torch.nn as nn\n\nclass SpatialReductionAttention(nn.Module):\n\n    def __init__(\n        self,\n        dim,\n        num_heads=8,\n        qkv_bias=False,\n        qk_scale=None,\n        attn_drop=0.,\n        proj_drop=0.,\n        sr_ratio=1\n    ):\n        super().__init__()\n        self.dim = dim\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = qk_scale or head_dim ** -0.5\n\n        self.q = nn.Linear(dim, dim, bias=qkv_bias)\n        self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)\n        self.attn_drop = nn.Dropout(attn_drop)\n        self.proj = nn.Linear(dim, dim)\n        self.proj_drop = nn.Dropout(proj_drop)\n\n        self.sr_ratio = sr_ratio\n        if sr_ratio > 1:\n            self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)\n            self.norm = nn.LayerNorm(dim)\n\n    def forward(self, x, H, W):\n        B, N, C = x.shape\n        q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)\n\n        if self.sr_ratio > 1:\n            x_ = x.permute(0, 2, 1).reshape(B, C, H, W)\n            x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)\n            x_ = self.norm(x_)\n            kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        else:\n            kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        k, v = kv[0], kv[1]\n\n        attn = (q @ k.transpose(-2, -1)) * self.scale\n        attn = attn.softmax(dim=-1)\n        attn = self.attn_drop(attn)\n\n        x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n        x = self.proj(x)\n        x = self.proj_drop(x)\n\n        return x\n```\n\n### Model Configuration\n\nFinally, let's look at the PVT model configuration.\n\n1. $P_i$: Patch size at stage $i$\n2. $C_i$: Number of output channels at stage $i$\n3. $L_i$: Number of encoder layers at stage $i$\n4. $R_i$: Reduction ratio of SRA at stage $i$\n5. $N_i$: Number of heads in SRA at stage $i$\n6. $E_i$: Expansion ratio in the feed-forward layer at stage $i$\n\nThe model design follows the design rules of ResNet:\n\n1. Use smaller output channels in the shallow stages.\n2. Concentrate most computational resources in the middle stages.\n\nFor discussion purposes, the table below shows a series of PVT models of different scales: PVT-Tiny, PVT-Small, PVT-Medium, and PVT-Large. Their parameter counts are comparable to ResNet18, ResNet50, ResNet101, and ResNet152, respectively.\n\n![model configuration](/content/papers/assets/21e302d123e03414376e1f41045b370f947cc69561bdd2b40f30aca3fe99d0f5.jpg)\n\n## Discussion\n\n### ImageNet Performance\n\n![imagenet performance](/content/papers/assets/1ea571ee05865772e38c9e2c45d269ca4eff3943e45d2f5493e73c18ab0bdc65.jpg)\n\nThe authors compare PVT with two of the most representative CNN backbones, ResNet and ResNeXt, which are widely used in many downstream task benchmarks.\n\nIn the table above, PVT models outperform traditional CNN backbones with similar parameter counts and computational budgets.\n\nFor instance, with a similar GFLOP, PVT-Small achieves a top-1 error rate of $20.2\\%$, outperforming ResNet50's $21.5\\%$ by $1.3$ percentage points ($20.2\\%$ vs. $21.5\\%$).\n\nWith similar or lower complexity, PVT models achieve comparable performance to recently proposed Transformer-based models like ViT and DeiT.\n\nPVT-Large has 18.3% top-1 error. Table 2 lists ViT/DeiT-Base/16 at 18.2%, although the paper’s prose says 18.3%. The table supports comparable performance, not exact equality.\n\n### Object Detection Performance\n\n![dense prediction performance-retinanet](/content/papers/assets/7edf448ea40ff1ab951f81717dd25d8bbfe171b94439ee27c7b3554e16650239.jpg)\n\n![dense prediction performance-maskrcnn](/content/papers/assets/500f38dcfc2a08becc4129abc5d5e8b5a92bb931aacb77b0596427d31033561a.jpg)\n\nSince this architecture targets dense prediction tasks from the outset, let's focus on PVT's performance in dense prediction tasks.\n\n1. **Datasets**:\n\n   - Using the COCO benchmark\n   - Training set: COCO train2017 (118k images)\n   - Validation set: COCO val2017 (5k images)\n\n2. **Models and Initialization**:\n\n   - Standard detectors: RetinaNet and Mask R-CNN\n   - Backbone initialized with ImageNet pretrained weights\n   - New layers initialized with Xavier initialization\n\n3. **Training Settings**:\n   - Batch size: 16\n   - Hardware: 8 V100 GPUs\n   - Optimizer: AdamW\n   - Initial learning rate: $1 \\times 10^{-4}$\n\nWith comparable parameter counts, PVT models significantly outperform traditional models. With RetinaNet, PVT-Tiny's AP is 4.9 points higher than ResNet18 (36.7 vs. 31.8).\n\nWith Mask R-CNN, PVT-Tiny's mask AP (APm) is 35.1, 3.9 points higher than ResNet18 (35.1 vs. 31.2), and even 0.7 points higher than ResNet50 (35.1 vs. 34.4).\n\nThese results suggest that PVT can serve as a good alternative to CNN backbones for object detection and instance segmentation tasks.\n\nThe image below shows PVT's results on the COCO validation set.\n\n![coco validation results](/content/papers/assets/88b27d29bee0d1c1ecfd77cf50f3a96db03fbc3434d0001aeb063405e164de60.jpg)\n\n### Contribution of the Pyramid Structure\n\nThe authors conducted several ablation studies to verify the impact of different parts of PVT on performance.\n\nFirst, the contribution analysis of the pyramid structure is shown in the table below:\n\n![pyramid structure contribution](/content/papers/assets/74187fc48b77ff4713d6e2a73d152ee6ffbc188ec17496163b625d2324504424.jpg)\n\nWith RetinaNet and the COCO 1× schedule, PVT-Small reaches 40.4 AP versus 31.7 for ViT-Small/32, an 8.7-AP difference. ViT-Small/32 draws and interpolates features from several layers to adapt to RetinaNet; ViT-Small/4 ran out of memory on a 32 GB GPU. These are whole-backbone configurations with different patch sizes, SRA and feature scales, so the entire difference cannot be isolated to the pyramid alone.\n\nThis indicates that the pyramid structure design helps improve performance in dense prediction tasks.\n\n### Depth vs. Width Trade-off\n\n![depth vs width](/content/papers/assets/281f21e2ce49a8c433cc4662859afe06addbe34a03e8ab9b2d46bb2e72eaa123.jpg)\n\nThe authors further explore whether PVT should be deeper or wider, as well as the impact of feature map sizes at different stages on performance.\n\nThe authors multiplied PVT-Small's hidden dimensions by 1.4 to build a wider version, then compared it with a deeper model of similar parameter count. In this ablation, the deeper model has 44.2M parameters and 41.9 AP, versus 46.8M and 40.8 AP for the wider model. Here, depth performs better under comparable parameter counts.\n\n### Addressing but Not Solving the Core Issue\n\n![limitations](/content/papers/assets/37b5b5be3ab11177640820d02530ce0ec37fd049dc1370046cf5e4efa92b4fdf.jpg)\n\nLastly, the authors discussed performance limitations.\n\nAs the input size increases, the GFLOPs of PVT grow faster than ResNet but slower than ViT. When the input size does not exceed 640×640 pixels, PVT-Small and ResNet50 have similar GFLOPs.\n\nAdditionally, with the input's shorter side at 800 pixels, RetinaNet with PVT-Small takes 76.9 ms per image on a V100, versus 55.9 ms with ResNet50. Reducing PVT-Small's shorter side to 640 pixels gives 51.7 ms and 38.7 AP, but now the input scales differ.\n\nThis identifies a large-image cost for the tested PVT implementation and hardware.\n\n\n> [!TIP]\n> \n> For fixed spatial reduction $R$, SRA forms an approximately $N\\times(N/R^2)$ attention matrix. Pairwise attention therefore remains $O(N^2/R^2)$ in token count, with a lower constant cost rather than linear scaling.\n\n\n## Conclusion\n\nAlthough in 2021, comparing against ResNet and ResNeXt might seem conservative, this study introduces the pyramid structure into Transformers to provide a pure Transformer backbone for dense prediction tasks, rather than focusing on task-specific heads or image classification models, offering an important direction for future research.\n\nAt this point, Transformer-based models in computer vision are still in their early stages, and many potential technologies and applications remain to be explored.\n","imageSizes":{"/content/papers/assets/0784052802290bf5595ec58a783a2cd29da20872dafa1be2fdf9d3ebd6813fbb.jpg":{"width":1368,"height":676},"/content/papers/assets/c223e5a72263d2009c8a19bff7b7580deef8977ce533fef6ea34342d9819695e.jpg":{"width":882,"height":432},"/content/papers/assets/21e302d123e03414376e1f41045b370f947cc69561bdd2b40f30aca3fe99d0f5.jpg":{"width":1626,"height":728},"/content/papers/assets/1ea571ee05865772e38c9e2c45d269ca4eff3943e45d2f5493e73c18ab0bdc65.jpg":{"width":1098,"height":1196},"/content/papers/assets/7edf448ea40ff1ab951f81717dd25d8bbfe171b94439ee27c7b3554e16650239.jpg":{"width":1428,"height":516},"/content/papers/assets/500f38dcfc2a08becc4129abc5d5e8b5a92bb931aacb77b0596427d31033561a.jpg":{"width":1416,"height":476},"/content/papers/assets/88b27d29bee0d1c1ecfd77cf50f3a96db03fbc3434d0001aeb063405e164de60.jpg":{"width":1024,"height":784},"/content/papers/assets/74187fc48b77ff4713d6e2a73d152ee6ffbc188ec17496163b625d2324504424.jpg":{"width":1080,"height":260},"/content/papers/assets/281f21e2ce49a8c433cc4662859afe06addbe34a03e8ab9b2d46bb2e72eaa123.jpg":{"width":994,"height":196},"/content/papers/assets/37b5b5be3ab11177640820d02530ce0ec37fd049dc1370046cf5e4efa92b4fdf.jpg":{"width":1218,"height":840}}}
