Self-attention on its own ignores word order, so Transformers need some way to tell it where each token is. The classic solution adds an absolute positional encoding $PE(pos)$ to each input vector: token 5 gets “position 5”, token 6 gets “position 6”, and so on.
But think about how language works. An adjective usually comes one position before its noun; a verb's subject is often a few positions to the left. These rules are about the distance between words, and they hold wherever the words appear in the sentence. Relative positional encoding builds this directly into attention. This reading covers the original relative position embeddings and RoPE (rotary position embedding), the method used by most modern large language models.
1Absolute vs. relative position
An absolute position is a token's index in the sequence: 0, 1, 2, …. A relative position describes one token as seen from another: “4 positions before me” is $-4$, “3 positions after me” is $+3$.
The difference shows up when we move the reference token. From position 5, the token at position 1 is at relative position $-4$; from position 6, the same token is at $-5$. Its absolute position (1) does not depend on who is looking; its relative position does.
Why relative positions?
- Language patterns are about distance. “The word right before me”, “the verb two words back”: these describe relations between tokens, and they are the same at position 3 and at position 300.
- Generalization to longer sequences. A model trained on sentences of length 100 has never seen absolute position 500, but it has seen every relative distance it will need (especially with the clipping described below).
2The relative position matrix
For a query at position $i$ and a key at position $j$, define the relative position
$$r_{i,j} = j - i.$$Arranging these in a matrix gives 0 on the diagonal, positive numbers to the right (keys after the query) and negative numbers to the left (keys before the query). Every diagonal line has a constant value.
Clipping
Do we need a separate notion of distance $+37$ and $+38$? Probably not: beyond some distance, the exact number matters little. So relative positions are clipped to a maximum distance $k$:
$$r_{i,j} = \text{clip}(j-i,\,-k,\,k) = \max\big(-k,\ \min(k,\ j-i)\big).$$There are now only $2k+1$ possible values, $-k,\dots,0,\dots,+k$, no matter how long the sequence is. Each value gets its own learned embedding vector, looked up like a word embedding.
3Self-attention with relative position embeddings
Shaw, Uszkoreit & Vaswani (2018) put the relative position embeddings directly into the attention score. Let $a_{r}$ be the learned vector (dimension $d_k$) for relative position $r$. The score between query $i$ and key $j$ becomes
$$e_{i,j} = \frac{q_i\cdot\big(k_j + a_{r_{i,j}}\big)}{\sqrt{d_k}},\qquad \hat\alpha_{i,j}=\text{softmax}_j(e_{i,j}),$$where $q_i=W^Qx_i$ and $k_j=W^Kx_j$ as usual. In words: when query $i$ looks at key $j$, the key is shifted by a vector that says “I am $r_{i,j}$ positions away from you”.
- No absolute positional encoding is added to the inputs. All position information now lives inside the attention scores.
- The paper also adds a relative embedding on the value side, $z_i=\sum_j\hat\alpha_{i,j}\,(v_j+a^V_{r_{i,j}})$; the key-side term above is the essential one.
- The same $2k+1$ embeddings are shared across all positions (and typically across heads), so the number of extra parameters is small.
The same pair gets the same score anywhere
Consider the phrase the cat appearing at the start of a sequence, or 15 tokens later. With an absolute encoding, the inputs become $x_{\text{cat}}+PE(s+1)$ and $x_{\text{the}}+PE(s)$, and the word–position cross terms change with the starting point $s$. With relative embeddings, the score only involves $q_{\text{cat}}$, $k_{\text{the}}$, and $a_{-1}$, so it is identical everywhere.
Results on machine translation
| Model | Position information | EN–DE BLEU | EN–FR BLEU |
|---|---|---|---|
| Transformer (base) | absolute | 26.5 | 38.2 |
| Transformer (base) | relative | 26.8 | 38.7 |
| Transformer (big) | absolute | 27.9 | 41.2 |
| Transformer (big) | relative | 29.2 | 41.5 |
Numbers from Shaw et al. (2018), Table 1. BLEU measures overlap with human translations; higher is better.
4RoPE: rotary position embedding
RoPE (Su et al., RoFormer) achieves relative positioning with no extra parameters and an elegant geometric trick: rotate the query and key vectors by an angle proportional to their positions.
The 2-dimensional case
Suppose queries and keys are 2-dimensional. Let $R(\phi)$ be the matrix that rotates a 2-D vector by angle $\phi$:
$$R(\phi)=\begin{bmatrix}\cos\phi & -\sin\phi\\ \sin\phi & \cos\phi\end{bmatrix}.$$For a query at position $m$ and a key at position $n$, RoPE uses
$$\tilde q_m = R(m\theta)\,W^Qx_m,\qquad \tilde k_n = R(n\theta)\,W^Kx_n,$$for a fixed base angle $\theta$. The query is rotated by $m\theta$, the key by $n\theta$. Now compute their dot product. Rotations satisfy $R(m\theta)^\top R(n\theta)=R((n-m)\theta)$, so
$$\tilde q_m^\top\tilde k_n = (W^Qx_m)^\top\,R\big((n-m)\theta\big)\,(W^Kx_n).$$The positions $m$ and $n$ appear only through their difference $n-m$. Rotating both vectors by the same extra amount does not change the angle between them, so shifting the whole phrase leaves the score unchanged. That is exactly a relative position encoding.
Optional: the complex-number view used in the paper
A 2-D vector $(a,b)$ can be written as the complex number $a+b\,\mathrm{i}$ (here $\mathrm{i}=\sqrt{-1}$, not a position index). Multiplying by $e^{\mathrm{i}\phi}=\cos\phi+\mathrm{i}\sin\phi$ rotates it by $\phi$. RoPE in this notation is
$$f_q(x_m,m)=(W^Qx_m)\,e^{\mathrm{i}m\theta},\qquad f_k(x_n,n)=(W^Kx_n)\,e^{\mathrm{i}n\theta},$$and the dot product of the two 2-D vectors is the real part of one times the complex conjugate of the other:
$$\langle f_q, f_k\rangle = \mathrm{Re}\big[(W^Qx_m)\,\overline{(W^Kx_n)}\,e^{\mathrm{i}(m-n)\theta}\big],$$which again depends on positions only through $m-n$.
Higher dimensions
Real queries and keys have $d$ dimensions (e.g., 128 per head). RoPE splits them into $d/2$ pairs and rotates pair $k$ by angle $m\theta_k$, each pair with its own frequency:
$$\theta_k = 10000^{-2(k-1)/d},\qquad k=1,\dots,d/2.$$Equivalently, $\tilde q_m=R^d_{m}W^Qx_m$ with a block-diagonal matrix $R^d_m$ made of $d/2$ rotation blocks $R(m\theta_1),\dots,R(m\theta_{d/2})$, and
$$\tilde q_m^\top\tilde k_n = x_m^\top (W^Q)^\top R^d_{n-m}\, W^K x_n.$$- These are exactly the frequencies of the sinusoidal positional encoding: early pairs rotate fast (fine-grained, local distances) and later pairs rotate slowly (coarse, long distances), like the bits of a binary counter.
- Only queries and keys are rotated. Values are untouched, and nothing is added to the input embeddings.
- RoPE has no learned parameters and no clipping table, and it works with any sequence length.
How well does it work?
On the GLUE benchmark, the original RoFormer paper reports results that are mixed compared with BERT: better on some tasks (e.g., MRPC, STS-B, QQP) and worse on others (e.g., SST-2, MNLI). RoPE's real success came later: it handles long inputs gracefully and is easy to extend to longer contexts, and it has become the standard choice in large language models such as the LLaMA, Mistral, and Qwen families.
5Comparing positional encodings
| Method | Where position enters | Absolute or relative | Learned parameters |
|---|---|---|---|
| Sinusoidal | added to input embeddings | absolute | none |
| Learned absolute | added to input embeddings | absolute | one vector per position |
| Relative embeddings (Shaw) | attention scores (key side) | relative | $2k+1$ vectors |
| RoPE | rotation of queries and keys | relative | none |
Two other relative methods worth knowing:
- T5 relative bias: adds a learned scalar to each attention score, depending on the (bucketed) distance $j-i$.
- ALiBi: subtracts a penalty proportional to the distance, $-\,c\cdot|i-j|$, from each score, with no learned parameters: the farther away, the less attention.
6Summary
- Absolute encodings label each token with its index; relative encodings describe each key by its offset $r_{i,j}=j-i$ from the query.
- Clipping limits offsets to $[-k,k]$, giving $2k+1$ learned embeddings that work for any sequence length.
- Shaw et al. add the relative embedding to the key inside the score: $q_i\cdot(k_j+a_{r_{i,j}})$. The same word pair gets the same score anywhere in the sequence.
- RoPE rotates queries and keys by angles proportional to their positions; their dot product depends only on $n-m$.
- RoPE uses the sinusoidal frequencies, has no parameters, and is the standard in modern large language models.
7Practice
Exercise 1: relative positions with clipping
With $k=3$, compute $r_{i,j}$ for query $i=2$ and keys $j=0,1,\dots,8$.
Exercise 2: number of embeddings
A model uses relative position embeddings with $k=16$ and $d_k=64$. How many relative embedding vectors and parameters are needed for the key side? Does this depend on the sequence length?
Exercise 3: RoPE in 2-D
With $\theta=30^\circ$, a query at position 1 and a key at position 4 are rotated by how much? What other pair of positions gives exactly the same score (for the same words)?
Quick quiz
8Further reading
- EleutherAI (2021). Rotary Embeddings: A Relative Revolution. EleutherAI blog. (Intuition and code for RoPE.)
- Fleetwood (2024). You Could Have Designed State of the Art Positional Encoding. Hugging Face blog. (From absolute positions to RoPE, step by step.)
- Shaw, Uszkoreit & Vaswani (2018). Self-Attention with Relative Position Representations. NAACL.
- Su, Lu, Pan, Murtadha, Wen & Liu. RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing (2024).