CSCE 471 Natural Language Processing · Spring 2027

Positional Encoding

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

“The dog bit the man” and “The man bit the dog” contain exactly the same words, but mean very different things. Word order matters. Self-attention, however, has a surprising blind spot: on its own, it cannot tell these two sentences apart.

This reading explains why, and how Transformers fix it by adding a positional encoding to each word vector. We will build up the classic sinusoidal positional encoding step by step: first what we want from it, then a single rotating point on a circle, then many rotations at different speeds, and finally why this design helps attention reason about distance.

After reading this, you should be able to explain why self-attention ignores word order · describe how a positional encoding is added to word vectors · list the properties a good positional encoding should have · explain the sinusoidal formula using rotations at different frequencies · explain why the dot product of two sinusoidal encodings depends only on their distance · name some alternatives used in modern models

1Self-attention ignores word order

Recall how self-attention computes the output for word $i$: it compares $q_i$ with every key $k_j$, turns the scores into weights $\hat\alpha_{i,j}$ with a softmax, and returns $z_i=\sum_j \hat\alpha_{i,j} v_j$. Look closely at what this depends on: the set of key and value vectors, and nothing about where each word sits. The sum $\sum_j$ gives the same answer in any order.

So if we swap two words, every word still sees exactly the same vectors. The output for each word stays the same; it just moves along with its word. To self-attention, a sentence is a bag of words.

Figure 1 (interactive). Self-attention outputs for I like cats a lot and the swapped I cats like a lot, using a small toy model (3-dimensional word vectors, 2-dimensional outputs). Each row compares the same word's output in the two sentences. Switch on positional encoding to see the outputs change.

2The fix: add a position vector

The idea is simple. For every position $pos=1,2,3,\dots$ we define a vector $PE(pos)$ with the same dimension $d$ as the word vectors, and add it to the word vector at that position:

$$x_{pos} \;\leftarrow\; x_{pos} + PE(pos).$$

Now the input at position 2 is “word + position 2”. If like and cats swap places, cats receives $PE(2)$ and like receives $PE(3)$, so the inputs are different and self-attention can tell the two sentences apart.

What should $PE(pos)$ look like?

We want an encoding with these properties:

Two naive ideas fail these tests:

IdeaProblem
$PE(pos)=pos$ (add the number)Unbounded: at position 500 the position swamps the word vector.
$PE(pos)=pos/n$ for an $n$-word sentenceDepends on length: position 5 is $0.5$ in a 10-word sentence but $0.05$ in a 100-word sentence.

3One frequency: a point on a circle

Here is a bounded idea: represent each position as a point on the unit circle, rotating by a fixed angle $\omega$ per position:

$$PE(pos) = \big[\,\sin(pos\cdot\omega),\; \cos(pos\cdot\omega)\,\big].$$

All values stay between $-1$ and $1$, and the encoding does not depend on sentence length. Since every vector has length 1, the cosine similarity of two positions is just the cosine of the angle between them:

$$\cos\text{-sim}\big(PE(pos), PE(pos')\big) = \cos\big((pos-pos')\,\omega\big).$$

This depends only on the distance $pos-pos'$. So neighboring positions are always equally similar (consistent steps), and nearby positions are more similar than distant ones, at least for a while.

Rotation per position $\omega$:Positions shown:
Figure 2 (interactive). Positions as points on a circle. Every step rotates by the same angle $\omega$, so neighbors are always equally similar. Increase the number of positions: eventually the points wrap around and two positions land on the same spot.

The catch is the last thing Figure 2 shows: a circle wraps around. With $\omega=30^\circ$, position 13 lands exactly on position 1, so the encoding is no longer unique. A small $\omega$ delays the wrap-around, but then neighboring positions become almost identical and hard to distinguish. One frequency cannot do both jobs.

4Many frequencies: lessons from binary

How do we write numbers so that every one is unique? Binary. Look at how the bits change as we count from 0 to 15:

Each bit alone repeats, but together, the fast bits distinguish neighbors and the slow bits distinguish far-apart positions, so every number gets a unique pattern.

Sinusoidal positional encoding uses the same trick, with smooth waves instead of bits. It stacks many (sin, cos) pairs, each rotating at a different frequency: a “soft” version of alternating bits.

Position $pos$:
Binary (4 bits)
fastest bit on the right
Sinusoidal ($d=8$, 4 frequencies)
−1 +1
Figure 3 (interactive). Left: binary code of the position. Right: the four frequencies of an 8-dimensional sinusoidal encoding ($\omega_k = 1/10^{\,k}$ for $k=0,1,2,3$, the values the formula below gives for $d=8$), with the current position marked. The colored cells show the full 8-dimensional vector $PE(pos)$. Like the binary bits, the first dimensions change fast and the last dimensions change slowly.

5The sinusoidal formula

For a model with dimension $d$, the encoding has $d/2$ (sin, cos) pairs. Pair number $k$ (for $k=0,1,\dots,d/2-1$) rotates with frequency $\omega_k$:

$$PE(pos)_{2k} = \sin(pos\cdot\omega_k),\qquad PE(pos)_{2k+1} = \cos(pos\cdot\omega_k),\qquad \omega_k = \frac{1}{10000^{\,2k/d}}.$$

Reading the formula:

Dimension $d$:
−1 +1
Figure 4 (interactive). The sinusoidal encoding for positions 0–50 (rows) and all $d$ dimensions (columns). Dimensions on the left alternate quickly from row to row; dimensions on the right barely change. Each row is a unique pattern. Hover over the image to read individual values.

6Why this helps attention

The score between two positions involves a dot product of their (projected) input vectors. Ignoring the matrices $W^Q$ and $W^K$ for simplicity, the dot product of the inputs at positions $i$ and $j$ expands into four terms:

$$\big(x_i+PE(i)\big)\cdot\big(x_j+PE(j)\big) = \underbrace{x_i\cdot x_j}_{\text{word–word}} + \underbrace{x_i\cdot PE(j) + PE(i)\cdot x_j}_{\text{word–position}} + \underbrace{PE(i)\cdot PE(j)}_{\text{position–position}}.$$

The first term is about the words, as before. The middle terms mix a word with a position; they carry little useful information on their own. The last term is where position comes in, and for the sinusoidal encoding it has a neat form. Using $\sin a\sin b+\cos a\cos b=\cos(a-b)$ for every pair:

$$PE(i)\cdot PE(j) = \sum_{k=0}^{d/2-1}\cos\big((i-j)\,\omega_k\big).$$

It depends only on the distance $i-j$, not on where in the sentence the two words are. It is largest ($d/2$) when $i=j$ and generally decreases as the words get farther apart. So “I like” at positions 1–2 and the same pair at positions 31–32 get exactly the same position–position term, while “I … like” at positions 1 and 4 get a different one.

Reference position:
$PE(pos)\cdot PE(pos')$ for all pairs
Row for the reference position
Figure 5 (interactive). Dot products between sinusoidal encodings ($d=128$, positions 0–50). Left: the full matrix, darkest on the diagonal and constant along every diagonal line, because the value depends only on $pos-pos'$. Right: one row as a curve. Move the reference position: the curve shifts but keeps the same shape.
Optional: shifting by $k$ positions is a rotation

The original paper gives one more reason for this design: for any fixed offset $\Delta$, $PE(pos+\Delta)$ is a linear function of $PE(pos)$. For one (sin, cos) pair with frequency $\omega$, the angle-addition formulas give

$$\begin{bmatrix}\sin((pos+\Delta)\omega)\\ \cos((pos+\Delta)\omega)\end{bmatrix} = \begin{bmatrix}\cos(\Delta\omega) & \sin(\Delta\omega)\\ -\sin(\Delta\omega) & \cos(\Delta\omega)\end{bmatrix}\begin{bmatrix}\sin(pos\,\omega)\\ \cos(pos\,\omega)\end{bmatrix}.$$

The matrix depends only on $\Delta$, not on $pos$: moving $\Delta$ positions ahead is the same rotation everywhere, exactly like Figure 2. This makes it easy for a model with linear layers to learn patterns such as “attend to the word two positions back”.

7Positional encoding in the Transformer

In the Transformer, the positional encoding is added once, at the very bottom: each input token is mapped to its embedding, the positional encoding for its position is added, and the result is fed into the stack of Transformer layers. The sinusoidal encoding has no learned parameters; it is computed from the formula.

Why add instead of concatenate? Concatenating would increase the dimension of every layer. Adding keeps the dimension at $d$, and in a high-dimensional space the word information and the position information can coexist: the model learns to use different directions for each.

Sinusoidal encoding is not the only option. Some alternatives:

8Summary

9Practice

Exercise 1: compute an encoding

With $d=4$, compute $PE(1)$. (Use $\sin 1\approx 0.841$, $\cos 1\approx 0.540$.)

The frequencies are $\omega_0 = 1/10000^{0}=1$ and $\omega_1=1/10000^{2/4}=1/100=0.01$.
$PE(1)=[\sin 1,\ \cos 1,\ \sin 0.01,\ \cos 0.01]\approx[0.841,\ 0.540,\ 0.010,\ 1.000]$. The first pair has already rotated a lot; the second has barely moved.

Exercise 2: distance

For the one-frequency encoding $PE(pos)=[\sin(pos\,\omega),\cos(pos\,\omega)]$, show that $PE(i)\cdot PE(j)$ depends only on $i-j$.

$PE(i)\cdot PE(j)=\sin(i\omega)\sin(j\omega)+\cos(i\omega)\cos(j\omega)=\cos(i\omega-j\omega)=\cos((i-j)\omega)$.

Exercise 3: wrap-around

With a single frequency and $\omega=45^\circ$ per position, which position first lands on the same point as position 1? Why does adding more, slower frequencies fix this?

A full turn is $360^\circ/45^\circ=8$ positions, so position $1+8=9$ coincides with position 1. A slower pair has not completed a turn by then, so positions 1 and 9 differ in those dimensions and the full vector stays unique.

Quick quiz

10Further reading