Positional Encoding: Where Is Each Word?

Attention looks at all the words at once, so on its own it cannot tell "dog bites man" from "man bites dog". Adding a position signal to each word fixes that.

AI · beginner · 8 min · 20 steps · free

What you'll learn

positional.py

import math

# Attention alone ignores word order: "dog bites man" and "man bites dog" would look the same.
words = ["dog", "bites", "man"]
meaning = {"dog": [1.0, 0.0], "bites": [0.0, 1.0], "man": [0.5, 0.5]}

# So each word's vector gets a position signal added: wave values that depend on where it sits.
inputs = []
for pos, word in enumerate(words):
    signal = [round(math.sin(pos), 2), round(math.cos(pos), 2)]
    vec = meaning[word]
    inputs.append([round(vec[0] + signal[0], 2), round(vec[1] + signal[1], 2)])
print(inputs)

# The same word in another position now gets different numbers.
dog_at_end = [round(1.0 + math.sin(2), 2), round(0.0 + math.cos(2), 2)]
print("dog at the start:", inputs[0], "dog at the end:", dog_at_end)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. A three-word sentence.
  3. Each word's meaning vector, as in the embeddings lesson.
  4. The model's real input: one vector per word, meaning plus position.
  5. Go through the words with their positions: "dog" is at position 0.
  6. The position signal for position 0: sin(0) = 0, cos(0) = 1.
  7. dog's meaning: [1, 0].
  8. Add them: [1, 0] + [0, 1] = [1, 1].
  9. pos changes from 0 to 1. word changes from 'dog' to 'bites'.
  10. Position 1: sin(1) = 0.84, cos(1) = 0.54.
  11. vec now points to a different list: [0, 1].
  12. "bites" becomes [0, 1] + [0.84, 0.54] = [0.84, 1.54].
  13. pos changes from 1 to 2. word changes from 'bites' to 'man'.
  14. Position 2: sin(2) = 0.91, cos(2) = −0.42.
  15. vec now points to a different list: [0.5, 0.5].
  16. "man" becomes [1.41, 0.08].
  17. Python moves to the next item of the loop: for pos, word in enumerate(words).
  18. It prints [[1.0, 1.0], [0.84, 1.54], [1.41, 0.08]].
  19. Now put "dog" at position 2 instead.
  20. Same word, different numbers: [1, 1] at the start and [1.91, −0.42] at the end. Now "dog bites man" and "man bites dog" look different to the model. Real models use hundreds of waves at different speeds, or learn position vectors.

Common mistakes

Best practices

Key takeaways

Check yourself

Without positional encoding, how would a transformer see "dog bites man" vs "man bites dog"?

Answer: The same. Both contain the same three vectors; attention alone does not care about order.

What does the position signal depend on?

Answer: Only the position. sin(pos) and cos(pos) use the position alone; the word's meaning is added separately.

·

More in Text as Numbers