CSCE 471 Natural Language Processing · Spring 2027

Relative Positional Encoding

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to distinguish absolute from relative positions · compute the relative position matrix $r_{i,j}=j-i$ and apply clipping · explain how relative position embeddings enter the attention score · explain why relative methods give the same score to the same word pair at any location · describe RoPE as rotating queries and keys and show why their dot product depends only on the distance · compare sinusoidal, relative, and rotary encodings

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.

Click a token to make it the reference
Figure 1 (interactive). Positions in a 12-token sequence. In relative mode, each token is labeled by its offset from the reference token (red). Move the reference and watch every relative label shift, while absolute labels never change.

Why relative positions?

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.

Clipping distance $k$:Click a cell
Figure 2 (interactive). The relative position matrix $r_{i,j}$ for 10 tokens (rows: query $i$, columns: key $j$). Clipped values are shown in red. The orange chips are the $2k+1$ learned relative position embeddings; the selected cell's embedding is highlighted. Set $k=10$ to turn clipping off.

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”.

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.

Phrase starts at position $s$:
Figure 3 (interactive). Attention score from cat (query) to the (key) in a toy model, as the phrase the cat is moved along the sequence. With an absolute sinusoidal encoding added to the inputs (red), the score wobbles with the location; with a relative position embedding (blue), it is constant.

Results on machine translation

ModelPosition informationEN–DE BLEUEN–FR BLEU
Transformer (base)absolute26.538.2
Transformer (base)relative26.838.7
Transformer (big)absolute27.941.2
Transformer (big)relative29.241.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.

Query position $m$:Key position $n$:
Base angle $\theta$ = 20°
Figure 4 (interactive). RoPE in 2-D. The unrotated query and key are drawn faintly; the rotated versions are drawn solid. The dot product depends only on the angle between the rotated vectors, which depends only on $n-m$. Click “Shift both by +3” to move both tokens: the vectors rotate, but the score stays the same.
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.$$

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

MethodWhere position entersAbsolute or relativeLearned parameters
Sinusoidaladded to input embeddingsabsolutenone
Learned absoluteadded to input embeddingsabsoluteone vector per position
Relative embeddings (Shaw)attention scores (key side)relative$2k+1$ vectors
RoPErotation of queries and keysrelativenone

Two other relative methods worth knowing:

6Summary

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$.

$j-i = -2,-1,0,1,2,3,4,5,6$, clipped to $[-3,3]$: $\;-2,-1,0,+1,+2,+3,+3,+3,+3$.

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?

$2k+1=33$ vectors, $33\times 64=2{,}112$ parameters. No: clipping makes it independent of 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)?

The query is rotated by $30^\circ$ and the key by $120^\circ$; the score depends on the difference $(4-1)\times 30^\circ=90^\circ$. Any pair with $n-m=3$, e.g. positions 10 and 13, gives the same score.

Quick quiz

8Further reading