SandHouse
Pages and contents

Positional Encoding

Positional Encoding in Transformers

Self-attention is naturally permutation invariant: without positional information, it treats tokens as an unordered set. Positional encoding gives the model information about token location, distance, and order. Positional information can be absolute, describing a token’s position, or relative, describing the displacement between two tokens.

Standard absolute positional encoding

The original Transformer adds a position-dependent vector to each token embedding: x~i=xi+piwhere xi is the token embedding and pi is the positional embedding for position i. The positional vectors may be fixed sinusoidal vectors or learned parameters. The limitation of this is that relative distances must be inferred by the model.

LePE: Locally Enhanced Positional Encoding

LePE adds positional information through a local operation, usually a depthwise convolution over the value features. A simplified form is:

Output=Attention⁡(Q,K,V)+DWConv⁡(V)

The convolution captures local spatial relationships, such as neighboring pixels in an image.

Key properties:

• Particularly useful in vision transformers.
• Encourages locality without restricting attention to local regions.
• The attention branch can still model long-range relationships.
• The convolutional branch injects position-dependent local structure.
• It works naturally with different image resolutions because it does not require a fixed positional embedding table.

LePE can be viewed as using attention for global interactions, but add a convolutional signal describing the local neighborhood.


RoPE: Rotary Positional Embedding

RoPE applies a position-dependent rotation to the query and key vectors:

qi′=Riqi,kj′=Rjkj

where Ri is a rotation matrix determined by position i. Attention then uses qi⊤Ri⊤Rjkjbecause
Ri⊤Rj=Rj−i.The attention score depends naturally on the relative displacement j−i.

Key properties:

• Applied to queries and keys rather than added to token embeddings.
• Encodes absolute position through each vector’s rotation.
• Makes query-key similarity depend on relative position.
• Commonly used in modern language models.
• Can extrapolate beyond the training context better than learned absolute embeddings, although performance may still degrade at much longer lengths.
• Different feature pairs rotate at different frequencies, allowing the model to represent positional relationships at several scales.

RoPE can be viewed as rotating each query and key according to its position, so their dot product reveals how far apart they are.