AI

Positional Encoding: How Transformers Know Word Order

Positional encoding explained: why transformers need it, the sinusoidal formula with a worked example, learned and relative positions, RoPE and ALiBi.

By OmniAI Editorial · Nov 22, 2026 · 10 min read

Positional encoding is the extra information a transformer model adds to each token so it knows where that token sits in a sentence. Attention by itself treats its input as an unordered set, so without positional encoding "dog bites man" and "man bites dog" would look identical. The original transformer added sine and cosine waves of different frequencies to each token's embedding; most modern language models instead use rotary positional embedding (RoPE), which rotates query and key vectors by an angle that depends on position.

This guide explains why positional encoding is necessary in transformers, walks through the sinusoidal positional encoding formula with real numbers, compares learned, relative, rotary and ALiBi approaches, shows how positional encoding in transformers affects context length, and lists common mistakes.

Why Is Positional Encoding Necessary in Transformers?

A transformer reads all tokens at once and lets each token look at every other token through self-attention. The attention score between two tokens depends only on their vectors, not on where they appear. Shuffle the words and, without extra information, each token would compute the same scores; the model would see a bag of words.

Older sequence models didn't have this problem. Recurrent networks read one token at a time, so order was built into the process. Transformers gave that up to process tokens in parallel, which is what makes them fast to train on GPUs. Positional encoding puts order back.

Our explainer on the attention mechanism covers how attention works; this article goes deep on the position part.

How Positional Encoding Works

There are two broad ways to give a model position information:

  1. Add position to the input. Each position gets a vector, and that vector is added to the token's embedding before the first layer. The original sinusoidal encoding and learned position embeddings work this way. This is called absolute positional encoding, because each position has its own fixed signal.
  2. Put position into attention. Instead of changing the input, the model changes how attention scores are computed so they depend on the distance between tokens. RoPE and ALiBi work this way, which gives the model a sense of relative position: "three tokens back" rather than "position 47."

The Sinusoidal Positional Encoding Formula

The original 2017 paper, "Attention Is All You Need," used fixed sine and cosine functions. For position pos and dimension index i in a model with embedding size d_model, the positional encoding formula is:

PE(pos, 2i)   = sin(pos / 10000^(2i / d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model))

Even dimensions use sine and odd dimensions use cosine, and each pair of dimensions uses a different frequency. The first pairs change quickly from one position to the next, like the second hand on a clock; later pairs change slowly, like the hour hand. Together they give every position a unique pattern, much like a binary counter where low bits flip often and high bits rarely.

The authors chose this form because, for any fixed offset k, the encoding of position pos + k can be written as a linear function of the encoding of pos, which they hypothesized would make it easy for the model to attend by relative position. It also needs no training and works for positions the model never saw.

Worked example with a tiny model

Take a toy model with d_model = 4, so two sine-cosine pairs. The first pair uses frequency 1; the second uses 1 / 10000^(2/4) = 1/100.

Positionsin(pos)cos(pos)sin(pos / 100)cos(pos / 100)
00.0001.0000.0001.000
10.8410.5400.0101.000
20.909−0.4160.0201.000
30.141−0.9900.0301.000

The first pair swings quickly and tells nearby positions apart; the second pair barely moves over these positions but keeps changing over hundreds of tokens. In a real model with d_model = 512, the wavelengths range from about 6.3 positions for the fastest pair to tens of thousands for the slowest, so every position in a long sequence gets a distinct signature.

Each token's input then becomes its word embedding plus this vector. The word "bank" at position 2 and at position 40 starts from the same word embedding but different positional signals.

A light panel with three ink wave lines of decreasing frequency from top to bottom, a vertical grey bar crossing all three, and an orange dot where the bar meets the top wave.
Each position reads off a unique mix of fast and slow waves.

A short code version

Here's the same idea in a few lines of PyTorch:

import math
import torch

def sinusoidal_positions(seq_len, d_model):
    pos = torch.arange(seq_len).unsqueeze(1)
    div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
    pe = torch.zeros(seq_len, d_model)
    pe[:, 0::2] = torch.sin(pos * div)
    pe[:, 1::2] = torch.cos(pos * div)
    return pe  # add to token embeddings of shape (seq_len, d_model)

Learned Positional Embeddings

Instead of a formula, a model can learn one vector per position during training, just as it learns word embeddings. BERT and GPT-2 used learned absolute position embeddings, with fixed maximum lengths of 512 and 1,024 positions respectively.

Learned embeddings are simple and work well within the trained length, but they have a hard limit: there's no vector for position 1,025 if the model only learned 1,024. That's one reason newer models moved to relative methods.

Positional encoding vs positional embedding: the terms are often used interchangeably. Strictly, "encoding" often refers to a fixed function like the sinusoidal one, while "embedding" refers to learned vectors, but many papers and libraries mix them.

Relative Positional Encoding

Language depends more on relative distance than absolute position: an adjective modifies the noun right after it, wherever that pair appears. Relative methods encode the offset between two tokens directly in attention.

Early versions added learned vectors for each distance to the attention computation. The T5 model used a simple learned bias per distance bucket, added to attention scores, with nearby distances getting their own buckets and far ones grouped together. These ideas led to the two approaches that dominate today.

Rotary Positional Embedding (RoPE)

Rotary positional embedding, introduced in the RoFormer paper (Su et al.), is the most widely used method in modern open language models, including the Llama, Qwen and Mistral families.

The idea: split each query and key vector into pairs of dimensions, treat each pair as a point on a 2D plane, and rotate it by an angle proportional to the token's position, with each pair rotating at a different frequency (the same spread of frequencies as the sinusoidal scheme). When attention takes the dot product of a query at position m and a key at position n, the rotations combine so the result depends only on the difference m − n. The paper's abstract describes it this way: RoPE "encodes the absolute position with a rotation matrix" and "incorporates the explicit relative position dependency in self-attention."

A one-pair example: rotating the 2D vector (1, 0) by one radian per position gives (1.000, 0.000) at position 0, (0.540, 0.841) at position 1, (−0.416, 0.909) at position 2 and (−0.990, 0.141) at position 3. Two tokens three positions apart always differ by the same rotation, wherever they are in the text.

Why it won:

  • Relative by construction, with no extra parameters.
  • Works with efficient attention kernels, because it only modifies queries and keys.
  • Decaying long-range dependence: the RoFormer authors list "decaying inter-token dependency with increasing relative distances" among its properties.
  • Extendable: its frequencies can be rescaled to stretch a model's context window.
A light circle with ink axes and three ink arrows from the center at increasing angles, the steepest one orange, beside a row of three small grey squares.
RoPE rotates each query and key by an angle that grows with position.

ALiBi: Attention With Linear Biases

ALiBi, from the paper "Train Short, Test Long" (Press et al.), takes an even simpler approach. It adds no positional vectors at all. Instead, as the abstract puts it, it "biases query-key attention scores with a penalty that is proportional to their distance," with a different slope for each attention head. Farther tokens get lower scores, so heads naturally focus on nearby context, and some heads with gentle slopes still look far back.

The paper showed a 1.3-billion-parameter model trained on 1,024-token inputs extrapolating to 2,048 tokens, matching the perplexity of a sinusoidal model trained on 2,048 tokens while training 11% faster and using 11% less memory. ALiBi was adopted by models such as BLOOM and MPT.

Positional Encoding Methods Compared

MethodWhere position entersAbsolute or relativeExtra parametersHandles longer inputs than trainedUsed in
SinusoidalAdded to input embeddingsAbsolute (with relative structure)NoneIn principle, but quality dropsOriginal transformer
Learned absoluteAdded to input embeddingsAbsoluteOne vector per positionNo: fixed maximum lengthBERT, GPT-2
Relative bias (T5-style)Added to attention scoresRelativeSmall learned tableSomewhatT5
RoPERotation of queries and keysRelativeNoneWith rescaling methodsLlama, Qwen, Mistral and most open LLMs
ALiBiLinear distance penalty on attention scoresRelativeNone (fixed slopes)Yes, designed for itBLOOM, MPT
No positional encoding (NoPE)None explicit; causal masking gives implicit orderImplicitNoneVariesResearch models

Positional Encoding and Context Length

Positional encoding is a big part of why context windows have limits. A model trained on 8,000-token sequences has only seen rotation angles or positions up to that length; at 32,000 tokens it meets angles it never learned, and quality collapses.

Several techniques stretch RoPE-based models beyond their training length:

  • Position interpolation: squeeze longer sequences into the trained range by scaling positions down, then fine-tune briefly.
  • NTK-aware and YaRN scaling: rescale RoPE's frequencies unevenly, keeping fast-rotating dimensions (which capture local order) nearly intact while stretching slow ones, usually with a short fine-tune.
  • Training on longer sequences in a later stage, which most long-context models do after initial pretraining.

When you load a model with a long context option, a setting like rope_scaling in its configuration is usually what's applying one of these methods. Our explainer on the transformer model covers the rest of the architecture these settings plug into.

Common Mistakes

  • Adding position to values instead of queries and keys with RoPE. RoPE is applied to queries and keys only; values carry content.
  • Mixing up positional encoding conventions. Some implementations interleave sine and cosine dimensions, others split them in halves; loading weights with the wrong layout breaks the model silently.
  • Exceeding the trained length without scaling. Output quality degrades quickly past the context the model was trained or extended for.
  • Assuming learned positions extrapolate. A learned table simply has no entry past its maximum length.
  • Forgetting position in non-text transformers. Vision transformers need position information for image patches too, usually learned or 2D variants.

FAQ

What is positional encoding in simple terms?

It's a signal added to each word's representation that tells a transformer where the word is in the sequence, so the model can tell "the cat chased the dog" from "the dog chased the cat."

Why do transformers need positional encoding?

Because self-attention compares tokens without regard to order. Without position information, a transformer would treat a sentence like an unordered bag of words.

What is rotary positional embedding?

RoPE encodes position by rotating the query and key vectors in attention by an angle proportional to each token's position. The dot product between two tokens then depends on how far apart they are, giving the model relative position information without extra parameters.

Is positional encoding learned or fixed?

Both exist. The original transformer used fixed sinusoidal functions, BERT and GPT-2 learned one vector per position, and modern LLMs mostly use RoPE, which is a fixed rotation scheme with no learned position parameters.

How does positional encoding affect context length?

Models only handle positions similar to those seen in training. Extending context usually requires rescaling the positional scheme, such as RoPE frequency scaling, plus some training on longer sequences.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog