Sub topic 6
Positional information: telling the model where tokens are
This chapter assumes you have read the earlier chapters on embeddings and self-attention. You should be comfortable with matrix shapes such as (seq_len, d_model), with softmax, and with the idea that queries, keys, and values come from learned matrix products. Here you will see why attention alone cannot tell "dog bites man" from "man bites dog". You will also see the main ways models add word-order information, and the practical problems that come with each.
Why attention needs help with order
Self-attention compares every token with every other token using dot products. A dot product between a query and a key depends only on the two vectors. It does not depend on where the tokens sit in the sequence.
This has a precise consequence. Take a sequence of embeddings and shuffle the rows. Without a causal mask, the attention output is the same set of rows, shuffled in the same way. This property is called permutation equivariance. The layer treats its input as a bag of vectors, not a sequence.
Word order carries meaning, so the model needs a way to know it. The usual fix is to inject position information into the vectors the attention layers see. Positional information is any signal that tells a token where it is in the sequence, or how far it is from another token.
The next code block checks this claim numerically. It runs attention on four vectors, then on a shuffled copy. After that it adds sinusoidal position vectors, which are defined in the next section, and repeats the test.
import numpy as np
def sinusoidal_positions(seq_len, d_model):
positions = np.arange(seq_len)[:, None]
i = np.arange(d_model // 2)[None, :]
angles = positions / (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
def attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
scores = q @ k.T / np.sqrt(k.shape[-1])
scores = scores - scores.max(axis=-1, keepdims=True)
w = np.exp(scores)
w = w / w.sum(axis=-1, keepdims=True)
return w @ v
rng = np.random.default_rng(0)
d = 8
x = rng.normal(size=(4, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
perm = np.array([2, 0, 3, 1])
# No positions: shuffling the input just shuffles the output.
out = attention(x, Wq, Wk, Wv)
out_shuffled = attention(x[perm], Wq, Wk, Wv)
print(np.allclose(out[perm], out_shuffled))
# With positions added: the shuffle now changes the result.
pe = sinusoidal_positions(4, d)
out_pos = attention(x + pe, Wq, Wk, Wv)
out_pos_shuffled = attention(x[perm] + pe, Wq, Wk, Wv)
print(np.allclose(out_pos[perm], out_pos_shuffled))The first line prints True and the second prints False. Once position vectors are added, the model can tell the original order from the shuffled one.
Where position enters the model
There are two broad places to inject position:
- At the input. Add a position vector to each token embedding before the first layer. The attention layers then see "token plus position" as one vector.
- Inside attention. Modify the queries and keys, or the attention scores, so the score between two tokens depends on their relative distance.
The diagram contrasts the two routes.
Absolute position methods
An absolute method gives each position index, 0, 1, 2, and so on, its own vector.
Learned position embeddings
The simplest method is a lookup table of shape (max_len, d_model). Row p holds the vector for position p. The table is a trained parameter, like the token embedding table. The input to the first layer is token_embedding[id] + position_embedding[p].
This method is easy to implement and works well within the trained length. Its main weakness is the hard limit. If the table has 2048 rows, position 2048 has no vector at all. Even if you invent one, the model has never been trained on it.
Sinusoidal encodings
The original transformer paper used fixed vectors built from sine and cosine waves. For position p and dimension pair i, the values are sin(p / 10000^(2i/d)) and cos(p / 10000^(2i/d)). Low-numbered dimension pairs oscillate quickly and high-numbered pairs oscillate slowly. Each position therefore gets a unique pattern, much like the digits of a counter, where the last digit changes fastest.
Nothing is trained, and the function can produce a vector for any p. In practice, models trained on short sequences still tend to do poorly on much longer ones. The formula can produce the vector, but the weights have never learned what to do with it.
Relative position methods
Language often depends more on distance than on exact index. The word "it" refers to a noun a few tokens back, wherever that pair appears in the text. Relative methods make the attention score between two tokens depend on how far apart they are.
Rotary position embedding (RoPE)
RoPE is used in many open models. It does not add anything to the embeddings. Instead, it rotates the query and key vectors by an angle proportional to the token's position. It treats each pair of dimensions as a point in a 2D plane and rotates that point. Different pairs rotate at different speeds, as in the sinusoidal scheme.
Rotations have a useful property. The dot product of a query rotated by angle m·θ and a key rotated by angle n·θ depends only on the difference m − n. The attention score therefore reflects relative distance, although you only ever apply an absolute rotation to each vector.
import numpy as np
def rope(x, position, base=10000):
# x: 1D vector with an even number of dimensions
d = x.shape[0]
freqs = base ** (-np.arange(d // 2) * 2 / d)
angles = position * freqs
cos, sin = np.cos(angles), np.sin(angles)
x1, x2 = x[0::2], x[1::2]
out = np.empty_like(x)
out[0::2] = x1 * cos - x2 * sin
out[1::2] = x1 * sin + x2 * cos
return out
rng = np.random.default_rng(1)
q = rng.normal(size=8)
k = rng.normal(size=8)
# Both pairs are 2 positions apart, at different absolute locations.
score_a = rope(q, 5) @ rope(k, 3)
score_b = rope(q, 12) @ rope(k, 10)
print(np.isclose(score_a, score_b))
# A pair 5 positions apart gives a different score.
score_c = rope(q, 8) @ rope(k, 3)
print(np.isclose(score_a, score_c))This prints True and then False. The score depends on the distance between the two positions, not on where the pair sits.
RoPE is applied to queries and keys only. The values v are left unrotated. It is also applied inside every attention layer, not once at the input.
ALiBi
ALiBi (Attention with Linear Biases) adds no position vectors. It subtracts a penalty from each attention score, proportional to the distance between the two tokens. Each head uses its own slope, so some heads focus on nearby tokens and others look further back. The method is cheap and was designed to help models handle sequences longer than those seen in training.
Comparing the methods
| Method | Type | Where applied | Trained parameters | Hard length limit |
|---|---|---|---|---|
| Learned embeddings | Absolute | Input | Yes, `max_len × d_model` | Yes, table size |
| Sinusoidal | Absolute | Input | No | No, but quality drops past training length |
| RoPE | Relative | Queries and keys in every layer | No | No, but quality drops past training length without adjustment |
| ALiBi | Relative | Attention scores | No | No, and designed to extrapolate |
Edge cases and failure modes
Extrapolation beyond the training length
A model trained on 4,096-token sequences has never seen position 10,000. With RoPE, the angles at that position fall outside the range the model learned from. Attention behavior can then degrade sharply. This is a major reason context windows have a fixed size.
Common extensions rescale positions. In position interpolation, you divide every position index by a constant so that a longer sequence maps back into the trained angle range. Other variants change the rotation frequencies, so fast-rotating pairs are left alone and slow-rotating pairs are stretched. These methods usually need a short round of fine-tuning on longer text to work well.
Position and the key-value cache
During generation, the key-value cache stores the keys and values of earlier tokens so they are not recomputed. With RoPE, the cached keys already contain their rotations. This works because a key's rotation depends only on its own position, which never changes. The new token is rotated with its position index, which is the current length of the sequence. If you pass the wrong index, for example 0 for every new token, the model sees all of its tokens as sitting at the same place and the output degrades.
Padding and batching
When sequences of different lengths are padded to the same length, position indices must count real tokens only. Left-padding shifts the real tokens to later indices unless position IDs are computed from the attention mask. Many serving bugs come from mismatched position IDs between training and inference.
Positions are not perfectly used
Even with correct positional information, models often attend more reliably to the start and end of a long input than to the middle. Position methods give the model the ability to track order. They do not guarantee that it uses that ability evenly across the whole window.
Summary of the working model
- Attention scores depend on vector contents, so without positional information the layer cannot see order.
- Absolute methods add a position-specific vector at the input. Relative methods change how queries and keys interact, so scores depend on distance.
- RoPE rotates queries and keys by position-dependent angles, and the resulting dot products depend only on the offset between tokens.
- Behavior beyond the training length is the main practical risk, and fixes usually involve rescaling positions plus extra training.
Exercise
You run the permutation test from this chapter on an attention layer with no causal mask and no positional information. You shuffle the input rows with a permutation and compare the output with the shuffled original output. What do you expect, and what changes if you add sinusoidal position vectors to the inputs at their original positions before shuffling the token content?
Show answer
Without positions, the output rows of the shuffled input equal the original output rows shuffled the same way, so the comparison is True (permutation equivariance). If position vectors stay attached to fixed slots while the token content is shuffled, each token meets a different position vector. The outputs are then no longer a simple reshuffle of the original ones, so the comparison is False. This shows the model can now distinguish different orderings.
Exercise
A model uses RoPE and was trained on sequences up to 4,096 tokens. Someone feeds it 8,192 tokens with no other changes. Name the likely problem, and describe one fix and what it costs.
Show answer
Positions 4,096 to 8,191 produce rotation angles the model never saw in training, so attention quality can degrade. One fix is position interpolation: divide each position index by 2 so the new range maps onto the trained range. The cost is that nearby positions become closer together in angle, so fine distinctions between neighboring tokens are blurred. The model usually needs a short fine-tuning run on longer sequences to recover quality.
Exercise
Why is RoPE applied to queries and keys but not to values?
Show answer
Position matters for deciding how much one token attends to another, which is determined by the query-key dot product. Rotating queries and keys makes that score depend on relative distance. The values carry the content that gets mixed into the output. Rotating them would distort that content with position-dependent angles that serve no purpose in the weighted sum.