Lesson 7 of 97 min
Position
Attention on its own can't see the order of the words, so each query and key is turned by an angle that grows with its place, and a score then depends only on how far apart two tokens are.
After this lesson you can explain how a transformer knows the order of words.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Add a row of waves
The original Transformer made a fixed row for each position. Each sine and cosine pair uses the same speed, and the next pair uses a slower speed. Add that row to the token embedding. Here the same four-number embedding goes into the first layer at positions zero and two. Attention Is All You Need, section 3.5
import torch
width = 4
positions = torch.tensor([0., 2.])
speeds = 10_000 ** (-torch.arange(0, width, 2) / width)
angles = positions[:, None] * speeds
waves = torch.stack((angles.sin(), angles.cos()), dim=-1).flatten(1)
token = torch.tensor([1., 2., 3., 4.])
print(torch.round(token + waves, decimals=3))tensor([[1.0000, 3.0000, 3.0000, 5.0000],
[1.9090, 1.5840, 3.0200, 5.0000]])See which numbers rotate together
Each pair rotates by [[cos, -sin], [sin, cos]]. Qwen3 pairs the first half of a head with the second half, so in a 128-number head the first pair uses indices 0 and 64. Here there are four numbers, so index 0 pairs with 2. Both pairs turn a quarter turn in this example. Qwen3 implementation
from transformers.models.qwen3.modeling_qwen3 import rotate_half
x = torch.tensor([1., 2., 3., 4.])
rotation = torch.tensor([[0., -1.], [1., 0.]])
pairs = x.reshape(2, -1).T
rotated = (pairs @ rotation.T).T.flatten()
print(rotated.tolist(), torch.equal(rotated, rotate_half(x)))[-3.0, -4.0, 1.0, 2.0] True
Read the RoPE settings
Read the rotary settings and the advertised position limit before a long run. The config below uses default RoPE. A checkpoint configured for YaRN can instead declare rope_type="yarn" and scaling settings. Use the checkpoint’s intended settings and test it on texts of your target length. Qwen3 config · YaRN paper
from transformers import AutoConfig
name = "Qwen/Qwen3-0.6B-Base"
revision = "da87bfb608c14b7cf20ba1ce41287e8de496c0cd"
cfg = AutoConfig.from_pretrained(name, revision=revision)
print(cfg.rope_parameters)
print(cfg.max_position_embeddings){'rope_theta': 1000000, 'rope_type': 'default'}
32768See what the causal mask preserves
Give each visible value the same share. The last token averages the same three values either way. Earlier tokens see different prefixes. Pass their averages to a second layer and the last token can pick up that difference. A decoder can pick up some order this way even with its rotations off. The Impact of Positional Encoding on Length Generalization
def causal_mean(values):
return values.cumsum(dim=-1) / torch.arange(1, values.size(-1) + 1)
values = torch.tensor([[1., 3., 9.], [3., 1., 9.]])
first = causal_mean(values)
second = causal_mean(first)
print(first[:, -1])
print(second[:, -1])tensor([4.3333, 4.3333]) tensor([2.4444, 3.1111])
Read a model with two kinds of layers
The series also uses Qwen3.5-0.8B-Base. Its six full-attention layers rotate a quarter of each head. Its 18 linear-attention layers update a state in sequence, which gives them a way to use order directly. Both kinds of layer are listed in the same text config. Qwen3.5 config
from collections import Counter
hybrid = AutoConfig.from_pretrained(
"Qwen/Qwen3.5-0.8B-Base",
revision="dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68",
).text_config
print(dict(Counter(hybrid.layer_types)))
print(hybrid.rope_parameters["partial_rotary_factor"]){'linear_attention': 18, 'full_attention': 6}
0.25Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Attention
A token sees three tokens, itself included. Their vectors are [2, 0], [0, 4] and [4, 8], and its shares for them are 0.5, 0.25 and 0.25. What is the second number of its blend?
2 of 3
With no position signal, attention reads "The penguin ate the fish." and "The fish ate the penguin." Does the period take in the same blend in both?
3 of 3
In a model with RoPE, a query at place 20 and a key at place 5 get a score. Now the query is at place 110. At which place must the key be for exactly the same score?
The ideas in this lesson
- Order is invisible to attention
- On its own, attention gives each token the same share wherever it is, so mixed-up words give the same blends.
- Position signal
- A model is told each token's place; the first transformers added a row of numbers for each place to its vector.
- RoPE
- Each query and key is turned by an angle that grows with its place, so a score depends only on how far apart two tokens are.
It leans on
- Vector
- Context window
Transcript
What the video says, part by part. Press a time to watch from there.
The order of the words
Here's a puzzle. The penguin ate the fish. The fish ate the penguin. The same words, in a different order. A model looks at all the words at once. So how does it know the order of the words?
Take away the order
Let's find out. Here are the two sentences, read by a real model. In each one, the period looks back at every token before it. Now take away the model's sense of order. Will the period give "fish" the same share in both sentences? Or a different one?
A bag, not a row
In attention, each token gives the tokens before it a share, and takes in a blend of them. Here's one of this model's first heads, with its sense of order switched off. The period gives "fish" the same small share in both sentences. And every other token gets the same share in both, too.
If you guessed "different", you're not alone. But a share comes from the period's query and each token's key.
Both are made from a token's own numbers.
Nothing in them says where the token is.
The same blend
So the period takes in the same blend, and comes out with the same vector.
On its own, attention sees a bag of tokens... not a row.
But order matters.
Ask the real model, with its sense of order back.
"The penguin ate the fish. So the fish is now inside the…" Penguin.
Now ask it the other way around: "The fish ate the penguin. So the penguin is now inside the…" Fish.
The words are the same. Only their order changed the answer.
A place for each token
Attention on its own sees a bag of tokens, not a row.
So a model has to be told each token's place.
Each token starts as its row in the table.
GPT-2 also learned a row of numbers for each place, and adds it to the token's row.
So the same word at place two and at place five starts from different numbers.
That's a position signal. People call it positional encoding.
GPT-2 learned rows for about a thousand places.
So what happens one token past the last one?
There's no row for it.
GPT-2 stops with an error. You'll still see these learned place rows in older code.
A turn for each place
Attention scores each pair of tokens with a query and a key. Today's models don't add a place to each token. They turn its query and its key.
But how do you turn a row of numbers?
A turn works on two numbers at a time, like an arrow on a page. So a query's numbers are taken in pairs.
Before the scores, each pair in each query and each key is turned by its place.
One step for place one. Two steps for place two. This is called RoPE.
Why turn?
Here's a made-up pair, like the hour hand of a clock. Each place turns it one hour. The query is at place five, and the key at place three.
Why turn?
A score is a dot product. For two arrows, it depends on their lengths and the angle between them. The picture works out their score: two.
Now move both along, a hundred places. Will the score change?
Only the distance counts
No. Both turn by the same amount, so the angle stays the same. So does the score. Like on a clock: three and five are as far apart as nine and eleven.
Now, back at five and three, move the key one place closer. The angle gets smaller. The score goes up, to about three and a half.
So the score depends only on how far apart two tokens are.
Each pair at its own speed
But a hand comes back to where it started. Spot the problem?... An hour hand goes all the way around in twelve steps. So with one pair, twelve places apart scores just like zero apart. So each pair turns at its own speed, like a clock's second, minute and hour hands. In this model, the fastest pair goes around in about six places. The slowest takes millions.
One number in the model's settings sets how slow. With many speeds together, the model can tell a near token from a far one.
Past what it learned
So can a model read a text of any length? The turn can be worked out for any place. But what each distance means is learned in training. Here's a small model built this way. It was trained on texts of about two thousand tokens.
This is its loss, its surprise at each next token. It stays flat up to about there. Then it climbs, to more than twice as high.
So, no. Past the longest texts it learned on, a model reads badly. How far a model reads well is called its context window.
In code
Now in real code. Ask the model, "The penguin ate the fish. So the fish is now inside the…" It says "penguin", with a chance of about eight in ten. Now give every token a place ten thousand further along. What will it say?
Penguin, with the same chance.
And a check says all its chances match.
Moving every place along doesn't change any distance, and only the distances count.
Here's how you'd use this. A model's settings say how slowly it turns, and how far it was built to read. Read them before you give it a long text.
Three ideas
So on its own, attention sees a bag of tokens. A position signal tells each token its place.
Today, each query and key is turned by its place, so all that counts is how far apart two tokens are. With its turn on, this head now looks at the word just before the period.
Each place turns
The query and the key turn a little more with each place. Now try it on this lesson's page, and take the quiz. Move both hands along, and watch the score.
You use this lesson in Lab 3: Open up a real transformer, after Encoders and decoders.
Facts last checked on .
