Gradient LabStart the lesson

Lessons › Chapter 11: Transformers and LLMs

Positional encoding

“Dog bites man” is ordinary. “Man bites dog” is news. Same three words, different order, different meaning.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Order matters

“Move money from savings to current” is not the same request as “from current to savings”.

Concept

Order changes meaning

“Dog bites man” is ordinary. “Man bites dog” is news. Same three words, different order, different meaning.

Problem

Attention ignores order

Attention compares every token with every other token. Shuffle the words and each token still sees the same set of others. On its own, attention treats a sentence like a bag of words.

Key idea

Stamp each position

positional encoding adds a unique pattern for each position: waves of different speeds, read off at that spot. Position 1 gets one pattern, position 2 another. These are added to each word’s embedding.

Build

Now order is visible

“dog” in position 1 now looks different from “dog” in position 3, so the model can tell who bit whom. Newer models use variations (like rotating vectors by position), but the goal is the same.

Real life

In real life: following a recipe

“Whisk the eggs, then add the flour” is not the same as “add the flour, then whisk the eggs”. When an assistant reads instructions, code or directions, the order of the words carries as much meaning as the words themselves.

Quick check: Why do transformers need positional information?

Without position signals, shuffling words wouldn’t change what attention sees.

Pseudocode

attention on its own sees a bag of words: order is lost
"dog bites man" and "man bites dog" would look the same

position_signal(p) = waves of different speeds, read at position p
input(token) = embedding(word) + position_signal(position)

Key terms

positional encoding
Extra numbers added to each token that tell the model where it sits in the sentence.

In the news

Recent models and papers that build on this idea: