◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

Positional Encodings

Self-attention sees a sentence as an unordered bag of tokens, so Transformers must be told where each token sits. Sinusoidal waves, learned position vectors, rotations (RoPE) and distance penalties (ALiBi) are the main ways to do it, and they decide how far a model's context can stretch.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

Self-Attention and Multi-Head Attention

This leads to

The Transformer
The full path from zero — 24 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. LSTMs and GRUs
  22. Sequence-to-Sequence Models
  23. Attention
  24. Self-Attention and Multi-Head Attention
  25. Positional Encodings

Read them roughly in this order. See it on the concept map →

Why it matters

"Dog bites man" and "man bites dog" contain the same three words. Only the order tells you which one is news. Yet the Self-Attention and Multi-Head Attention layer at the heart of every Transformer cannot see order at all. Each token's output is a weighted average of all value vectors, and an average doesn't care what order its ingredients came in. Shuffle the input tokens and you get exactly the same outputs, shuffled the same way.

A positional encoding fixes this by injecting each token's position into the computation. It sounds like a detail, but the choice matters a great deal in practice:

  • It decides whether a model can handle texts longer than the ones it was trained on.
  • The tricks for stretching a model's context window from 4,000 tokens to 128,000 or more are almost all tricks about positional encodings.
  • The method used by most open models today, RoPE, has its own quirks that you meet as soon as you fine-tune or serve them (Running Models Locally, Serving LLMs at Scale).

The intuition

Imagine a pile of index cards, one word per card, that someone dropped on the floor. To rebuild the sentence you need page numbers on the cards. There are a few ways to write them:

  1. Stamp an absolute address on each card. "This is card 7." That is what sinusoidal and learned positional encodings do: they add a position-specific vector to each token's embedding.
  2. Only record relative positions. You rarely care that a word is the 1,503rd in a book. You care that the adjective is right before its noun, or that "it" is five words after "the animal". Relative methods make attention depend on the distance between two tokens, not their absolute addresses. RoPE and ALiBi do this.

How do you write "position 7" as a vector of, say, 512 numbers? Think of a clock. The second hand moves fast and distinguishes moments a second apart, but repeats every minute. The minute hand distinguishes minutes and repeats every hour; the hour hand repeats every half day. Read together, the hands give a unique time over a long span. The sinusoidal encoding is a clock with hundreds of hands, each turning at a different speed.

Sinusoidal positional encoding, d_model = 64: four of the 64 dimensions Each dimension is a sine wave over position with its own wavelength. Dots mark whole positions 0 to 60. dimension 0 wavelength ≈ 6 +0.657 dimension 8 wavelength ≈ 20 +0.800 dimension 16 wavelength ≈ 63 +0.644 dimension 24 wavelength ≈ 199 +0.220 position 7 value at position 7 0 20 40 60 position in the sequence Fast waves tell neighbours apart; slow waves tell distant positions apart. (The odd dimensions hold matching cosines.)
Fig. 1 Four of the 64 dimensions of a sinusoidal positional encoding, computed from the formula. Each dimension oscillates with its own wavelength. The values at position 7 (orange) form part of that position's unique fingerprint.

Key idea Attention is blind to order. Positional encodings put order back, either by adding a "where am I" vector to each token (absolute) or by making attention scores depend on the distance between tokens (relative, as in RoPE and ALiBi).

How it works

Sinusoidal encodings (the original Transformer)

The original Transformer added a fixed vector ppos\mathbf{p}_{\text{pos}} to each token embedding. Its entries are sines and cosines at geometrically spaced frequencies. For position pos\text{pos} and dimension pair i=0,1,…,d/2−1i = 0, 1, \dots, d/2 - 1:

ppos, 2i=sin⁡ ⁣(pos100002i/d),ppos, 2i+1=cos⁡ ⁣(pos100002i/d)\mathbf{p}_{\text{pos},\,2i} = \sin\!\left(\frac{\text{pos}}{10000^{2i/d}}\right), \qquad \mathbf{p}_{\text{pos},\,2i+1} = \cos\!\left(\frac{\text{pos}}{10000^{2i/d}}\right)

Here dd is the embedding size. Even dimensions get a sine, odd ones a cosine of the same frequency. The number 10,000 sets the slowest wavelength. Dimension 0 completes a cycle every 2π≈6.32\pi \approx 6.3 positions; the last dimensions take up to 2π×10,000≈63,0002\pi \times 10{,}000 \approx 63{,}000 positions.

Worked example. With d=64d = 64, position 1, the first pair (i=0i = 0) has frequency 1/100000=11/10000^0 = 1, so the values are sin⁡1=0.841\sin 1 = 0.841 and cos⁡1=0.540\cos 1 = 0.540. The second pair (i=1i = 1) has frequency 1/100002/64=0.7501/10000^{2/64} = 0.750, so sin⁡0.750=0.682\sin 0.750 = 0.682 and cos⁡0.750=0.732\cos 0.750 = 0.732. The vector for position 1 starts (0.841,0.540,0.682,0.732,… )(0.841, 0.540, 0.682, 0.732, \dots).

Two properties made this attractive:

  • Unique and bounded. Every position gets a distinct pattern, and all values stay between −1 and 1, the same scale as the embeddings.
  • Distance is visible. Because sin⁡\sin and cos⁡\cos of pos+k\text{pos} + k are a fixed rotation of those at pos\text{pos}, the dot product pa⋅pb\mathbf{p}_a \cdot \mathbf{p}_b depends only on a−ba - b. In the code below, positions 10 and 13 have exactly the same similarity as positions 50 and 53.

The encoding is simply added to the token embedding: xpos=etoken+ppos\mathbf{x}_{\text{pos}} = \mathbf{e}_{\text{token}} + \mathbf{p}_{\text{pos}}. Adding rather than concatenating keeps the width the same; with hundreds of dimensions there is room for the network to keep the two kinds of information apart.

Learned positional embeddings

A simpler idea: make the position vectors parameters and learn them, exactly like token embeddings. A table with one row per position, up to some maximum length, is trained along with everything else. BERT (512 positions), GPT-2 (1,024) and GPT-3 (2,048) did this. The original Transformer paper reported that learned and sinusoidal encodings worked about equally well.

The drawback is a hard limit. Position 1,025 has no row in GPT-2's table, so the model simply cannot process longer inputs. Even sinusoidal encodings, which can be computed for any position, generalise poorly beyond the training length in practice, because the network has never seen those patterns.

RoPE: rotary position embeddings

Rotary position embedding (RoPE), introduced by Jianlin Su and colleagues in 2021, is now the standard: Llama, Mistral, Qwen, Gemma and most other open models use it. Instead of adding anything to the embeddings, RoPE rotates the query and key vectors inside every attention layer, by an angle proportional to the token's position.

Split a query vector into pairs of numbers, and treat each pair as an arrow in a 2-D plane. For a token at position mm, rotate pair ii by the angle m θim\,\theta_i, where θi=10000−2i/d\theta_i = 10000^{-2i/d} (the same frequencies as the sinusoidal encoding). For one pair (x1,x2)(x_1, x_2), rotation by angle ϕ\phi is

(x1′x2′)=(cos⁡ϕ−sin⁡ϕsin⁡ϕcos⁡ϕ)(x1x2)\begin{pmatrix} x_1' \\ x_2' \end{pmatrix} = \begin{pmatrix} \cos\phi & -\sin\phi \\ \sin\phi & \cos\phi \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \end{pmatrix}

Do the same to the keys. Now comes the clever part. The attention score is a dot product, and the dot product of two arrows depends only on their lengths and the angle between them. If the query is rotated by mθm\theta and the key by nθn\theta, the angle between them changes by (m−n)θ(m - n)\theta. So the score depends on the content of the two tokens and on their relative position m−nm - n, and not on where in the text the pair sits.

RoPE: rotate queries and keys by an angle proportional to their position Here one pair of dimensions, rotating 20° per position. The query q and key k are the same vectors in both panels. query at 5, key at 2 q k q at position 5 k at position 2 angle between them: 120° positions 5 and 2: offset 3 query at 9, key at 6 q k q at position 9 k at position 6 angle between them: 120° positions 9 and 6: offset 3 Dashed: q and k before rotation. In the right panel both are rotated further, but the angle between them, and so their dot product, depends only on the offset between the positions.
Fig. 2 RoPE in one pair of dimensions. The same query and key, placed at positions (5, 2) on the left and (9, 6) on the right. Both are rotated further on the right, but the angle between them is the same, because the offset is still 3.

Rotation never changes a vector's length, so RoPE doesn't distort the content. Fast-rotating pairs give fine-grained sensitivity to nearby positions, slow-rotating ones track long-range position. The values are never stored; they are recomputed from the position, so there is no table to run off the end of.

ALiBi: attention with linear biases

ALiBi (Press, Smith and Lewis, 2021) is even simpler. Add nothing to the embeddings and rotate nothing. Instead, after computing each attention score, subtract a penalty proportional to the distance between query and key:

scoreij=qi⋅kjdk−sh⋅(i−j)\text{score}_{ij} = \frac{\mathbf{q}_i \cdot \mathbf{k}_j}{\sqrt{d_k}} - s_h \cdot (i - j)

The slope shs_h is fixed, not learned, and different for each head hh. With 8 heads the slopes are 12,14,…,1256\tfrac12, \tfrac14, \dots, \tfrac{1}{256}. Steep heads focus on nearby tokens; shallow ones can look far back. A token 10 positions away loses 10sh10 s_h from its score before the softmax. The paper showed that a model trained on 1,024-token sequences could be run on longer ones with little loss in quality. BLOOM and MPT used ALiBi.

Stretching the context window

Suppose a RoPE model was trained on 4,096-token sequences and you want 32,768. Positions beyond 4,096 produce rotation angles the model never saw, and quality collapses. Several fixes work with a little extra fine-tuning:

  • Position interpolation (Chen et al., 2023): divide all positions by 8, so 32,768 positions are squeezed into the trained range of angles. Neighbouring tokens now differ by 1/8 of a step, which the model adapts to quickly.
  • Changing the base. Raising the 10,000 in the frequencies slows every rotation. "NTK-aware" scaling and YaRN (Peng et al., 2023) adjust the frequencies unevenly, keeping fast rotations for local detail and stretching the slow ones. Llama 3 uses a base of 500,000.

Together with efficient attention (Long Context and Efficient Attention) and enough long training documents, this is how open models went from 2,048-token contexts in 2023 to 128,000 tokens and beyond by 2024. A long window is not the same as using it well: models still tend to miss facts buried in the middle of very long inputs.

In code

Sinusoidal encodings and RoPE in NumPy, checking the two properties claimed above:

import numpy as np

def sinusoidal(n_pos, d):
    pos = np.arange(n_pos)[:, None]                 # (n_pos, 1)
    i = np.arange(0, d, 2)[None, :]                 # even dimensions 0, 2, 4, ...
    angle = pos / 10000 ** (i / d)                  # (n_pos, d/2)
    pe = np.zeros((n_pos, d))
    pe[:, 0::2] = np.sin(angle)                     # even dims: sine
    pe[:, 1::2] = np.cos(angle)                     # odd dims: cosine
    return pe

pe = sinusoidal(100, 64)
print(pe[1, :4].round(3))                           # position 1, first four dims
# similarity depends on distance, not on absolute position
print(round(pe[10] @ pe[13], 2), round(pe[50] @ pe[53], 2), round(pe[10] @ pe[40], 2))

def rope(x, pos, base=10000):
    d = x.shape[-1]
    theta = pos / base ** (np.arange(0, d, 2) / d)  # one angle per pair of dims
    cos, sin = np.cos(theta), np.sin(theta)
    x1, x2 = x[0::2], x[1::2]
    out = np.empty_like(x)
    out[0::2] = x1 * cos - x2 * sin                 # rotate each (x1, x2) pair
    out[1::2] = x1 * sin + x2 * cos
    return out

rng = np.random.default_rng(0)
q, k = rng.normal(size=8), rng.normal(size=8)
for m, n in [(5, 2), (105, 102), (1005, 1002)]:     # same offset m - n = 3
    print(m, n, round(rope(q, m) @ rope(k, n), 4))
print(round(np.linalg.norm(q), 4), round(np.linalg.norm(rope(q, 7)), 4))

# [0.841 0.54  0.682 0.732]
# 25.59 25.59 17.07
# 5 2 -1.5865
# 105 102 -1.5865
# 1005 1002 -1.5865
# 1.8627 1.8627

The RoPE score is identical for positions (5, 2), (105, 102) and (1005, 1002): only the offset of 3 matters. The last line confirms rotation doesn't change the vector's length.

Learned positional embeddings, GPT-2 style, are two lines of PyTorch:

import torch
import torch.nn as nn

vocab_size, max_len, d_model = 50257, 1024, 768          # GPT-2 small sizes
tok_emb = nn.Embedding(vocab_size, d_model)               # one vector per token id
pos_emb = nn.Embedding(max_len, d_model)                  # one learned vector per position

ids = torch.tensor([[464, 3797, 3332, 319, 262, 2603]])  # "The cat sat on the mat" (GPT-2 ids)
x = tok_emb(ids) + pos_emb(torch.arange(ids.shape[1]))   # add position to meaning
print(x.shape, pos_emb.weight.numel())
# torch.Size([1, 6, 768]) 786432

Build a GPT from Scratch uses exactly this learned approach.

Common pitfalls

  • Running past the trained length. Learned tables simply have no entry for later positions (an index error, or silent garbage if you wrap around). RoPE models degrade sharply past their training length unless a scaling method is configured. Check max_position_embeddings and any rope_scaling setting in the model's configuration.
  • Mismatched RoPE settings. Loading weights with a different RoPE base, scaling factor or pairing convention than they were trained with produces fluent-looking nonsense. Some implementations rotate adjacent pairs (x0,x1)(x_0, x_1), others pair the first half with the second half (x0,xd/2)(x_0, x_{d/2}); weights trained one way don't work the other way.
  • Off-by-one positions during generation. With a The KV Cache and Fast Inference, each new token must get the next position number, not position 0 again. A bug here quietly degrades every generated token after the first.
  • Forgetting positions entirely. An encoder with no positional information treats text as a bag of words. Its accuracy on order-sensitive tasks drops while everything still "works".

Watch out A bigger advertised context window isn't a promise of good use of it. Test retrieval and reasoning at the lengths you actually need, with your own documents, rather than trusting the maximum in the model card.

Variations

  • Relative position biases (Shaw et al., 2018; the T5 model) learn a bias for each bucket of distances, added to attention scores. ALiBi is a fixed, simpler version.
  • No positional encoding at all. Decoder-only models with a causal mask can partly infer position, because each token sees a different number of predecessors. Some research models drop positional encodings entirely, though mainstream LLMs keep RoPE.
  • 2-D and 3-D positions. Vision Transformers need to encode row and column; video models add time. Multimodal models use multi-dimensional variants of RoPE.

Next comes the full The Transformer block, which adds positional information once at the input (absolute methods) or inside every attention layer (RoPE, ALiBi).

A bit of history

The 2017 Transformer paper by Vaswani et al. introduced sinusoidal encodings and noted that learned ones performed nearly identically; they chose sinusoids hoping they would extend to longer sequences. BERT and the GPT series then used learned tables. Shaw, Uszkoreit and Vaswani (2018) introduced relative position representations, and Transformer-XL (Dai et al., 2019) and T5 (Raffel et al., 2019) developed relative schemes further. Jianlin Su and colleagues published RoFormer with rotary embeddings in 2021, at first on a Chinese blog and then on arXiv. GPT-J, GPT-NeoX and PaLM adopted it, and after Meta's LLaMA (2023) it became the default for open models. Ofir Press, Noah Smith and Mike Lewis introduced ALiBi in 2021. In 2023 position interpolation, NTK-aware scaling and YaRN made it cheap to extend the context of existing RoPE models.

Try it

  1. By hand, compute the first two numbers of the sinusoidal encoding at position 2 (sin⁡2\sin 2, cos⁡2\cos 2) and check them against sinusoidal(100, 64)[2, :2].
  2. Plot pe @ pe.T as an image (plt.imshow). Why is it brightest along the diagonal, and why do the stripes run parallel to it?
  3. Implement an ALiBi bias matrix for 6 tokens and slope 12\tfrac12: entry (i,j)(i, j) is −12(i−j)-\tfrac12 (i - j) for j≤ij \le i and −∞-\infty otherwise. Add it to a matrix of zeros and apply softmax by rows. How does attention fall off with distance?

Hint for 3: with equal content scores, the weights in each row decay by a factor of e−1/2≈0.61e^{-1/2} \approx 0.61 per step back.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A GPT-2-style model with a learned positional table of 1,024 rows receives a 1,500-token input. What happens?

  2. With RoPE, a query at position 105 and a key at position 102 give the same score as the same query and key at positions 5 and 2. Why?

  3. You want a RoPE model trained on 4,096 tokens to handle 32,768. Position interpolation does what?

  4. In ALiBi, head A has slope 1/2 and head B has slope 1/256. Which statement is right?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated Transformer

Jay Alammar · Beginner · Free

The famous picture-by-picture walk through the Transformer architecture.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Tutorial

The Annotated Transformer

Harvard NLP · Advanced · Free

The original Transformer paper, line by line, with working PyTorch code beside each paragraph.

Paper

Attention Is All You Need

Vaswani et al. · 2017 · Advanced · Free

Introduced the Transformer, the architecture behind every modern LLM.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/positional-encoding.md