Watch the full visual breakdown on YouTube here
Transformer attention scores are computed purely from dot products of token vectors. When those vectors carry no notion of order, the model assigns identical attention patterns to sentences that are semantically different but contain the same words. Adding a raw integer position index seems like the obvious fix, yet it catastrophically distorts the geometry of attention.
Why Attention Is Blind to Word Order
Imagine a Transformer that receives the five‑word sentence "The cat sat on mat". The attention mechanism builds a similarity matrix by taking the dot product of every pair of token embeddings. Because the dot product is oblivious to where a token lives in the sequence, swapping "cat" and "mat" leaves the matrix unchanged – the model cannot tell who sat on whom.
The underlying reason is that attention treats the input as a bag of words: it only sees the set of vectors, not their positions. This is why a dedicated positional encoding is required.
The Bag‑of‑Words Trap Inside Attention
We assign each word a 2‑dimensional semantic embedding E:
- The →
[0, 1] - cat →
[2, 1] - sat →
[1, 2] - on →
[1, 1] - mat →
[2, 0]
These vectors are the exact numbers from the running example. The attention score between "cat" and "mat" is the dot product:
(2 × 2) + (1 × 0) = 4 So the raw semantic similarity is 4. Swapping the two words does not change this value, confirming that pure embeddings carry no order information.
Why Adding 0, 1, 2, 3, 4 Breaks Everything
A tempting fix is to add the integer position p directly to each component of E:
X_naive = E + p For "cat" at position p = 1 we add the vector [1, 1] and obtain X_naive = [3, 2]. For "mat" at p = 4 we add [4, 4] and get X_naive = [6, 4].
The new dot product becomes:
(3 × 6) + (2 × 4) = 18 + 8 = 26 The attention score inflates from 4 to 26, completely drowning out the semantic signal. Later tokens dominate because their position numbers are larger.
import numpy as np E = np.array([[0, 1], # The [2, 1], # cat [1, 2], # sat [1, 1], # on [2, 0]]) # mat p = np.arange(5).reshape(-1, 1) # [[0],[1],[2],[3],[4]] X_naive = E + p # naive addition score_naive = X_naive[1] @ X_naive[4] # cat vs mat print('Naive score:', score_naive) # → 26 Why Scaling Between 0 and 1 Still Fails
One might think that normalising the position index solves the explosion problem. By dividing each p by N‑1 (where N = 5), the scaled positions become [0.00, 0.25, 0.50, 0.75, 1.00].
For a five‑word sentence the second word ("cat") receives a positional offset of 0.25, but in a longer 101‑word sentence the same offset would be 0.01. The step size between adjacent tokens therefore depends on the total length, breaking the model’s ability to recognise a consistent “one‑step” distance.
0.25 vs 0.01 How Wave Pairs Lock Distance Without Exploding
The sinusoidal positional encoding solves both issues with a pair of bounded waves:
PE(p) = [ sin(p) , cos(p) ] Rounded to two decimals, the vectors for our five positions are:
- p = 0 →
[0.00, 1.00] - p = 1 →
[0.84, 0.54] - p = 2 →
[0.91, -0.42] - p = 3 →
[0.14, -0.99] - p = 4 →
[-0.76, -0.65]
All coordinates stay within [-1, 1], and every adjacent pair shares the same dot product:
PE(p)·PE(p+1) = sin(p)sin(p+1) + cos(p)cos(p+1) = cos(1) ≈ 0.54 Thus the similarity contributed by position alone is a constant 0.54, regardless of where the pair appears in the sentence.
p = np.arange(5) PE = np.stack([np.sin(p), np.cos(p)], axis=1) print('PE vectors (rounded):') print(np.round(PE, 2)) # Adjacent dot product (should be cos(1) ≈ 0.54) adj_dot = np.dot(PE[0], PE[1]) print('Adjacent positional dot product:', round(adj_dot, 2)) Testing Both Methods in Clean NumPy Code
Below is a self‑contained script that reproduces every number used in this article. Run it to see the raw, naive, and sinusoidal attention scores side by side.
import numpy as np # Semantic embeddings (E) E = np.array([[0, 1], # The [2, 1], # cat [1, 2], # sat [1, 1], # on [2, 0]]) # mat # Raw semantic similarity (cat vs mat) raw_score = E[1] @ E[4] # Naive integer addition p_int = np.arange(5).reshape(-1, 1) X_naive = E + p_int naive_score = X_naive[1] @ X_naive[4] # Normalised positions (0‑1 range) – shown for illustration only p_norm = p_int / (len(p_int) - 1) X_norm = E + p_norm norm_score = X_norm[1] @ X_norm[4] # Sinusoidal positional encoding p = np.arange(5) PE = np.stack([np.sin(p), np.cos(p)], axis=1) X_sin = E + PE sin_score = X_sin[1] @ X_sin[4] print('Raw semantic score :', raw_score) # 4 print('Naive integer score :', naive_score) # 26 print('Normalised integer score:', round(norm_score, 2)) print('Sinusoidal score :', round(sin_score, 2)) Running the script prints raw = 4, naive = 26, normalised = 8.0 and sinusoidal = 2.53. The constant 0.54 from the previous section is the similarity contributed by position alone, PE(p)·PE(p+1), not the full attention score of the combined vectors.
Resources & Full Series
- Free GitHub Starter Repo:
starter_code.py– a clean NumPy scaffold with built-in shape assertions so you can implement sinusoidal encodings yourself. - Free $0+ 1-Page PDF Cheat Sheet: Positional Encoding Visual Field Guide – summarizes the numerical walkthrough, why
0, 1, 2and[0, 1]fail, thePE(p)·PE(p+1) = 0.54unit-circle proof, and the NumPy snippet. - Complete $7 Interactive Colab Notebook + Solution Pack: Positional Encoding From Scratch Pack – includes the interactive Colab notebook, completed
solution.py, starter scaffold, and PDF cheat sheet.
Catch Up on Earlier Parts of the Series
- Part 1 – Self-Attention From Scratch: Written Deep-Dive on Dev.to
- Part 2 – Tokenization & Embeddings From Scratch: Read on Dev.to


