Sub topic 6
Positional information: telling the model where tokens are
This chapter assumes you know what token embeddings are (vectors, one per token ID) and have seen the self-attention computation from the previous chapter. You should be comfortable with NumPy arrays and matrix multiplication.
Why attention needs position
Self-attention compares every token with every other token using dot products. Nothing in that computation depends on where a token sits in the sequence. If you shuffle the input rows, the output rows are shuffled the same way, and each row keeps its value. This property is called permutation equivariance.
Word order carries meaning. "The dog bit the man" and "The man bit the dog" use the same tokens. Without position information, attention treats them as the same set of vectors. The model needs an extra signal that says "this token is at position 0, this one at position 1," and so on.
The causal mask from the earlier chapter does not fix this. It limits which tokens can be seen, but it does not tell the model how far away they are.
The simplest fix: add a position vector
The original transformer adds a position vector to each token embedding before the first layer. The input to layer one is:
x[i] = embedding(token[i]) + position_vector(i)
Both vectors have the same width, so the sum has that width too. After this step, the same token at two different positions produces two different input vectors.
Sinusoidal encodings
The original paper builds the position vectors from sine and cosine waves of different frequencies. No learning is involved. Each position gets a fixed pattern.
import numpy as np
def sinusoidal_positions(seq_len, d_model):
# d_model must be even
pos = np.arange(seq_len)[:, None]
i = np.arange(d_model // 2)[None, :]
angles = pos / (10000 ** (2 * i / d_model))
pe = np.zeros((seq_len, d_model))
pe[:, 0::2] = np.sin(angles)
pe[:, 1::2] = np.cos(angles)
return pe
pe = sinusoidal_positions(seq_len=6, d_model=8)
print(np.round(pe[:3], 2))Low-index dimensions use fast-changing waves, so they separate nearby positions. High-index dimensions use slow waves, so they separate distant ones. Together they give every position a distinct pattern.
Learned position embeddings
An alternative is a trainable table with one row per position, up to a maximum length. It works like the token embedding table, and training adjusts the rows. This is simple, but the model has no row for positions beyond the table size.
Relative position methods
Adding a vector to the input makes the model infer distance indirectly. Many modern models instead inject position inside attention, so the score between two tokens depends on how far apart they are.
Rotary position embeddings (RoPE) are the common choice. RoPE rotates each query and key vector by an angle proportional to its position. When you take the dot product of a rotated query and a rotated key, the result depends on the difference between their positions. Position is applied to queries and keys only, not to values.
Common errors
- Forgetting position entirely. The model still runs and trains, but it behaves like a bag of tokens and gives poor results on order-sensitive text.
- Exceeding the trained length. A learned table has no entries past its maximum. Sinusoidal and rotary methods can produce values for longer inputs, but quality usually drops on lengths the model never saw in training.
- Adding position to values in a RoPE model. Rotation applies to queries and keys only.
- Mixing up width. The position vector must match the embedding width, or the addition fails.
Exercise
You shuffle the order of the input embeddings, with no position information added. What happens to the output of a self-attention layer without a mask?
Show answer
The output rows are shuffled in the same way. Each token's output value does not change, so the layer cannot tell the original order apart from the new one. This is why position information must be added.