# Positional Encoding Explained: Absolute, Relative and RoPE

> Self-attention cannot see token order, so positional encodings tell the model where a token is or how far apart two tokens are: sinusoidal and learned encodings are added to the input, relative biases and ALiBi act on attention scores, and RoPE rotates queries and keys.

- URL: https://dmxsf.com/en/wiki/architecture/positional-encoding/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-08
- Tags: Positional encoding, RoPE, Transformer, Long context

## After this page you will be able to

- Explain why self-attention cannot tell token order without positional information, and what role the causal mask plays.
- Say where sinusoidal encodings, learned encodings, relative biases, ALiBi and RoPE each put the position information.
- Explain why the RoPE dot product depends only on relative position, and verify it with a few lines of code.
- Say why long-context models depend so heavily on position design: low-frequency dimensions that never complete a turn are the hard part of extrapolation.

If you have read [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/) but positional encoding still feels like formulas without intuition, this page is the natural next step. It assumes [Attention Basics: How a Transformer Reads Context](https://dmxsf.com/en/wiki/architecture/attention-basics/).

## Why self-attention has no sense of order

The core formula of attention is

$$
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V
$$

Nothing in it tells the model which token comes first, which comes later, or how far apart two tokens are. More precisely, self-attention without a mask is **permutation-equivariant**: reorder the $n$ input vectors with any permutation $P$ and the outputs are reordered by the same permutation. A token's output vector does not change because it was moved.

$$
\mathrm{Attention}(PX)=P\,\mathrm{Attention}(X)
$$

Here $\mathrm{Attention}(X)$ means self-attention on $X$ with fixed $W_Q,W_K,W_V$. For language this is a disaster:

- "Dog bites man" and "man bites dog" use the same words and mean different things.
- Coreference, temporal order and logical structure all depend on position.

The code below checks this on random data, and contrasts it with the causal-mask case:

```python
import torch

torch.manual_seed(0)
n, d = 6, 16
x = torch.randn(n, d)
Wq, Wk, Wv = (torch.randn(d, d) / d**0.5 for _ in range(3))

def attention(x, causal=False):
    q, k, v = x @ Wq, x @ Wk, x @ Wv
    scores = q @ k.T / d**0.5
    if causal:
        scores = scores.masked_fill(torch.triu(torch.ones(n, n), 1).bool(), float("-inf"))
    return torch.softmax(scores, dim=-1) @ v

perm = torch.randperm(n)  # shuffle the order of the 6 tokens
for causal in (False, True):
    same = torch.allclose(attention(x[perm], causal), attention(x, causal)[perm], atol=1e-5)
    print(f"causal mask={causal!s:5}: output of shuffled input == shuffled original output -> {same}")
```

Output:

```text
causal mask=False: output of shuffled input == shuffled original output -> True
causal mask=True : output of shuffled input == shuffled original output -> False
```

Why is the second line `False`? A causal mask lets token $t$ see only the first $t$ positions, so after shuffling, each token sees different content and equivariance no longer holds. This means a decoder-only model can, in principle, read position off clues such as "how many tokens are before me" even without any positional encoding. Kazemnejad et al. (2023) call this NoPE and give a constructive proof (for a sequence that starts with `<bos>`): the first layer can recover absolute positions using the causal mask and the softmax, and later layers can implement relative positional encoding. How it performs in experiments is covered in the comparison table below.

Still, the Llama series and many other models inject position explicitly with RoPE, and the sections below walk through the explicit routes.

## Absolute positional encoding: a fixed ID for every position

The original Transformer paper uses absolute positional encoding. The idea is simple: position $pos$ gets a vector $p_{pos}$ that is added to the token embedding, so the model's input becomes

$$
h_{pos}=\mathrm{emb}(x_{pos})+p_{pos}
$$

Two tokens with identical content now get different input vectors when they sit at different positions. The vector $p_{pos}$ comes from one of two sources:

- **Learned**: a table of size $n_{\text{ctx}}\times d$, where position $pos$ looks up row $pos$ and the table is trained with everything else. The number of rows is the maximum context length (GPT-2 has 1024).
- **Fixed formula**: the sinusoidal encoding in the next section, with no parameters at all.

The original paper tried both: learned embeddings and the sinusoidal version gave nearly identical results (Table 3, row E). The authors chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones seen in training.

## Why sinusoidal encoding became the classic

*Attention Is All You Need* uses fixed sine and cosine functions, with $0\le i<d/2$:

$$
PE_{(pos,\,2i)}=\sin\!\left(\frac{pos}{10000^{2i/d}}\right),\qquad
PE_{(pos,\,2i+1)}=\cos\!\left(\frac{pos}{10000^{2i/d}}\right)
$$

Each pair of dimensions $(2i,2i+1)$ is the sine and cosine of one frequency $\omega_i=10000^{-2i/d}$, with wavelength $2\pi\cdot10000^{2i/d}$: from $2\pi\approx6.3$ positions for pair 0, growing geometrically to almost $10000\cdot2\pi$ (the paper says the wavelengths form a geometric progression from $2\pi$ to $10000\cdot2\pi$). You do not need to memorize the formula. The design motivation matters more:

- Different dimensions have different frequencies.
- Low-frequency dimensions change slowly and describe long-range trends.
- High-frequency dimensions change quickly and separate neighbouring positions.

Every position therefore gets a unique "phase signature" made of many frequencies.

## Why this design is clever

Sinusoidal encoding became the classic for three reasons:

1. It needs no learned parameters.
2. Different positions are naturally distinguishable.
3. A relative shift can be expressed indirectly through trigonometric identities.

The third point matters most. Fix an offset $k$. For every frequency $\omega_i$ the angle-addition formulas give

$$
\begin{pmatrix}\sin\big((pos+k)\omega_i\big)\\ \cos\big((pos+k)\omega_i\big)\end{pmatrix}
=\begin{pmatrix}\cos k\omega_i&\sin k\omega_i\\ -\sin k\omega_i&\cos k\omega_i\end{pmatrix}
\begin{pmatrix}\sin(pos\,\omega_i)\\ \cos(pos\,\omega_i)\end{pmatrix}
$$

In words, the encoding of position $pos+k$ is the encoding of position $pos$ multiplied by a matrix that depends only on the offset $k$, not on $pos$ (the paper puts it this way: for any fixed offset $k$, $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$). That matrix is a two-dimensional rotation, and RoPE later uses exactly this structure of "position difference = rotation" directly on the attention scores. The same angle-addition formula also shows that the dot product of two position encodings depends only on how far apart they are:

$$
PE_{pos}\cdot PE_{pos+k}=\sum_{i=0}^{d/2-1}\cos(k\,\omega_i)
$$

So although it looks like an absolute encoding, the model has a chance to recover some relative-position information from it. That is why it was the default of early Transformers.

## Hands-on: the positional encoding matrix

The widget below draws the sinusoidal encoding as a heat map, one row per position, like a fingerprint. Drag "highlighted position p" and the table lists that position's values on a few dimension pairs; the curve underneath verifies the third point above.

Things to notice:

1. **Columns on the left (high frequency) flip sign every few positions, columns on the right (low frequency) barely change across the whole page.** Many frequencies stacked together are what make every row different.
2. **The dot product of two positions depends only on how far apart they are.** Change p and the curves coincide; the farther apart, the smaller the dot product. The model therefore has a chance to read relative distance out of the summed vectors.
3. **There are no learned parameters and no length limit.** The formula is defined for any p, but being able to compute an encoding is not the same as the model performing well on longer sequences, which the extrapolation section returns to.

## Limits of absolute encodings

Absolute encodings are easy to understand but come with long-standing problems:

- The model sees a position index, and does not necessarily generalize to longer sequences.
- When the inference length exceeds the training distribution, extrapolation of absolute representations is often unstable.
- For many tasks what matters is how far apart two tokens are, not that this one is token number 517.

The expansion of the attention score shows the same thing. After adding $p_m,p_n$ to the inputs, the score between the query at position $m$ and the key at position $n$ is

$$
(x_m+p_m)^\top W_q^\top W_k\,(x_n+p_n)
=x_m^\top W_q^\top W_k\,x_n
+x_m^\top W_q^\top W_k\,p_n
+p_m^\top W_q^\top W_k\,x_n
+p_m^\top W_q^\top W_k\,p_n
$$

Only the first of the four terms is free of position. The other three contain $p_m$ or $p_n$, so position enters the score as an absolute index and the model has to learn by itself how to extract "these two indices differ by this much". That is why the community moved quickly to relative encodings.

## Relative positional encoding: distance instead of index

The core idea of relative positional encoding is that, for attention, how many steps separate token A and token B often matters more than their absolute indices. For example:

- Whether a subject and its verb are 2 words or 20 words apart is often more informative than "the subject is word 3".
- In long contexts, both local neighbourhoods and long-range relations are relative notions.

So relative encodings inject the position difference directly into the attention scores or the attention representation, which makes it easier to learn whether nearer tokens are more relevant, whether certain offsets matter in particular, and how long-range dependencies should be kept. Three common implementations:

- **Relative position representations** (Shaw et al., 2018): learn one vector per relative distance and add it inside the attention score. Distances are clipped to $[-k,k]$, giving $2k+1$ vectors. The authors hypothesized that precise relative position stops being useful beyond some distance, and clipping also lets the model handle sequence lengths unseen in training. Their machine translation experiments use $k=16$.
- **A scalar bias on the scores** (T5, Raffel et al., 2020): simplify the vector to a scalar added directly to the attention logit. Each head has 32 scalars, distances are bucketed logarithmically, and all distances beyond 128 share one bucket. The parameters are shared across layers, while each head within a layer has its own set.
- **A linear distance penalty** (ALiBi, Press et al., 2022): no learned position parameters at all; the logit is reduced by a penalty proportional to distance, $m_h\cdot|i-j|$. The slopes $m_h$ are a fixed geometric sequence, $2^{-1},2^{-2},\dots,2^{-8}$ for 8 heads.

## Why relative positions suit long sequences

A big problem with absolute positions is that sequences of different lengths change what an index means. Relative positions are more stable:

- Whether a sentence has 64 or 4096 tokens, "3 tokens apart" is roughly the same relation.

This makes relative modeling a more natural fit for long contexts and length extrapolation, and many modern long-sequence methods borrow the relative idea to some degree.

Putting the three lines side by side makes it clear that they answer different questions:

*Figure: Absolute position is like numbering every token, relative position stresses how far apart tokens are, and RoPE writes that distance relation into the matching function of the query and the key.*

## RoPE: turning position into rotation

RoPE (Rotary Position Embedding, Su et al., 2021) is popular because it writes position modeling in a remarkably elegant geometric form:

- It does not simply add a position vector to the token.
- It rotates two-dimensional subspaces of the query and key by an angle that depends on position.

In other words, position is no longer a label attached to a token; the vector changes its phase with position.

What makes this work is that relative position shows up naturally in the dot product of query and key. RoPE does not stuff an extra position bias into attention; it builds position into the attention computation itself.

## A geometric picture of RoPE

Split a vector into pairs of dimensions. Each pair is a point in a plane. RoPE then does the following:

- At position 1, rotate by one angle.
- At position 2, rotate by a larger angle.
- At position 3, keep rotating by the same rule.

The same token representation therefore has a different phase at different positions, and the relative distance between two positions ends up as the difference of their rotation angles.

This is why people say RoPE has such geometric beauty: it translates position relations into phase relations.

## The RoPE formula: why the dot product depends only on relative position

Let the head dimension $d$ be even. Pair adjacent dimensions into $d/2$ pairs; pair $i$ is rotated at position $m$ by the angle $m\theta_i$, where

$$
\theta_i=b^{-2i/d},\qquad i=0,1,\dots,\tfrac d2-1
$$

and $b$ is the base (10,000 in the RoFormer paper). Assemble the 2D rotation matrices $R(\phi)$ of the pairs into a block-diagonal matrix $R_m$:

$$
R(\phi)=\begin{pmatrix}\cos\phi&-\sin\phi\\ \sin\phi&\cos\phi\end{pmatrix},\qquad
R_m=\mathrm{diag}\big(R(m\theta_0),\,R(m\theta_1),\,\dots,\,R(m\theta_{d/2-1})\big)
$$

RoPE is not added to the input. After computing $q_m=W_qx_m$ and $k_n=W_kx_n$, each is rotated according to its own position and then the dot product is taken:

$$
(R_mq_m)^\top(R_nk_n)=q_m^\top R_m^\top R_n\,k_n=q_m^\top R_{n-m}\,k_n
$$

The last step relies on two properties of rotation matrices: the transpose is the inverse rotation, $R(\alpha)^\top=R(-\alpha)$, and angles add, $R(\alpha)R(\beta)=R(\alpha+\beta)$. Hence $R(m\theta)^\top R(n\theta)=R\big((n-m)\theta\big)$ in every $2\times2$ block, which assembles into $R_m^\top R_n=R_{n-m}$.

Three consequences follow:

1. Position enters the score only through $n-m$: shifting the query and the key by the same amount leaves the score unchanged.
2. $R_m$ is orthogonal, so rotation does not change a vector's length. Position changes who matches whom, not how large the vectors are.
3. Rotation acts only on the query and key, not the value: position affects the attention weights but not the content that is read out.

Compared with "add a position vector" in the previous section, the four mixed terms are gone. Only $q_m^\top R_{n-m}k_n$ remains, and position appears only as relative distance.

## Hands-on: rotate q and k

The upper half of the widget draws q (blue) and k (amber) in one two-dimensional pair: drag m and n to see how they rotate, and the red arc is the angle between them. The lower half adds all pairs together and plots how the dot product changes with distance when q and k match perfectly.

Try this:

1. **Increase m and n by the same amount.** Both vectors rotate a lot, the angle between them stays the same, and so does the dot product: the RoPE dot product depends only on m−n.
2. **Compare pair 0 with the last pair.** With d=128 and base=10,000, pair 0 turns 1 radian per position, about one turn every 6.3 positions; the last pair needs about 54,000 positions per turn and barely moves over a few dozen positions. High-frequency pairs separate neighbours, low-frequency pairs handle long range.
3. **Raise the base from 10,000 to 500,000 or 1,000,000 and watch the curve at the lower right.** At the same distance the match decays more slowly. Llama 3 sets the RoPE base to 500,000, which its paper says supports longer contexts better; Code Llama raises the base from 10,000 to 1,000,000 for long-context fine-tuning and reports that this reduces the decay of attention scores with distance.

## Hands-on: verify the relative-position property in code

Below is a complete RoPE implementation that follows the RoFormer convention: adjacent dimensions $(x_{2i},x_{2i+1})$ form a pair. We put the same q at every position and the same k at every position, then check whether position pairs with the same offset give the same dot product:

```python
import torch

def apply_rope(x, base=10000.0):
    """x: (seq_len, d). Adjacent dims (x[2i], x[2i+1]) form a 2D vector, rotated by m*theta_i at position m."""
    seq_len, d = x.shape
    theta = base ** (-torch.arange(0, d, 2).float() / d)       # theta_i = base^(-2i/d), d/2 frequencies
    angle = torch.outer(torch.arange(seq_len).float(), theta)  # (seq_len, d/2): m * theta_i
    cos, sin = angle.cos(), angle.sin()
    out = torch.empty_like(x)
    out[:, 0::2] = x[:, 0::2] * cos - x[:, 1::2] * sin
    out[:, 1::2] = x[:, 0::2] * sin + x[:, 1::2] * cos
    return out

torch.manual_seed(0)
d, T = 64, 200
q, k = torch.randn(d), torch.randn(d)
Q = apply_rope(q.expand(T, d))  # the same q placed at every position
K = apply_rope(k.expand(T, d))  # the same k placed at every position
for m, n in [(3, 10), (13, 20), (103, 110), (190, 197)]:
    print(f"m={m:3d}  n={n:3d}  n-m={n - m}  dot product {Q[m] @ K[n]:.4f}")
```

Output:

```text
m=  3  n= 10  n-m=7  dot product -7.5584
m= 13  n= 20  n-m=7  dot product -7.5584
m=103  n=110  n-m=7  dot product -7.5584
m=190  n=197  n-m=7  dot product -7.5584
```

All four $(m,n)$ pairs have offset 7 and the same dot product to four decimals (the tiny differences are float32 rounding), although their absolute positions range from 3 to 190. That is the numerical check of $q_m^\top R_{n-m}k_n$.

The Llama implementation in Hugging Face looks slightly different: instead of pairing adjacent dimensions it pairs dimension $i$ with dimension $i+d/2$ (`rotate_half`). The two conventions differ only by a fixed permutation of dimensions and are mathematically equivalent. The code below verifies it (it reuses `apply_rope` from above):

```python
def apply_rope_half(x, base=10000.0):
    """The Llama convention in Hugging Face: dimension i is paired with dimension i + d/2."""
    seq_len, d = x.shape
    theta = base ** (-torch.arange(0, d // 2).float() * 2 / d)
    angle = torch.outer(torch.arange(seq_len).float(), theta)
    angle = torch.cat([angle, angle], dim=-1)
    x1, x2 = x[:, : d // 2], x[:, d // 2 :]
    return x * angle.cos() + torch.cat([-x2, x1], dim=-1) * angle.sin()

x = torch.randn(10, 64)
perm = torch.cat([torch.arange(0, 64, 2), torch.arange(1, 64, 2)])  # even dims first, then odd dims
print(torch.allclose(apply_rope(x)[:, perm], apply_rope_half(x[:, perm]), atol=1e-5))
```

Output:

```text
True
```

## Why RoPE matters for long context

RoPE is popular not only because it is elegant but because it is practical in modern LLMs:

1. It fits naturally with the attention dot product.
2. It expresses relative position naturally.
3. Its frequency structure is explicit, so changing a few frequency parameters extends the window (see the next section) without redesigning the architecture.
4. It is easy to integrate into an existing Transformer.

That is why the Llama series (Llama 2, Llama 3 and Code Llama all use RoPE) and a large body of long-context work chose or inherited RoPE.

## Why RoPE still faces a length-extrapolation problem

Many introductions leave the impression that with RoPE the long-context problem is mostly solved. It is not that simple, and the reason starts with which angles each frequency saw during training.

The wavelength of pair $i$ is $\lambda_i=2\pi\,b^{2i/d}$ (the number of positions needed for one full turn). With training length $L$, the pair completes $L/\lambda_i$ turns during training:

- **High-frequency pairs (many turns):** every phase has been seen. Beyond $L$ they simply keep turning through known phases, so nothing is unfamiliar to the model.
- **Low-frequency pairs (less than one turn):** training covered only part of one turn. Beyond distance $L$ the angle enters a range that never appeared in training. That is true extrapolation, and the attention scores become unreliable.

Counting with code, for $d=128$ and $b=10{,}000$, the wavelengths and how many pairs never complete a turn:

```python
import math

d, base, L = 128, 10000, 4096
wavelength = [2 * math.pi * base ** (2 * i / d) for i in range(d // 2)]  # positions per full turn of pair i
print(f"pair 0: {wavelength[0]:.1f}, pair 31: {wavelength[31]:.0f}, last pair: {wavelength[-1]:,.0f} positions per turn")
print(f"pairs with wavelength above L={L}: {sum(w > L for w in wavelength)} / {d // 2}")
print(f"pairs above 8192: {sum(w > 8192 for w in wavelength)}, above 32768: {sum(w > 32768 for w in wavelength)}")
```

Output:

```text
pair 0: 6.3, pair 31: 544, last pair: 54,410 positions per turn
pairs with wavelength above L=4096: 18 / 64
pairs above 8192: 14, above 32768: 4
```

With $L=4096$, 18 of the 64 pairs fall into the low-frequency group. Direct extrapolation therefore breaks quickly: the Position Interpolation (PI) paper reports that, beyond the training window, perplexity can shoot above $10^3$, comparable to an untrained model. For LLaMA 7B extended to 8192, direct extrapolation gives perplexity above $10^3$, while position interpolation without any fine-tuning gives below 20. The methods that came later all change the frequencies so that longer sequences fall inside the phase range seen in training:

- Position interpolation (PI): divide all frequencies by the extension factor $s$.
- NTK-aware scaling: switch to a larger base.
- YaRN: treat pairs differently according to how many turns they make, compress only the low-frequency pairs, and add an attention temperature.
- Other RoPE scaling and extrapolation techniques.

The derivations, comparisons and an interactive demo with adjustable parameters are in [Long Context: Position Extrapolation, Training Recipes and Cost](https://dmxsf.com/en/wiki/architecture/long-context/). The right takeaway is that RoPE is an important foundation of modern long-context modeling, but not the end of the story.

Drawing one high-frequency and one low-frequency pair inside and outside the training length shows where the problem lies:

*Figure: Schematic; the curves are cos(θ·distance): the high-frequency pair makes 3 turns per L positions, the low-frequency pair 0.4 turn. The high-frequency pair has seen every phase within the training length and merely repeats in the extrapolation zone; the low-frequency pair does not complete a turn, so beyond L it enters angles never seen. This is the main source of extrapolation failures and what PI, NTK-aware scaling and YaRN deal with.*

## Comparison of position schemes

| Scheme | Where position enters | Learned position parameters | Facts worth remembering |
| --- | --- | --- | --- |
| Sinusoidal (Vaswani et al., 2017) | Added to the input embeddings | None | Wavelengths form a geometric progression from $2\pi$ to $10000\cdot2\pi$; $PE_{pos+k}$ is a linear function of $PE_{pos}$; nearly identical to learned embeddings |
| Learned absolute (e.g. GPT-2) | Added to the input embeddings | A table of $n_{\text{ctx}}\times d$ | The number of rows is the maximum context length: 1024 for GPT-2 |
| Relative position representations (Shaw et al., 2018) | A relative-position vector inside the attention score | $2k+1$ vectors | Distance clipped to $\pm k$; $k=16$ in the machine translation experiments |
| T5 relative bias (Raffel et al., 2020) | A scalar bias on the attention logit | 32 scalars per head, shared across layers | Logarithmic distance buckets; all distances beyond 128 share one bucket |
| ALiBi (Press et al., 2022) | Subtracts $m_h\cdot$distance from the attention logit | None, slopes are fixed | A 1.3B model trained at length 1024 reaches, at 2048, the same perplexity as a sinusoidal model trained at 2048, while training about 11% faster and using about 11% less memory |
| RoPE (Su et al., 2021) | Rotates the query and key | None | Dot product depends only on relative position; used by the Llama series; the window is extended by changing the base or scaling frequencies |
| No positional encoding (NoPE, Kazemnejad et al., 2023) | Not injected explicitly; relies on the causal mask | None | In from-scratch decoder-only models of about 107M parameters on a set of reasoning and math tasks, length generalization was better than with APE, the T5 bias, ALiBi and RoPE |

Three things to keep in mind when reading the table:

1. Conclusions about extrapolation depend on model scale, task and training setup, so the schemes cannot be ranked simply. The NoPE paper itself admits it could not study the effect of large-scale pretraining. In its post-submission pretraining of 1B-parameter code language models with a context length of 1024, RoPE's perplexity exploded beyond the training length, while NoPE and ALiBi extrapolated to almost twice the training length, with ALiBi relatively more stable beyond that.
2. Being able to compute an encoding at any position is not the same as using it well: sinusoidal encoding has no length limit, yet direct extrapolation with it is not impressive.
3. In practice, RoPE's length extension comes mainly from modifying the frequencies (the base or frequency scaling) together with continued training on long sequences; see [Long Context](https://dmxsf.com/en/wiki/architecture/long-context/).

## Why position encoding affects RAG and long-context products

Positional encoding is not just a benchmark detail; it directly shapes real systems:

- Whether a long-document QA system can reliably use information from the middle.
- Whether variables and function definitions stay connected in a long code context.
- Whether the model still holds on to key earlier turns after a conversation grows long.

That is why papers such as [Lost in the Middle](https://dmxsf.com/en/blog/lost-in-the-middle/), although mainly empirical studies of a phenomenon, keep running into positional encoding and attention design.

## Common misconceptions

### 1. Positional encoding is just adding a sequence number to each token

What matters is how the number enters the attention computation and whether it can express relative relations.

### 2. Absolute and relative positions are an either-or choice

Many modern methods sit between the two, or embed relative ideas into an absolute representation.

### 3. With RoPE the model automatically supports unlimited context

RoPE suits long sequences better, but length extrapolation still needs extra design and validation; see the [Long Context](https://dmxsf.com/en/wiki/architecture/long-context/) page.

### 4. Ignoring the engineering impact of position design

Positional encoding affects not only paper scores but also how well retrieved passages are used in RAG, how far a code assistant can see, and how stable multi-turn conversations are.

## Summary and exercises

**Key points:**

1. Self-attention without a mask is permutation-equivariant, so position must be supplied from outside. The causal mask of a decoder-only model leaks some position information, but the Llama series still uses RoPE explicitly.
2. In sinusoidal encoding every pair of dimensions has one frequency and the wavelengths form a geometric progression; $PE_{pos+k}$ is a linear function of $PE_{pos}$, and the dot product of two encodings depends only on their distance.
3. Relative schemes (Shaw, T5, ALiBi) put distance directly into the attention score; RoPE rotates query and key so the score becomes $q_m^\top R_{n-m}k_n$, which depends only on relative position.
4. The wavelength of RoPE pair $i$ is $2\pi b^{2i/d}$. Low-frequency pairs that do not complete a turn within the training length are the hard part of extrapolation, and PI, NTK-aware scaling and YaRN all modify the frequencies.
5. Raising the base (500,000 for Llama 3, 1,000,000 for Code Llama's long-context fine-tuning) lengthens the wavelengths and slows the decay of attention with distance.

### Quick self-check

**1. Without a mask, you shuffle the order of the n token vectors fed to self-attention. What happens to the output?**

- [ ] It is completely unchanged
- [x] Each token's output vector is unchanged, only reordered in the same way
- [ ] Every output vector becomes random
- [ ] The attention weights become uniform

> Self-attention without a mask is permutation-equivariant: a token's output depends only on its own content and the content of all tokens, not on their order, so shuffling the input just reorders the output. This is exactly why position information must be injected explicitly.

**2. In sinusoidal positional encoding, how do frequency and wavelength change as the pair index i grows?**

- [ ] Higher frequency, shorter wavelength
- [x] Lower frequency, longer wavelength
- [ ] Neither changes, only the phase differs
- [ ] The frequency first rises and then falls

> The frequency is 10000 raised to the power −2i/d, which shrinks as i grows; the wavelength 2π·10000^(2i/d) grows geometrically from 2π to almost 10000·2π.

**3. In RoPE, what does the score between the query at position m and the key at position n depend on?**

- [ ] Only the content of q and k
- [ ] The values of m and n separately
- [x] The content of q and k, and the relative position n−m
- [ ] Only n−m, independent of content

> The rotated score is the dot product of q with R(n−m)k: the content q, k and the relative position n−m decide it together, while the values of m and n alone do not matter. The code on this page checks the pairs (3,10), (13,20), (103,110) and (190,197).

**4. With d=128, base=10,000 and training length 4096, how many of the 64 pairs have a wavelength above 4096 (less than one turn within the training length)?**

- [ ] 4 pairs
- [x] 18 pairs
- [ ] 32 pairs
- [ ] 64 pairs

> The wavelength of pair i (counting from 0) is 2π·10000^(2i/128). Solving 2π·10000^(2i/128) > 4096 gives i ≥ 46, that is i = 46 to 63, 18 pairs. The code on this page confirms it.

**5. Which of these schemes do not add a position vector to the input embeddings but act on the attention q, k or scores instead? (Select all that apply)**

- [x] T5 relative position bias
- [x] ALiBi
- [x] RoPE
- [ ] Sinusoidal positional encoding

> The T5 bias and ALiBi modify the attention logits directly; RoPE rotates q and k before the dot product. Sinusoidal encoding and learned embeddings are absolute encodings added to the input embeddings.

**6. You raise the RoPE base from 10,000 to 500,000 and change nothing else. What happens?**

- [ ] Every pair rotates faster
- [x] Every pair rotates more slowly and its wavelength grows
- [ ] The dot product no longer depends only on relative position
- [ ] The parameter count increases

> θ_i = base^(−2i/d), so a larger base makes θ_i smaller: the same distance turns a smaller angle and the wavelength is longer. RoPE has no learned position parameters, and the dot product still depends only on relative position.

**Exercises:**

1. Prove $R(\alpha)^\top R(\beta)=R(\beta-\alpha)$ and explain what this step does in RoPE.
2. With $d=128$ and training length $L=8192$, how many dimension pairs have a wavelength above $L$ for base 10,000 and for base 500,000? What does this show?
3. If position vectors are added to the input, the attention score expands into four terms. Which terms contain position, and how do they differ from RoPE's $q_m^\top R_{n-m}k_n$?

<details>
<summary>Reference answers</summary>

1. $R(\alpha)^\top=R(-\alpha)$. Multiplying out $R(-\alpha)R(\beta)$ gives the four entries $\cos\alpha\cos\beta+\sin\alpha\sin\beta=\cos(\beta-\alpha)$, $\sin\alpha\cos\beta-\cos\alpha\sin\beta=-\sin(\beta-\alpha)$, $\cos\alpha\sin\beta-\sin\alpha\cos\beta=\sin(\beta-\alpha)$ and $\sin\alpha\sin\beta+\cos\alpha\cos\beta=\cos(\beta-\alpha)$, which is exactly $R(\beta-\alpha)$. In RoPE take $\alpha=m\theta_i$ and $\beta=n\theta_i$: in every $2\times2$ block $R(m\theta_i)^\top R(n\theta_i)=R((n-m)\theta_i)$. So $(R_mq)^\top(R_nk)=q^\top R_{n-m}k$: positions $m$ and $n$ affect the score only through the difference $n-m$.
2. Counting with code the pairs with $\lambda_i=2\pi\,b^{2i/128}>8192$ gives 14 pairs for base 10,000 and 29 pairs for base 500,000. The larger the base, the longer the wavelength of each pair ($\theta_i$ is smaller), so more low-frequency pairs complete less than one turn within the training length, and those pairs only use a small range of angles during training.
3. Only the first of the four terms, $x_m^\top W_q^\top W_k x_n$, is free of position; the other three contain $p_m$ or $p_n$. In all three, position appears as an absolute index, and the model has to learn to read the difference out of two indices. RoPE's score is just $q_m^\top R_{n-m}k_n$, so position enters only as the relative distance $n-m$ from the start.

</details>

## Further reading

- To see how positional encoding fits into the full architecture, continue with [Transformer Block Explained: Attention, FFN, Residuals and LayerNorm](https://dmxsf.com/en/wiki/architecture/transformer-block/).
- To see how RoPE is extended beyond 128K tokens, and what long-context training recipes cost, read [Long Context: Position Extrapolation, Training Recipes and Cost](https://dmxsf.com/en/wiki/architecture/long-context/).
- To put position in the context of the papers, read [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/), [LLaMA: Open and Efficient Foundation Language Models](https://dmxsf.com/en/blog/llama-open-and-efficient-foundation-language-models/) and [Lost in the Middle](https://dmxsf.com/en/blog/lost-in-the-middle/).
- Vaswani et al., [Attention Is All You Need](https://arxiv.org/abs/1706.03762) (2017): the sinusoidal encoding in Section 3.5 and the comparison with learned embeddings.
- Shaw, Uszkoreit and Vaswani, [Self-Attention with Relative Position Representations](https://arxiv.org/abs/1803.02155) (2018); Raffel et al., [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) (T5, 2020): relative position representations and the relative position bias.
- Su et al., [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) (2021): the definition and derivation of RoPE; the [paper breakdown](https://dmxsf.com/en/blog/roformer-rotary-position-embedding/) checks its experimental protocol and reproduces the decay quantity of Figure 2 in code.
- Press, Smith and Lewis, [Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation](https://arxiv.org/abs/2108.12409) (ALiBi, ICLR 2022).
- Kazemnejad et al., [The Impact of Positional Encoding on Length Generalization in Transformers](https://arxiv.org/abs/2305.19466) (2023): NoPE compared with other positional encodings on length generalization.
- Chen et al., [Extending Context Window of Large Language Models via Position Interpolation](https://arxiv.org/abs/2306.15595) (2023); Rozière et al., [Code Llama: Open Foundation Models for Code](https://arxiv.org/abs/2308.12950) (2023); Llama Team, [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) (2024): the failure of direct extrapolation, and changing the RoPE base.

## Companion code

[Position encodings and length extrapolation](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/positional-encoding): Sinusoidal encodings as clocks, RoPE's score depending only on distance, the stretching recipes (position interpolation, NTK-aware, YaRN, the Llama 3.1 rule) computed side by side, and five position schemes trained on short text and tested on long text.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/positional-encoding`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/README.en.md)
- [`position.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/position.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#positional-encoding)

## FAQ

### Why does a Transformer need positional encoding?

Self-attention without a mask is permutation-equivariant: shuffle the input tokens and every token's output stays the same, it just moves with its token. Positional encoding injects where a token is, or how far apart two tokens are, into the representations or the attention scores, so the model can tell dog bites man from man bites dog. The causal mask of a decoder-only model leaks some order information by itself, so training without any explicit encoding (NoPE) works, but mainstream models such as the Llama series still use RoPE explicitly.

### What is the difference between absolute, relative and rotary (RoPE) position encodings?

Absolute encodings give every position a fixed vector (sinusoidal or learned) that is added to the input. Relative encodings (Shaw's relative position representations, T5's bias, ALiBi) make the attention score depend directly on the distance between tokens. RoPE rotates the query and the key by an angle that depends on position, so their dot product depends only on the relative position, which keeps the implementation simple and still expresses relative distance.

### Does RoPE give you unlimited context length?

No. The largest distance seen in training is the training length L. Low-frequency dimension pairs that do not complete a turn within L meet angles beyond L that were never seen in training, and attention scores become unreliable (the Position Interpolation paper reports that direct extrapolation beyond the training window can push perplexity above 1000, comparable to an untrained model). Frequency scaling such as position interpolation, NTK-aware scaling or YaRN, continued training on long sequences and evaluation at the target length are still needed. RoPE is a foundation of modern long-context modeling, not the finish line.

### What is the RoPE base (10,000 or 500,000) and what does raising it do?

The base sets the rotation frequency of each dimension pair, θ_i = base^(−2i/d): the larger the base, the smaller the angle turned over a given distance and the longer the wavelength of each pair. Code Llama raised the base from 10,000 to 1,000,000 for long-context fine-tuning and reports that this reduces the decay of attention scores with distance. Llama 3 uses a base of 500,000, which its paper says supports longer contexts better, citing Xiong et al. (2023) for the value being effective up to 32,768 tokens.

### Does positional encoding affect RAG and long-context applications?

Yes. Position design changes how sensitive the model is to information at different distances, which affects how well retrieved passages are used, how far back a code assistant can see a definition, and how stable long conversations are. When you build a long-context application, measure quality at the target length and at different positions instead of assuming that a longer context is always better.
