← Home

Positional Encoding Explained: How Transformers Learn Order

What is positional encoding in transformers? Why attention is order-blind, learned vs sinusoidal embeddings, and a from-scratch NumPy implementation.

View as Markdown

I closed the token embeddings post with a problem I had set aside: the embedding lookup is order-blind. gather returns the same vector for cat whether it is the first word or the hundredth. Attention, which receives those vectors, is permutation-invariant too. Shuffle the tokens and, without help, the math produces the same outputs in shuffled order. By default a transformer is a bag-of-words model, and that broke my mental model the first time I thought it through, because order carries much of the meaning in language.

$$ \text{"Dog bites man"} \neq \text{"Man bites dog"}. $$

The two sentences have the same three words and the same three token embeddings, but opposite meanings. Something has to tell the model where each token sits, and that is positional encoding. In GPT it is a second lookup table next to the token embedding matrix. This post covers why attention cannot see order on its own, what positional vectors are, the math of adding them, a three-word worked example with every addition written out, learned vs sinusoidal encodings with formula steps, and where this sits in my AL-1 build.


Why is attention order-blind?

Self-attention computes a weighted sum over all tokens, and the weights come from dot products between query and key vectors. A dot product is

$$ q_i \cdot k_j = \sum_{k=1}^{d} q_{i,k}\, k_{j,k}. $$

There is no position index $t$ inside that sum. The number $q_i \cdot k_j$ depends only on the vectors, not on whether $i$ is slot 0 or slot 99. Shuffle the tokens and the same vectors land in different slots, so attention computes the same pairwise dot products, permuted. Without extra information, the model cannot tell position 0 from position 100.

Picture six people in a room: Alice, Bob, Charlie, David, Eva and Frank. You are told who is present but not where they sit. A transformer with token embeddings alone is in that position. It knows the cast but not the seating chart, and language needs the seating chart.

flowchart LR
  subgraph blind["Token embeddings only"]
    a1["cat @ pos 0"] --> v1["vector V"]
    a2["cat @ pos 99"] --> v1
  end
  subgraph fixed["+ Positional encoding"]
    b1["cat @ pos 0"] --> w1["V + P0"]
    b2["cat @ pos 99"] --> w2["V + P99"]
  end

The word cat has the same embedding vector $V$ everywhere. Only after adding a position-specific vector $P_t$ does slot 0 become $V + P_0$ and slot 99 become $V + P_{99}$, which are two different inputs to attention.


What is a positional embedding?

A positional embedding is a second lookup table, parallel to the token table. The token embedding answers “what word is this?” and the positional embedding answers “where does it sit?”

Stack all position vectors into a matrix

$$ P \in \mathbb{R}^{L \times d} $$

where $L$ is the maximum sequence length and $d$ is d_model. Row $t$ is the vector that means “I am the token at position $t$.”

GPT-2 small uses

$$ L = 1024 $$
$$ d = 768 $$
$$ P \in \mathbb{R}^{1024 \times 768} $$
$$ 1024 \times 768 = 786{,}432 \text{ parameters} $$

That is roughly 800k parameters whose only job is to encode order. The lookup is the same gather as for token embeddings, indexed by position ID instead of token ID.

Toy table with $L = 5$, $d = 2$:

$$ P = \begin{bmatrix} 0.1 & 0.2 \\ 0.3 & 0.4 \\ 0.5 & 0.6 \\ 0.7 & 0.8 \\ 0.9 & 1.0 \end{bmatrix} $$
$$ \text{row } 0 = \text{first token} $$
$$ \text{row } 1 = \text{second token} $$
$$ \vdots $$

The implementation differs from the token embedding layer in one respect: the indices are generated, not passed in.

class PositionalEmbedding:
    def __init__(self, max_seq, d_model, std=0.02):
        w = np.random.randn(max_seq, d_model) * std
        self.weight = Tensor(w)              # (max_seq, d_model), trainable

    def forward(self, seq_len):
        positions = np.arange(seq_len)       # [0, 1, 2, ..., seq_len-1]
        return self.weight.gather(positions, dim=0)   # (seq_len, d_model)

For a 5-token sentence, np.arange(5) makes [0, 1, 2, 3, 4] and gather pulls those five rows. The initializer is the same $0.02$ GPT-2 standard deviation as the token embeddings, so training does not start against large activations. The cost is $O(L)$ row selection with no matmul, which is negligible next to attention’s $O(L^2)$.


The math: why we add, not concatenate

The transformer input is the sum of the two tables, elementwise:

$$ X = E + P $$

where $E$ holds token embeddings and $P$ holds position embeddings, both with shape $(L, d)$.

Take a toy sentence of three tokens with $d = 2$:

$$ E = \begin{bmatrix} 1 & 2 \\ 3 & 4 \\ 5 & 6 \end{bmatrix} $$
$$ P = \begin{bmatrix} 0.1 & 0.2 \\ 0.3 & 0.4 \\ 0.5 & 0.6 \end{bmatrix} $$

Row 0 of $X$:

$$ X_{0,0} = E_{0,0} + P_{0,0} $$
$$ X_{0,0} = 1 + 0.1 $$
$$ X_{0,0} = 1.1 $$
$$ X_{0,1} = E_{0,1} + P_{0,1} $$
$$ X_{0,1} = 2 + 0.2 $$
$$ X_{0,1} = 2.2 $$

Row 1 of $X$:

$$ X_{1,0} = 3 + 0.3 = 3.3 $$
$$ X_{1,1} = 4 + 0.4 = 4.4 $$

Row 2 of $X$:

$$ X_{2,0} = 5 + 0.5 = 5.5 $$
$$ X_{2,1} = 6 + 0.6 = 6.6 $$

So

$$ X = E + P = \begin{bmatrix} 1.1 & 2.2 \\ 3.3 & 4.4 \\ 5.5 & 6.6 \end{bmatrix}. $$

This addition is the whole mechanism. After it, cat at position 0 and cat at position 99 are different vectors going into attention.

Why add two unrelated things instead of concatenating? Concatenation would join $[1, 2]$ and $[0.1, 0.2]$ into $[1, 2, 0.1, 0.2]$, doubling $d$. Attention’s projection cost scales with $d^2$, so doubling the width quadruples that cost and inflates every downstream weight. Addition keeps $d$ fixed, so position information costs no extra width. The model has 768 dimensions to work with, and gradient descent can carve out subspaces where token identity and position do not collide. The sum stays separable enough for attention to read both.

I plotted the projection cost of both options against $d$. The dashed line at $d = 768$ marks my model. At that width the position table has the 786,432 parameters from above.

Line chart of projection cost against model width d. Adding costs d squared and concatenating costs (2d) squared. At d equals 768 adding costs 589,824 and concatenating costs 2,359,296.
At $d = 768$, adding costs 589,824 and concatenating costs 2,359,296, four times as much.

Like token embeddings, $P$ starts as scaled noise. Backprop updates only the positions a batch used: a 5-token sequence sends gradients into rows 0 to 4 and leaves rows 5 to 1023 alone on that step. Over training the rows specialize. Nobody hand-codes this; it comes from next-token prediction, like everything else in the model.


Worked example: “dog bites man” vs “man bites dog”

I use $d = 2$ so every addition fits on one line. The three token embeddings come from the token embedding table:

$$ e_{\text{dog}} = \begin{bmatrix} 1 \\ 2 \end{bmatrix} $$
$$ e_{\text{bites}} = \begin{bmatrix} 3 \\ 1 \end{bmatrix} $$
$$ e_{\text{man}} = \begin{bmatrix} 0 \\ 3 \end{bmatrix} $$

Three learned position rows:

$$ p_0 = \begin{bmatrix} 0.1 \\ 0.0 \end{bmatrix} $$
$$ p_1 = \begin{bmatrix} 0.0 \\ 0.2 \end{bmatrix} $$
$$ p_2 = \begin{bmatrix} 0.3 \\ 0.1 \end{bmatrix} $$

Sentence 1: “dog bites man”

Token at position 0 is dog. Combine embedding with position 0:

$$ x_0 = e_{\text{dog}} + p_0 $$
$$ x_{0,0} = 1 + 0.1 $$
$$ x_{0,0} = 1.1 $$
$$ x_{0,1} = 2 + 0.0 $$
$$ x_{0,1} = 2.0 $$
$$ x_0 = \begin{bmatrix} 1.1 \\ 2.0 \end{bmatrix} $$

Token at position 1 is bites:

$$ x_1 = e_{\text{bites}} + p_1 $$
$$ x_{1,0} = 3 + 0.0 $$
$$ x_{1,0} = 3.0 $$
$$ x_{1,1} = 1 + 0.2 $$
$$ x_{1,1} = 1.2 $$
$$ x_1 = \begin{bmatrix} 3.0 \\ 1.2 \end{bmatrix} $$

Token at position 2 is man:

$$ x_2 = e_{\text{man}} + p_2 $$
$$ x_{2,0} = 0 + 0.3 $$
$$ x_{2,0} = 0.3 $$
$$ x_{2,1} = 3 + 0.1 $$
$$ x_{2,1} = 3.1 $$
$$ x_2 = \begin{bmatrix} 0.3 \\ 3.1 \end{bmatrix} $$

Full input matrix for “dog bites man”:

$$ X_{\text{dbm}} = \begin{bmatrix} 1.1 & 2.0 \\ 3.0 & 1.2 \\ 0.3 & 3.1 \end{bmatrix} $$

Sentence 2: “man bites dog”

The token embeddings and position rows are the same. The order differs, so each token meets a different position vector.

Token at position 0 is man:

$$ x'_0 = e_{\text{man}} + p_0 $$
$$ x'_{0,0} = 0 + 0.1 $$
$$ x'_{0,0} = 0.1 $$
$$ x'_{0,1} = 3 + 0.0 $$
$$ x'_{0,1} = 3.0 $$
$$ x'_0 = \begin{bmatrix} 0.1 \\ 3.0 \end{bmatrix} $$

Token at position 1 is bites:

$$ x'_1 = e_{\text{bites}} + p_1 $$
$$ x'_{1,0} = 3 + 0.0 $$
$$ x'_{1,0} = 3.0 $$
$$ x'_{1,1} = 1 + 0.2 $$
$$ x'_{1,1} = 1.2 $$
$$ x'_1 = \begin{bmatrix} 3.0 \\ 1.2 \end{bmatrix} $$

Token at position 2 is dog:

$$ x'_2 = e_{\text{dog}} + p_2 $$
$$ x'_{2,0} = 1 + 0.3 $$
$$ x'_{2,0} = 1.3 $$
$$ x'_{2,1} = 2 + 0.1 $$
$$ x'_{2,1} = 2.1 $$
$$ x'_2 = \begin{bmatrix} 1.3 \\ 2.1 \end{bmatrix} $$

Full input matrix for “man bites dog”:

$$ X_{\text{mbd}} = \begin{bmatrix} 0.1 & 3.0 \\ 3.0 & 1.2 \\ 1.3 & 2.1 \end{bmatrix} $$

What changed?

Compare row by row. Position 0 was dog at $[1.1, 2.0]$ and is now man at $[0.1, 3.0]$. Position 2 was man at $[0.3, 3.1]$ and is now dog at $[1.3, 2.1]$. Only position 1 (bites) gives the same combined vector $[3.0, 1.2]$, because bites stayed in the middle.

Without positional encoding, sentence 1 would be $[e_{\text{dog}}, e_{\text{bites}}, e_{\text{man}}]$ and sentence 2 would be $[e_{\text{man}}, e_{\text{bites}}, e_{\text{dog}}]$, a permutation of the same three vectors. Attention is blind to that shuffle. With $P$ added, $X_{\text{dbm}} \neq X_{\text{mbd}}$ as matrices, and the query-key dot products inside attention produce different scores. The model can now tell who did the biting.

I built the input matrices for both sentences, first without $P$ and then with it.

Input matrices without positions. Dog bites man has rows 1.0 2.0, 3.0 1.0 and 0.0 3.0. Man bites dog has the same three rows, with dog and man swapped.

Without $P$, both sentences hold the same three rows.

Input matrices with positions added. Dog bites man has rows 1.1 2.0, 3.0 1.2 and 0.3 3.1. Man bites dog has rows 0.1 3.0, 3.0 1.2 and 1.3 2.1.

With $P$, dog and man get different rows. Only bites stays the same.


Learned vs sinusoidal: the design fork

The original Attention Is All You Need paper used fixed sinusoidal encodings: no learned parameters, just a formula. For position $t$ and dimension index $i$ (with model width $d$):

$$ PE(t, 2i) = \sin\!\left(\frac{t}{10000^{2i/d}}\right) $$
$$ PE(t, 2i+1) = \cos\!\left(\frac{t}{10000^{2i/d}}\right) $$

Even dimensions get sines and odd dimensions get cosines. Each pair oscillates at a different wavelength, because the divisor $10000^{2i/d}$ grows with $i$.

Worked numbers for $t = 1$, $i = 0$, $d = 4$:

$$ \frac{2i}{d} = \frac{0}{4} = 0 $$
$$ 10000^{0} = 1 $$
$$ \frac{t}{10000^{2i/d}} = \frac{1}{1} = 1 $$
$$ PE(1, 0) = \sin(1) \approx 0.8415 $$
$$ PE(1, 1) = \cos(1) \approx 0.5403 $$

For $t = 1$, $i = 1$:

$$ \frac{2i}{d} = \frac{2}{4} = 0.5 $$
$$ 10000^{0.5} = 100 $$
$$ \frac{t}{10000^{2i/d}} = \frac{1}{100} = 0.01 $$
$$ PE(1, 2) = \sin(0.01) \approx 0.0100 $$
$$ PE(1, 3) = \cos(0.01) \approx 0.99995 $$

So position 1 gets a distinct value in every one of the $d$ dimensions. Low-index dimensions change fast with $t$ and high-index dimensions change slowly. A shift by a fixed offset acts on each sine/cosine pair as a rotation, so relative offsets are linear functions of these encodings. That is why sinusoids can, in principle, extrapolate to sequence lengths never seen in training. There are no parameters to learn.

I plotted the four dimensions of the $d = 4$ example over positions 0 to 40. The dashed line at $t = 1$ marks the numbers above, and the table repeats them.

Four sinusoidal curves over positions 0 to 40. Dimensions 0 and 1 cycle every few positions. Dimension 2 rises slowly and dimension 3 falls slowly. A table gives the values at t equals 1: 0.8415, 0.5403, 0.0100 and 1.0000.
Dimensions 0 and 1 cycle within a few positions. Dimensions 2 and 3 barely move over 40 positions.

GPT-2 dropped this and learned $P$ directly, which is the table above. These are the tradeoffs I weighed while building AL-1:

  • Learned: flexible, often marginally better on in-distribution lengths, and simple to implement (it is another Embedding). The cost is a hard cap at $L = 1024$: ask for position 1025 and there is no row, so the model cannot run.
  • Sinusoidal: no parameters, and it can extrapolate past the training length, but it is rigid and has historically been slightly worse on benchmarks.

For a toy GPT trained at a fixed context length, learned wins on simplicity and I never need positions beyond $L$. I went with learned. Modern models mostly moved past both to RoPE (which rotates queries and keys by position inside attention rather than adding to the input) and ALiBi (distance-dependent score biases). These are different mechanisms for the same problem.


Where this fits in the build

AL-1 pipeline: autograd → gradient checker → BPE tokenizer → token embeddings → positional encoding → attention.

The input to the first transformer block is $X = E + P$: token identity plus position, both learned, both lookups. Every token carries two answers at once, what am I and where am I. Without $P$, the model reads “dog bites man” exactly like “man bites dog”. That single 800k-parameter matrix, added at layer zero, is what gives the rest of the stack any information about order.

This is where my two-table mental model settled. The token embedding answers “what word is this?” and the positional embedding answers “where does it sit?” Attention receives both in one vector and can use meaning and sequence together. The lookup is cheap and easy to implement, and without it a transformer is a very expensive bag of words.

Support the writing

If this post helped, a coffee keeps the deep dives coming.

Buy me a coffee