# 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.

AI and LLM interview question Q047, Transformer architecture. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-positional-encoding

## Say it in 30 seconds

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.

## Say it in 2 minutes

A transformer reads every token in the input at the same time. That is a big part of why it trains faster than the older models, because nothing waits for the word before it. But it also means the 2017 design has no built-in sense of order. Without a fix, a sentence and its words in a new order look the same to the attention step, which sees only the set of words.

So we add positional encoding. Each token's vector gets a second vector that stands for its slot, first, second, tenth, and the two are added together. The 2017 Transformer paper used sine and cosine waves of different speeds, so each slot gets its own pattern. The authors also tried learned position vectors and found nearly identical results.

The hard case is a contract. The buyer pays the supplier and the supplier pays the buyer hold the same words, but they put the duty to pay on opposite parties. A word-count search misses that. Position tells the model which party comes first and who is paying.

Later designs changed how position is used. RoPE, from 2021, rotates parts of the attention inputs so the score depends on the gap between two tokens. For an interview, the basic idea is simple, the variants are design choices, and I would test any choice on long documents before trusting it.

## 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.

- **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. **Make the word's vector:** Each token becomes a list of numbers, its embedding, which training sets.
2. **Make the slot's vector:** Compute the sine and cosine values for its position with the 2017 formula.
3. **Add the two:** Add them one number at a time, so the two lists can be summed.
4. **Pass the sum on:** Attention then sees each word together with where it sits.

*Diagram, How position reaches the model: 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.*
1. The word's own vector goes into the sum.
2. Its slot number becomes a position vector, added in.
3. The sum, one vector per word, goes into the model.
4. Attention now reads each word knowing where it sits.

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:

```text
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." Better: In 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." Better: It 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." Better: Even 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?

A. Each question finds the clause that matches its own parties.
B. Both questions return the same clause at the same score.
C. The top result has a score of 0.91 and the second has 0.84.
D. The search index holds 40,000 contracts and is updated nightly.

**Answer:** B. If swapping the parties gives the same score, the model is reading which words appear, not their order. Position signals exist to stop exactly that.

**Quick check:** Why does a transformer need positional encoding?

A. Attention reads all tokens together, so without positions it loses the word order.
B. It makes the vocabulary bigger, so rare words fit.
C. It turns the output back into readable text.
D. It skips the last layer to save training time.

**Answer:** A. Attention looks at every token together and has no built-in sense of order. Position is the signal that puts that order back. The other three are not what it does.

## Can you answer these from memory?

**Flash cards**

- **What is positional encoding?** A position signal added to each token so the model knows word order.
- **Why is it needed?** Transformers read all tokens at once, so the 2017 design needs it to keep word order.
- **Where is it added?** In the 2017 design, to each token's embedding, before attention runs. RoPE applies it inside attention.
- **What did the 2017 paper use?** Sine and cosine waves of different speeds. Learned vectors did about as well.
- **What is RoPE?** Rotary position embedding. It makes attention depend on how far apart two tokens are.
- **How do you test word order?** Swap the parties or steps in test pairs, then check the answer changes.

## Likely follow-up questions

- Q042 Why did transformers replace RNNs and LSTMs? https://designervenkat.online/interview/ai/why-transformers-replaced-rnns-and-lstms
- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
- Q044 What are queries, keys and values? https://designervenkat.online/interview/ai/what-are-queries-keys-and-values
- Q046 What is multi-head attention? https://designervenkat.online/interview/ai/what-is-multi-head-attention
- Q048 Sinusoidal vs learned vs rotary (RoPE) positions? https://designervenkat.online/interview/ai/sinusoidal-vs-learned-vs-rotary-rope-positions
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
