TRANSFORMERS / ORDER / FIELD GUIDEtoken + position → attention
Back to field guides

FIELD GUIDE 13

Positional Encoding Explained:
How Transformers Know Order

Same words, different order, different meaning.

Short answerPositional encoding is the information a transformer adds so it knows the order of the tokens it's reading.
Row of empty theater seats, each lit by a soft warm spotlight in sequence
Every token gets a seat. Positional encoding is how the model knows which seat.
Updated November 11, 2026Beginner-first / Formula + worked example

00 Short answer

The quick
version.

Short answer: positional encoding is the information a transformer adds so it knows the order of the tokens it's reading. Attention on its own treats a sentence like a bag of words: "dog bites man" and "man bites dog" would look the same. Positional encoding fixes that, either by adding a position-specific vector to each token's embedding (the original sine-and-cosine method, or learned position vectors) or by building position directly into the attention calculation (relative methods such as RoPE and ALiBi, used in many modern LLMs).

01 Why it matters

\1

Older sequence models such as RNNs read text one token after another, so order came for free. A transformer reads all tokens in parallel, and its core operation, attention, compares every token with every other token using dot products. Nothing in that calculation says which token came first.

Formally, self-attention without position information is permutation-equivariant: shuffle the input tokens, and you get the same outputs, just shuffled the same way. For language that's a problem. "Not good, actually great" and "Great, actually not good" contain the same tokens.

So before (or during) attention, the model needs a signal for "this token is at position 0, this one at position 1…". That signal is the positional encoding. You can see where it enters in the how a transformer works lesson, at the step where tokens become "vectors + position".

02 The original

\1

The 2017 paper Attention Is All You Need used a fixed pattern of sine and cosine waves. For a token at position pos, and dimension index i of a model with embedding size d:

PE(pos,2i)=sin(pos100002i/d)PE(pos,2i+1)=cos(pos100002i/d)

In words: even dimensions get a sine, odd dimensions get a cosine, and each pair of dimensions uses a different wavelength. The first pairs oscillate quickly, and later pairs oscillate more and more slowly, with wavelengths from 2π up to about 10,000 × 2π. The resulting vector is added to the token's embedding before the first layer.

Worked example (embedding size 4)

With d = 4 there are two sine/cosine pairs. The first pair uses the angle pos ÷ 1; the second uses pos ÷ 100 (because 10000^(2/4) = 100).

Position sin(pos) cos(pos) sin(pos/100) cos(pos/100)
0 0.000 1.000 0.000 1.000
1 0.841 0.540 0.010 1.000
2 0.909 −0.416 0.020 1.000
3 0.141 −0.990 0.030 1.000

How to read it: the first two columns change fast and tell neighboring positions apart. The last two change slowly and carry "roughly where in the text" information. Together, every position gets a distinct fingerprint, like the hands of a clock moving at different speeds. Real models use hundreds or thousands of dimensions, so there are many more "hands".

Why sines and cosines?

  • Bounded values. Everything stays between −1 and 1, so position doesn't swamp the word meaning in the embedding.
  • No training needed and defined for any position, including ones longer than seen in training (in principle; in practice, models still struggle well beyond their training length).
  • Relative offsets are easy to express. For each frequency, the encoding of position pos + k is a fixed rotation of the encoding at pos. The original authors chose sinusoids because they hypothesized this would make it easy for the model to attend by relative position.

Sinusoidal positional encoding in Python

import numpy as np

def sinusoidal_positions(seq_len, d_model):
    pos = np.arange(seq_len)[:, None]                 # (seq_len, 1)
    i = np.arange(0, d_model, 2)[None, :]             # even dims
    angles = pos / np.power(10000, i / d_model)       # (seq_len, d_model/2)
    pe = np.zeros((seq_len, d_model))
    pe[:, 0::2] = np.sin(angles)
    pe[:, 1::2] = np.cos(angles)
    return pe

print(sinusoidal_positions(4, 4).round(3))   # matches the table above
# x = token_embeddings + sinusoidal_positions(seq_len, d_model)

03 Another method

\1

The simplest alternative: give each position its own trainable vector, exactly like a token embedding, and add it to the token embedding. BERT and GPT-2 work this way.

  • Pro: the model learns whatever position signal is most useful.
  • Con: there's a hard limit. A model trained with a table of 512 positions (BERT) or 1,024 positions (GPT-2) has no vector at all for position 2,000. That's one reason newer long-context models moved to relative methods.

04 Modern method

\1

For language, how far apart two tokens are often matters more than their absolute positions. "The word two tokens back" means the same thing at position 10 and position 10,000. Relative methods put distance into the attention step itself:

  • Relative position representations (Shaw et al., 2018) add learned vectors for clipped distances between tokens into the attention computation.
  • T5-style relative bias adds a learned scalar to each attention score, based on the (bucketed) distance between query and key.

05 Modern method

\1

RoPE, introduced in the RoFormer paper (Su et al., 2021), is the most common choice in today's open LLMs, including the LLaMA family. Instead of adding a vector to the embeddings, it rotates the query and key vectors inside every attention layer:

  1. Split each query and key vector into pairs of numbers, so each pair is a point in 2D.
  2. Rotate each pair by an angle equal to position × θ, where each pair has its own frequency θ (using the same kind of wavelength schedule as the sinusoidal method).
  3. Compute attention as usual.

The neat part: when you take the dot product of a query rotated by position m and a key rotated by position n, the result depends only on the difference m − n. Absolute positions go in; relative distance comes out. Values (V) are not rotated, only queries and keys.

RoPE works well with the KV cache: each key is rotated once, for its own position, and stored. It never has to be rotated again as new tokens arrive.

06 Connect it

\1

ALiBi (Press et al., 2021, Train Short, Test Long) drops position vectors entirely. It subtracts a penalty from each attention score that grows linearly with the distance between the query and the key, with a different slope for each head. Nearby tokens get a small penalty, far tokens a larger one. The paper showed this let models handle inputs longer than their training length better than sinusoidal encoding did. BLOOM and MPT are examples of models that used ALiBi.

07 Compare

\1

Method Where position enters Absolute or relative Trainable? Examples Notes
Sinusoidal Added to embeddings Absolute (relative-friendly) No Original transformer (2017) Defined for any length, but quality still drops far past training length
Learned absolute Added to embeddings Absolute Yes BERT, GPT-2 Hard maximum length
Relative bias Attention scores Relative Yes T5 Distances bucketed or clipped
RoPE Rotates Q and K Relative (via rotation) No (fixed frequencies) LLaMA family, many open LLMs Plays well with KV caching; can be rescaled for longer context
ALiBi Linear penalty on attention scores Relative No (fixed slopes) BLOOM, MPT Designed for length extrapolation

08 Scale up

\1

How a model encodes position is a big part of how long a context window it can handle. Models usually degrade on positions well beyond what they saw in training. To stretch a RoPE model to a longer context, researchers rescale the rotation angles, so long sequences map back into the range of angles the model already knows. Examples include position interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023), usually combined with some extra fine-tuning on longer texts.

Curiously, decoder-only models trained without any explicit positional encoding can still pick up some sense of order, because the causal mask means each token sees a different number of predecessors (Haviv et al., 2022). Explicit encodings still remain the standard choice.

Hands placing smooth river stones in a careful line along a sandy path at low sun
The same stones in a different order make a different path.

09 Watch out

\1

  • "Positional encoding is the token ID." No. The token ID says which word; the positional encoding says where it is. They're combined.
  • "Every transformer adds a position vector to the input." Not anymore. RoPE and ALiBi act inside attention and add nothing to the embeddings.
  • "Sinusoidal encoding lets a model handle any length." The formula is defined for any position, but a model's quality still falls off well beyond its training length.
  • "Position is handled once, at the start." With RoPE and ALiBi it's applied in every attention layer.

Want to see where this happens inside a layer? The transformer block lesson walks through attention, residuals, normalization and the feed-forward network in order.

FAQ Positional encoding / quick answers

Questions,
answered.

Short explanations with the limits left visible.

· informational guide

01 / answerWhat is positional encoding in simple terms?

It's the information a transformer adds so it knows the order of the tokens. Without it, attention would treat a sentence as an unordered bag of words.

02 / answerWhy do transformers need positional encoding?

Because attention compares all tokens in parallel, and its dot products don't depend on order. Shuffle the words and plain self-attention gives the same results, just shuffled. Positional encoding breaks that symmetry.

03 / answerWhat is the formula for sinusoidal positional encoding?

PE(pos, 2i) = sin(pos / 10000^(2i/d)) and PE(pos, 2i+1) = cos(pos / 10000^(2i/d)), where pos is the token position, i indexes dimension pairs and d is the embedding size. The vector is added to the token embedding.

04 / answerIs positional encoding learned or fixed?

Both exist. The original transformer used fixed sinusoids; BERT and GPT-2 learn a vector for each position; RoPE and ALiBi use fixed rules applied inside attention.

05 / answerWhat is the difference between positional encoding and positional embedding?

They're often used interchangeably. "Embedding" usually hints at a learned lookup table (one trainable vector per position); "encoding" often refers to a fixed formula like the sinusoidal one.

06 / answerWhat is RoPE?

Rotary positional embedding rotates pairs of numbers in each query and key vector by an angle proportional to the token's position. The attention score between two tokens then depends on their distance, and nothing is added to the embeddings.

07 / answerWhat is ALiBi?

Attention with Linear Biases subtracts a penalty from attention scores that grows with the distance between tokens, with a different slope per head. It uses no position vectors and was designed to help models handle longer inputs than they were trained on.

08 / answerWhy is positional encoding added and not concatenated?

Adding keeps the vector size the same and was enough in practice. Because embeddings are high-dimensional, the model can learn to use part of the space for position. Concatenating would also work but makes every layer bigger.

Sources Papers / official docs

Read the
sources.

↗keep exploring

More explainAI
field guides.