Two Dimensional Positional Encodings for Spatial Attention

71 concepts59 papers1 proposal

When Transformers were originally designed for natural language processing, they treated data as a one-dimensional sequence. A sentence flows linearly from left to right, and standard positional encodings—whether sinusoidal or learned—reflect this by assigning a single scalar index to each token.

However, when we apply Transformers to two-dimensional data like images, tables, or grids, this 1D assumption breaks down. Standard Vision Transformers (ViTs) bypass this by chopping an image into patches and flattening them into a linear sequence.

This flattening process introduces a fundamental flaw: it destroys the inherent geometric structure of the data. In a $W \times H$ grid of patches, a patch at coordinate $(x, y)$ is physically adjacent to the patch directly below it at $(x, y+1)$. Yet, in a flattened 1D sequence, these two patches are separated by an artificial distance of $W$ tokens. Standard 1D encodings treat them as distant elements, forcing the model to painfully relearn the basic rules of 2D geometry from scratch. As noted by Wenhao Li et al., this lack of 2D inductive bias severely limits a model's capacity for abstract spatial reasoning.

To fix this, researchers have developed Two-Dimensional Positional Encodings (2D PE). Instead of forcing 2D data into a 1D mold, these methods inject spatial geometry directly into the attention mechanism, allowing models to natively understand rows, columns, distances, and orientations.


Axial Decomposition and Absolute 2D Coordinates

The most straightforward way to preserve a grid structure is to assign each token two independent coordinates: a row index ($y$) and a column index ($x$).

Instead of learning a unique embedding vector for every single position in a fixed grid, the positional information is factorized into separate horizontal and vertical components. These components are then combined (typically via addition or concatenation) to form the final spatial embedding.

Standard 1D Flattening:
[ Patch 1 ] -> [ Patch 2 ] -> [ Patch 3 ] -> ... -> [ Patch N ]
(Loses vertical adjacency)

2D Axial Decomposition:
(Row 1, Col 1)  (Row 1, Col 2)  (Row 1, Col 3)
(Row 2, Col 1)  (Row 2, Col 2)  (Row 2, Col 3)

Mostafa Dehghani et al. demonstrate that factorizing coordinates this way allows models to generalize to arbitrary aspect ratios and resolutions. Because the horizontal and vertical dimensions are treated independently, the model can dynamically scale the coordinate space rather than being locked into a rigid, pre-trained 1D sequence length.

This row-and-column awareness is highly effective across different structured data modalities:

  • Tables: In table-to-text generation, Ewa Andrejczuk et al. and Miao Chen et al. utilize learnable row and column indices to ensure that the relative alignment of cells is preserved even after a table is linearized for processing.
  • High-Resolution Images: When processing high-resolution documents or screenshots, Jiabo Ye et al. use 2D position embeddings to help language models reconstruct the global layout of fragmented image patches. To make this sequence parsing easier, Xiaoyi Dong et al. introduce explicit "newline" tokens at the end of each row of patches, acting as structural cues for the autoregressive decoder.
  • Irregular Grids: For architectures that do not use uniform grids—such as the patch mosaics proposed by Tomer Ronen et al.—embeddings can be derived directly from the continuous 2D coordinates of each patch center. This ensures spatial context is preserved even when tokens represent varying scales and non-contiguous locations.

Relative 2D Encodings and Translation Equivariance

Absolute coordinates tell a model where a feature is on the canvas, but computer vision tasks often care more about how far apart two features are relative to each other. If an object shifts from the top-left corner of an image to the bottom-right, its internal geometric structure remains identical. Traditional Convolutional Neural Networks (CNNs) handle this naturally through translation equivariance, but standard Transformers do not.

To bridge this gap, Irwan Bello et al. introduced 2D relative positional embeddings. Instead of adding a static coordinate vector to the input tokens, this approach injects a bias directly into the attention matrix based on the relative horizontal distance ($\Delta x$) and vertical distance ($\Delta y$) between the query token and the key token.

$$\text{Attention}(Q, K) = \text{Softmax}\left(\frac{QK^T}{\sqrt{d_k}} + R_x + R_y\right)$$

Where $R_x$ and $R_y$ are learnable look-up tables corresponding to the relative spatial offsets between tokens.

This mechanism allows the attention process to account for the exact spatial distance between pixels, mimicking the localized spatial awareness of convolutions while maintaining the global receptive field of self-attention. Aravind Srinivas et al. demonstrate that integrating these relative encodings provides the critical spatial inductive biases required for precise localization tasks like instance segmentation and object detection.

Furthermore, Huisi Wu et al. and Haoyuan Chen et al. show that mapping these spatial distances into a finite set of learnable values helps a model preserve local and multi-scale structures. This makes the architecture highly data-efficient, allowing it to excel even when trained on small or highly specialized datasets, such as medical histopathology images.


2D Rotary Embeddings and Scale Generalization

In modern language models, Rotary Position Embeddings (RoPE) are widely favored because they encode relative distance by rotating query and key vectors in a complex plane. To bring this mathematical elegance to vision tasks, researchers extended RoPE to two dimensions.

In a 2D RoPE framework, the hidden channels of a token's query or key vector are split into two halves. The first half is rotated using the horizontal coordinate $x$, and the second half is rotated using the vertical coordinate $y$. When the query and key vectors are multiplied during the attention step, the trigonometric identities naturally cause the result to depend purely on the relative distances $\Delta x$ and $\Delta y$.

Token Hidden Dimensions: [  d / 2 channels  |  d / 2 channels  ]
                                   |                  |
                           Rotate by X-coord  Rotate by Y-coord

Xiangxiang Chu et al. implement this 2D rotary mechanism in VisionLLaMA, pairing it with an auto-scaling interpolation strategy. This allows the model to seamlessly generalize to high-resolution inputs at inference time, even if it was only trained on lower-resolution images.

However, rigidly splitting rotations along the Cartesian axes can occasionally introduce axis-aligned artifacts. To provide more isotropic spatial awareness, Byeongho Heo et al. proposed a "RoPE-Mixed" approach that introduces learnable frequencies, allowing the model to adapt dynamically to complex, diagonal, and multi-scale spatial relationships.

This high-fidelity spatial preservation is particularly vital for generative and editing tasks:

  • Image Synthesis: Jinbin Bai et al. demonstrate that 2D rotary embeddings provide the structural inductive bias necessary to maintain global coherence across thousands of image tokens in high-resolution text-to-image generation.
  • Autoregressive Editing: Qi Cai applies 2D rotary embeddings with specific spatial offsets to cleanly differentiate between source reference tokens and target generation tokens within a shared transformer architecture, ensuring that the spatial layout of the original image is perfectly preserved in the edited output.
  • Context Scaling: When scaling up to massive token counts, Shi Liu et al. show that mapping high-resolution image patches back to the position IDs of their lower-resolution counterparts prevents the mathematical decay of token relationships, keeping the global 2D layout accessible across long contexts.

Key Foundational Work

Attention Augmented Convolutional Networks (2019) — contributed 2 concept elements to this direction.
UTNet: A Hybrid Transformer Architecture for Medical Image Segmentation (2021) — contributed 1 concept elements to this direction.
TokenPose: Learning Keypoint Tokens for Human Pose Estimation (2021) — contributed 1 concept elements to this direction.
History & citationVersion 1 · 2026-10-04

Current · Permanent link

View frozen version 1

Cite this direction

Latest version (a living page):

@misc{lacuna_2d_relative_position_encoding_6f77a8d3,
  title = {2D relative position encoding},
  author = {{Lacuna}},
  howpublished = {Lacuna research direction},
  year = {2026},
  url = {https://lacuna.tiptreesystems.com/direction/2d-relative-position-encoding/rdr_6f77a8d344e943969f42824b039bdc6b},
  note = {Latest version of a living research direction; cite a version for a fixed text. Accessed 2026-11-26},
}

This exact version (version 1, frozen text):

@misc{lacuna_2d_relative_position_encoding_6f77a8d3_v1,
  title = {2D relative position encoding},
  author = {{Lacuna}},
  howpublished = {Lacuna research direction},
  year = {2026},
  url = {https://lacuna.tiptreesystems.com/direction/2d-relative-position-encoding/rdr_6f77a8d344e943969f42824b039bdc6b/v/1},
  note = {Version 1, frozen 2026-10-04. Accessed 2026-11-26},
}
About

These directions overlap with this one through shared papers.

See something wrong? Report a mistake