NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Rethinking and Improving Relative Position Encoding for Vision Transformer

Kan Wu, Houwen Peng, Minghao Chen, Jianlong Fu, Hongyang Chao

Abstract

Relative position encoding (RPE) is important for transformer to capture sequence ordering of input tokens. General efficacy has been proven in natural language processing. However, in computer vision, its efficacy is not well studied and even remains controversial, e.g., whether relative position encoding can work equally well as absolute position? In order to clarify this, we first review existing relative position encoding methods and analyze their pros and cons when applied in vision transformers. We then propose new relative position encoding methods dedicated to 2D images, called image RPE (iRPE). Our methods consider directional relative distance modeling as well as the interactions between queries and relative position embeddings in self-attention mechanism. The proposed iRPE methods are simple and lightweight. They can be easily plugged into transformer blocks. Experiments demonstrate that solely due to the proposed encoding methods, DeiT [21] and DETR [1] obtain up to 1.5% (top-1 Acc) and 1.3% (mAP) stable improvements over their original versions on ImageNet and COCO respectively, without tuning any extra hyperparameters such as learning rate and weight decay. Our ablation and analysis also yield interesting findings, some of which run counter to previous understanding.

Introduction

Standard Transformers are "permutation invariant," meaning they treat a sequence of image patches like an unordered bag of tokens, losing critical spatial information. To address this, researchers typically add Absolute Position Encoding (APE), assigning unique coordinates to every spot on the grid. However, in Natural Language Processing, Relative Position Encoding (RPE)—which focuses on the distance between tokens rather than fixed coordinates—has often proven more effective.

In computer vision, the efficacy of RPE has been controversial; some studies suggested it offered no gain over absolute encoding, while others found it helpful. This paper introduces image Relative Position Encoding (iRPE), a set of lightweight methods designed to clarify this debate and help Vision Transformers (ViTs) better understand the spatial structure of 2D images.

Methods: Image Relative Position Encoding (iRPE)

The authors propose iRPE, which introduces several novel components to adapt RPE for visual tasks:

  1. Bias vs. Contextual Modes: They explore "Bias" mode (a simple spatial weight added to the attention score) and "Contextual" mode, where the spatial encoding interacts directly with the image features (queries).
  2. 2D Spatial Mapping: Since images are 2D, they propose four ways to map relative positions: undirected methods based on Euclidean distance and directed methods (Cross & Product) that account for horizontal and vertical offsets separately or combined, capturing the "flow" of the image.
Figure 1: Illustration of (a) bias mode and (b) contextual mode for relative position encoding in self-attention.
  1. Piecewise Index Function: Instead of a simple "clip" (ignoring everything beyond a certain distance), they use a function that gives high resolution to nearby neighbors and lower resolution to distant ones, preserving long-range dependencies more efficiently.
  2. Efficiency Optimization: They provide an optimized implementation that reduces the computational complexity of contextual RPE from $O(n^2d)$ to $O(nkd)$, making it practical for high-resolution tasks.

Key Insights and Results

The researchers evaluated iRPE on ImageNet-1K (classification), COCO 2017 (detection), and fine-grained visual categorization benchmarks.

Performance and Directionality

  • ImageNet: Adding iRPE to the DeiT-S model improved Top-1 accuracy by 1.5% without tuning any extra hyperparameters.
  • Object Detection: Integrating iRPE into the DETR-ResNet50 model yielded a 1.3% mAP improvement on the COCO dataset.
  • Directionality is Crucial: The "Product" and "Cross" methods (which are directional) consistently outperformed undirected Euclidean distance. This suggests that for vision, knowing if a patch is "above" or "to the right" is more important than just knowing its distance.

Efficiency and Scalability

Their optimized implementation adds less than 1% extra computational cost (MACs) to the baseline models. As shown in the figure below, the efficient version maintains a near-constant, minimal overhead regardless of input resolution, making it a highly scalable upgrade for most architectures.

Figure 6: Comparison of extra MACC ratio between inefficient and efficient implementations across different resolutions.

RPE as a "Localizer"

Visualization shows that RPE forces the shallow (early) layers of a Transformer to focus on local neighborhoods, effectively injecting a "convolution-like" inductive bias. Interestingly, while RPE can completely replace absolute encoding for classification, APE is still necessary for object detection (like in DETR) because the model needs a global coordinate system to predict bounding box locations.

Conclusion

iRPE provides a stable performance boost and clarifies the role of spatial encoding in ViTs. By accounting for directional distances and feature interactions, it bridges the gap between the local-focus of Convolutions and the global-focus of Transformers. Future work will involve extending these 2D spatial priors to 3D data such as video or point clouds.

Summary updated

BibTeX
@inproceedings{wu2021rethinking,
  author = {Kan Wu and Houwen Peng and Minghao Chen and Jianlong Fu and Hongyang Chao},
  title = {{Rethinking and Improving Relative Position Encoding for Vision Transformer}},
  booktitle = {IEEE/CVF International Conference on Computer Vision},
  year = {2021},
  url = {https://openreview.net/forum?id=7UqrsFh_zNU},
}
Figure