Search

Search papers and lessons

Positional Encoding

Level 3 · 9 min read

Positional encoding adds a position-dependent vector to each token embedding, so a model that sees all tokens at once can still tell which word came first.

On this page

  • Colour = topic mix
  • Architectures
  • Language & LLMs
  • Representation learning
  • Linear algebra
  • Sign in to see your progress

TL;DR

A transformer reads all tokens in parallel, so on its own it cannot tell "dog bites man" from "man bites dog" beyond the words themselves. Positional encoding fixes this by adding a vector that depends only on each token's position to that token's embedding. Now the same word at two positions gives two different inputs, and the model can use order.

Where you'll see it: the input layer of every transformer language model, and the vision transformers that split an image into patches and need to know where each patch sits.

Intuition

Numbering the seats

Picture a long table where guests are seated. Every guest is described by their name, which is their embedding. If you only know the names, you know who came, but not who sat next to whom. Positional encoding gives each seat a label, and each guest carries the label of their seat. Two guests with the same name in different seats now look different to anyone reading the table.

Why not simply write the position as a number, 1, 2, 3, and so on? Because a raw counter has a scale problem. Position 500 would have a value a hundred times larger than position 5, and a network trained on short sentences would see values it never met. Good encodings stay bounded and vary smoothly, so nearby positions look alike and distant ones look different.

Clocks of different speeds

The standard solution uses sine and cosine waves. Each pair of dimensions acts like a clock hand. Fast hands change a lot between neighbouring positions and tell apart nearby tokens. Slow hands change little across a sentence and tell apart the rough region of a long document. Together they give a unique fingerprint for each position, and the fingerprint of position p+kp + k can be built from the fingerprint of position pp in a simple way.

0246810−1−0.500.51positionencoding value
  • fast sin, dim 0
  • fast cos, dim 1
  • slow sin, dim 2
The fast pair changes by a large amount between neighbouring positions. The slow sine barely moves over this range, so it separates far-apart regions instead.

Why addition, not concatenation

The encoding is added to the embedding, not appended to it. Addition keeps the model width fixed, and the attention layers can still separate the two signals because they are learned in different directions of the same space. The cost is that word identity and position share the same dimensions, which is a tradeoff the model learns to live with.

The math

Definition: Sinusoidal positional encoding

For a token at position pp, with p=0,1,2,…p = 0, 1, 2, \dots, and an embedding of even length dd, the positional encoding PE(p)∈Rd\mathbf{PE}(p) \in \mathbb{R}^d has entries

PE(p, 2i)=sin⁡ ⁣(p100002i/d),PE(p, 2i+1)=cos⁡ ⁣(p100002i/d)\mathrm{PE}_{(p,\,2i)} = \sin\!\left(\frac{p}{10000^{2i/d}}\right), \qquad \mathrm{PE}_{(p,\,2i+1)} = \cos\!\left(\frac{p}{10000^{2i/d}}\right)

for i=0,1,…,d/2−1i = 0, 1, \dots, d/2 - 1. Each pair (2i,2i+1)(2i, 2i+1) is one clock with its own frequency ωi=1/100002i/d\omega_i = 1 / 10000^{2i/d}. The model input for the token is xp+PE(p)\mathbf{x}_p + \mathbf{PE}(p), where xp\mathbf{x}_p is the token's word embedding.

The frequencies ωi\omega_i fall geometrically from 11 at i=0i = 0 towards 1/100001/10000 at the largest ii. So the encoding covers wavelengths from about 2π2\pi positions up to about 20000π20000\pi positions.

A shift is a rotation

The key property comes from a trigonometric identity. For each clock, sin⁡(a)sin⁡(b)+cos⁡(a)cos⁡(b)=cos⁡(a−b)\sin(a)\sin(b) + \cos(a)\cos(b) = \cos(a - b). Applying it to every pair gives

PE(p)⋅PE(p+k)=∑i=0d/2−1cos⁡ ⁣(k ωi).\mathbf{PE}(p) \cdot \mathbf{PE}(p + k) = \sum_{i=0}^{d/2 - 1} \cos\!\left(k \, \omega_i\right).

The right side depends only on the offset kk, not on the absolute position pp. This is why the encoding can express "three tokens to the left" in a way the attention mechanism can use, since attention scores are dot products between queries and keys.

Learned encodings

Instead of a fixed formula, one can learn a table of PP vectors of length dd, one per position up to a maximum length PP. Many models trained with BERT-style or GPT-style pretraining use this. Learned tables fit the training data well, but they have no value for positions beyond PP, and nothing forces nearby positions to look alike. The sinusoidal form is defined at every position and varies smoothly, but in practice models trained on it still tend to degrade well beyond their training length.

Worked examples

Example
Encoding positions 1 and 2 with d = 4

Use d=4d = 4, so there are two clocks. For i=0i = 0 the frequency is 1/100000=11/10000^0 = 1. For i=1i = 1 the frequency is 1/100002/4=1/100=0.011/10000^{2/4} = 1/100 = 0.01.

  1. Position p=1p = 1:
    • PE(1,0)=sin⁡(1)≈0.8415\mathrm{PE}_{(1,0)} = \sin(1) \approx 0.8415
    • PE(1,1)=cos⁡(1)≈0.5403\mathrm{PE}_{(1,1)} = \cos(1) \approx 0.5403
    • PE(1,2)=sin⁡(0.01)≈0.0100\mathrm{PE}_{(1,2)} = \sin(0.01) \approx 0.0100
    • PE(1,3)=cos⁡(0.01)≈1.0000\mathrm{PE}_{(1,3)} = \cos(0.01) \approx 1.0000
  2. Position p=2p = 2:
    • PE(2,0)=sin⁡(2)≈0.9093\mathrm{PE}_{(2,0)} = \sin(2) \approx 0.9093
    • PE(2,1)=cos⁡(2)≈−0.4161\mathrm{PE}_{(2,1)} = \cos(2) \approx -0.4161
    • PE(2,2)=sin⁡(0.02)≈0.0200\mathrm{PE}_{(2,2)} = \sin(0.02) \approx 0.0200
    • PE(2,3)=cos⁡(0.02)≈0.9998\mathrm{PE}_{(2,3)} = \cos(0.02) \approx 0.9998
  3. The fast clock has moved a lot between positions 1 and 2: its first entry went from 0.84 to 0.91 and its second from 0.54 to minus 0.42. The slow clock barely moved. Two tokens with the same word, one at position 1 and one at position 2, now have different inputs.
  4. Interpretation: the encoding gives every position a distinct fingerprint, with the fast pair separating neighbours and the slow pair giving a coarse sense of distance. A model that adds these to the embeddings can use the difference between positions 1 and 2.
Example
Relative offsets through dot products

Use the same d=4d = 4 encoding and check the shift property numerically.

  1. Dot product of positions 1 and 2, from the values above: 0.8415⋅0.9093+0.5403⋅(−0.4161)+0.0100⋅0.0200+1.0000⋅0.9998≈0.7651−0.2248+0.0002+0.9998≈1.54030.8415 \cdot 0.9093 + 0.5403 \cdot (-0.4161) + 0.0100 \cdot 0.0200 + 1.0000 \cdot 0.9998 \approx 0.7651 - 0.2248 + 0.0002 + 0.9998 \approx 1.5403.
  2. Predicted by the formula with k=1k = 1: cos⁡(1)+cos⁡(0.01)≈0.5403+1.0000=1.5403\cos(1) + \cos(0.01) \approx 0.5403 + 1.0000 = 1.5403. The two results agree.
  3. Now compare positions 1 and 3 (offset 2) with positions 5 and 7 (also offset 2). The formula gives cos⁡(2)+cos⁡(0.02)≈−0.4161+0.9998=0.5837\cos(2) + \cos(0.02) \approx -0.4161 + 0.9998 = 0.5837 in both cases, even though the absolute positions differ.
  4. Interpretation: an attention head that scores pairs by dot product will see the same relative relationship whenever the gap is 2, wherever in the sequence the pair sits. That is the property that lets attention reason about "the word two places back", and it is one reason sinusoidal encodings generalise to longer sequences.

Tradeoffs and failure modes

SituationProblemBetter choice
Sequences longer than trainingLearned table has no entries past its maximum lengthA relative scheme such as rotary embeddings (sinusoidal is defined at any position but often degrades too)
Need precise relative distancesAbsolute additive codes mix position with contentRelative position biases or [[rotary-position-embedding
Short fixed-length inputs with plenty of dataLearned encodings fit well and are simpleLearned position embeddings
Position matters only locallyGlobal encodings add noise to local patternsConvolutions or local attention windows
Images split into patchesA raw 1D index loses the grid layout2D position encodings, or learned embeddings per row and column

Failure modes to watch for: a model that performs well up to its training length and then collapses past it is usually a sign of a learned table with no extrapolation. A model that ignores order entirely may have had its positional signal drowned out, for example by an embedding scale much larger than the encoding scale. Scaling the embedding by d\sqrt{d} before adding the encoding, as in the original transformer, is one common guard.

History

Early sequence models such as the recurrent network did not need an explicit position signal, because they read tokens one at a time and their state carried order implicitly. Convolutional sequence models encoded position through their filter structure.

When Vaswani and colleagues introduced the transformer in 2017, they removed recurrence to allow parallel training. To restore order they added sinusoidal encodings to the input embeddings, and they reported that learned position embeddings performed about the same on their tasks. They hypothesised that the sinusoidal form might extrapolate to longer sequences than seen in training.

Later models often used learned position embeddings. BERT, published in 2018, is a well-known example. Work on relative encodings followed, including schemes that modify the attention scores directly, and rotary embeddings, proposed by Su and colleagues in 2021, which encode relative position as a rotation of query and key vectors. Positional encoding is now one of the most actively varied parts of transformer design, even though the basic need for order is unchanged.

Check yourself

QuestionA transformer receives the tokens of 'cat chases dog' with no positional encoding. Why can it not tell this from 'dog chases cat' using the attention computation alone?Show answer

Attention computes weighted sums over all token vectors and does not, by itself, use the order in which the vectors are arranged. Permuting the input tokens permutes the outputs in the same way, so the model's view of the set of words is identical in both orders. Positional encoding breaks that symmetry by making each token's vector depend on its position.

QuestionUsing d = 4, compute the sinusoidal encoding for position 3, to four decimal places. Use sin⁡(3)≈0.1411\sin(3) \approx 0.1411, cos⁡(3)≈−0.9900\cos(3) \approx -0.9900, and sin⁡(0.03)≈0.0300\sin(0.03) \approx 0.0300, cos⁡(0.03)≈0.9996\cos(0.03) \approx 0.9996.Show answer

The two clocks have frequencies 1 and 0.01. The entries are sin⁡(3)≈0.1411\sin(3) \approx 0.1411, cos⁡(3)≈−0.9900\cos(3) \approx -0.9900, sin⁡(0.03)≈0.0300\sin(0.03) \approx 0.0300, and cos⁡(0.03)≈0.9996\cos(0.03) \approx 0.9996. So PE(3)≈(0.1411,−0.9900,0.0300,0.9996)\mathrm{PE}(3) \approx (0.1411, -0.9900, 0.0300, 0.9996).

QuestionWhy does the sinusoidal encoding let the dot product between positions p and p+k depend only on k?Show answer

Each clock contributes sin⁡(a)sin⁡(b)+cos⁡(a)cos⁡(b)=cos⁡(a−b)\sin(a)\sin(b) + \cos(a)\cos(b) = \cos(a - b) to the dot product. With a=p ωia = p\,\omega_i and b=(p+k) ωib = (p+k)\,\omega_i, the difference is k ωik\,\omega_i, which does not involve pp. Summing over the clocks gives a value that depends only on the offset kk. This makes relative relationships visible to attention wherever they occur.

QuestionYou trained a model with learned position embeddings up to length 512. At inference you feed it documents of 2000 tokens and the output quality collapses after token 512. What is the cause, and what would you try first?Show answer

The learned table has no vectors for positions above 512, so those positions receive either undefined or clipped inputs, and the model never learned what to do with them. The first fix to try is a relative or extrapolating scheme, such as a rotary encoding, which is defined at any position without new parameters (extrapolation is still not guaranteed, so test it). If the model must keep learned embeddings, fine-tuning on longer sequences is the other common route, with a check on quality across lengths.

Sources