esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

What Is Positional Encoding?

What positional encoding is, why transformers need word order, and how sine waves and rotary codes add it, explained simply for your AI interview.

In short

Positional encoding is extra information that tells a transformer (the neural network design from the 2017 paper) where each token sits in the input. Transformers read all tokens at once, so the 2017 design needs it to see word order.

11 min readIntermediateVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

I'd say positional encoding is the signal that tells a transformer where each word sits. The model reads all the words at once, so in the 2017 design, without it, word order is lost, and a sentence can be read as if its parties were swapped. We add a position vector to each word's vector before attention. The 2017 paper used sine and cosine waves. Later methods, such as RoPE, build the position into attention itself.

What is positional encoding, in plain words?

A transformer reads all the words of its input at the same time. That is a big part of why it trains faster than older models. It also means the 2017 design has no built-in sense of order, so the order has to be handed back to it.

Positional encoding is that handed-back order. For each word, the model gets a short list of numbers that marks its slot: first, second, tenth. The model adds this list to the word's own list before the attention step.

Think of a new hire handed a pile of contract pages with the page numbers torn off. Every clause is there, but nobody knows which comes first. Page numbers in the margin fix that. Positional encoding is the page number for each word. Without it, a model reading a loan agreement can mix up who owes whom.

Key words

Token
A small piece of text the model works on, such as a word or part of a word.
Embedding
The list of numbers that stands for one token. Training sets its values.
Position
Where a token sits in the input, counted from the start.
Attention
The step where each token looks at the others to decide which ones matter for it.

Why does a transformer need it?

Older models such as recurrent networks read one word after another, so the order came with the reading. The 2017 Transformer paper dropped that step. It notes that the sequential design blocks parallel work within one training example, and that the Transformer allows significantly more parallelization.

  • “Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.”

    Vaswani and colleagues, 2017

So the position has to be added to the input, because attention alone does not know which slot a word occupies. Reorder the words and the model is given the same set of words, so it can mix up who does what.

  • Without it

    Same words, same read

    Shuffle the words and the model sees the same bag, so it cannot tell who acts.

  • With it

    Each slot is marked

    The model knows the first word from the last, so it can tell who pays whom.

A made-up but realistic case: a legal team searches 40,000 supplier contracts for late-payment terms. Two clauses hold the same words in a new order. "The buyer pays the supplier within 30 days of invoice." and "The supplier pays the buyer within 30 days of invoice." A search that ignores order scores both clauses the same for a question about either party. A model that knows order can tell which party owes the fee.

How is the position added to each word?

The 2017 design builds the position list from sine and cosine waves. Each slot gets its own pattern, and waves of different speeds keep the patterns apart. The formula needs no training.

  1. 1

    Make the word's vector

    Each token becomes a list of numbers, its embedding, which training sets.

  2. 2

    Make the slot's vector

    Compute the sine and cosine values for its position with the 2017 formula.

  3. 3

    Add the two

    Add them one number at a time, so the two lists can be summed.

  4. 4

    Pass the sum on

    Attention then sees each word together with where it sits.

How position reaches the model

Two lists per word

The word: buyer

its meaning as numbers

Its slot: 0

its place in the sentence

Added together

one vector per word

Transformer

attention now sees order

Order-aware reading

knows who comes first

  1. 1The word's own vector goes into the sum.
  2. 2Its slot number becomes a position vector, added in.
  3. 3The sum, one vector per word, goes into the model.
  4. 4Attention now reads each word knowing where it sits.
Each word's vector is added to the position vector for its slot. The sum goes into the model, so attention can tell the first word from the last. In the 2017 design the position vector comes from a formula, not from training.

Here is the idea in a short program. The word vectors are made-up numbers, not from a real model, but the positions use the real formula.

Python
import math

def position(pos, d=4):
    # Sine and cosine at different speeds, as in the 2017 Transformer paper.
    vec = []
    for i in range(d // 2):
        angle = pos / (10000 ** (2 * i / d))
        vec += [round(math.sin(angle), 2), round(math.cos(angle), 2)]
    return vec

# Made-up word vectors. A real model learns these during training.
WORD = {"buyer": [1.0, 0.0, 0.5, 0.0], "supplier": [0.0, 1.0, 0.0, 0.5], "pays": [0.5, 0.5, 0.5, 0.5]}

def bag_of_words(words):
    # Adding word vectors together throws the order away.
    return [round(sum(WORD[w][k] for w in words), 2) for k in range(4)]

def with_position(words):
    # Each word's vector gets the position of its slot added to it.
    return [[round(WORD[w][k] + position(pos)[k], 2) for k in range(4)] for pos, w in enumerate(words)]

a = ["buyer", "pays", "supplier"]
b = ["supplier", "pays", "buyer"]
print("same bag of words:", bag_of_words(a) == bag_of_words(b))
print("buyer in A, position 0:", with_position(a)[0])
print("buyer in B, position 2:", with_position(b)[2])

Output

same bag of words: True
buyer in A, position 0: [1.0, 1.0, 0.5, 1.0]
buyer in B, position 2: [1.91, -0.42, 0.52, 1.0]

The first line says the two clauses have the same bag of words. The last two lines show that the same word, buyer, gets a different vector when its slot changes. That difference is what lets the model tell the clauses apart.

How did later designs change it?

The 2017 authors also tested learned position vectors, and the results were nearly the same. They chose sine and cosine partly because it may help with inputs longer than those seen in training.

  • “We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.”

    Vaswani and colleagues, 2017

  • “Specifically, the proposed RoPE encodes the absolute position with a rotation matrix and meanwhile incorporates the explicit relative position dependency in self-attention formulation.”

    Su and colleagues, RoFormer, 2021

  • Fixed waves

    Added to the input

    A formula with no table to learn. It was the 2017 choice.

  • Learned

    A table learned in training

    Worked nearly as well in the 2017 test. The paper chose sine and cosine because they may handle inputs longer than training.

  • Rotary (RoPE)

    Built into attention

    Rotates parts of the attention inputs, so the score depends on the gap between two words.

For an interview, say three things: positions are required, the method is a design choice, and you would test that choice on long documents before picking one.

How would you check that a model really reads word order?

Build test pairs where only the order changes: swap the buyer and the supplier, or move a condition after its outcome. Then check that the answers change the right way.

If a model gives the same score to both halves of each pair, it may be matching words and ignoring their order. Run a simple word-count baseline on the same pairs as a comparison.

Tip

Use real clauses, long ones too. The method you pick can behave differently as inputs grow, so one short test proves little.

What does the interviewer want to hear?

A strong answer covers

  • A plain definition: a signal that tells the model where each token sits.
  • Why it's needed: transformers read all tokens at once, so order must be added.
  • How it's added: a position vector is summed with each token's embedding.
  • The 2017 sine and cosine method, and the learned alternative.
  • Why it matters: the same words in a new order can change who owes whom.
  • Later methods such as RoPE, and a test that swaps order to check the model.

Common traps

  • Trap"The model reads words in order, so it already knows where they are."

    BetterIn the 2017 design, transformers read all tokens at once, so order has to be added as a signal.

  • Trap"Position is just a number stamped on the end of each word."

    BetterIt is a vector added to the word's own vector, so it changes what the model computes.

  • Trap"Positional encoding only matters for long text."

    BetterEven a short clause can put the late fee on the wrong party. Order matters at any length.

Can you spot the missing order?

Spot the problem

Your contract model gets two opposite questions and returns these results. Which result shows it ignores word order?

Quick check

Why does a transformer need positional encoding?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q042Why did transformers replace RNNs and LSTMs?11 min
  2. Q043What is self-attention?11 min
  3. Q044What are queries, keys and values?11 min
  4. Q046What is multi-head attention?10 min
  5. Q048Sinusoidal vs learned vs rotary (RoPE) positions?13 min
  6. Q050What is causal (masked) attention?10 min

Last updated on 26 November 2026

Building an AI feature that reads long contracts or documents?

I design and build AI products and agents, including the screens and the system behind them. Book a short call and tell me what your documents look like and what the assistant must do with them.