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
- Builds on
- 24 concepts →
- Quiz
- 4 questions ↓
Read first
Self-Attention and Multi-Head AttentionThis leads to
The TransformerThe full path from zero — 24 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- 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:
- 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.
- 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.
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 to each token embedding. Its entries are sines and cosines at geometrically spaced frequencies. For position and dimension pair :
Here 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 positions; the last dimensions take up to positions.
Worked example. With , position 1, the first pair () has frequency , so the values are and . The second pair () has frequency , so and . The vector for position 1 starts .
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 and of are a fixed rotation of those at , the dot product depends only on . 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: . 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 , rotate pair by the angle , where (the same frequencies as the sinusoidal encoding). For one pair , rotation by angle is
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 and the key by , the angle between them changes by . So the score depends on the content of the two tokens and on their relative position , and not on where in the text the pair sits.
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:
The slope is fixed, not learned, and different for each head . With 8 heads the slopes are . Steep heads focus on nearby tokens; shallow ones can look far back. A token 10 positions away loses 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_embeddingsand anyrope_scalingsetting 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 , others pair the first half with the second half ; 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
- By hand, compute the first two numbers of the sinusoidal encoding at position 2 (, ) and check them against
sinusoidal(100, 64)[2, :2].- Plot
pe @ pe.Tas an image (plt.imshow). Why is it brightest along the diagonal, and why do the stripes run parallel to it?- Implement an ALiBi bias matrix for 6 tokens and slope : entry is for and 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 per step back.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Illustrated Transformer
The famous picture-by-picture walk through the Transformer architecture.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
The Annotated Transformer
The original Transformer paper, line by line, with working PyTorch code beside each paragraph.
RoFormer: Enhanced Transformer with Rotary Position Embedding
Rotary position embeddings, used by most modern LLMs.
Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation
ALiBi: instead of adding position vectors, penalise attention scores in proportion to distance.
Attention Is All You Need
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