Lesson 5 of 96 min
Attention
Each token gives every token before it a share, the shares add up to 1, and it takes in a blend of those tokens by their shares, so the same word gets a different vector in every sentence.
After this lesson you can explain how each token gathers what it needs from the others.
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.
Ask for eager attention
By default, transformers works out attention a fast way that never writes the shares down. So output_attentions=True gives you nothing, and the next line fails. Load the model with attn_implementation="eager", the plain way, and it hands back a set of shares for every layer.
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen3-0.6B-Base"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
inputs = tok("The penguin swam away from the seal.", return_tensors="pt")
out = model(**inputs, output_attentions=True)
print(out.attentions[6].shape)[transformers] `sdpa` attention does not support `output_attentions=True`. Please set your attention to `eager` if you want any of these features. IndexError: tuple index out of range
model = AutoModelForCausalLM.from_pretrained(name, attn_implementation="eager")
out = model(**inputs, output_attentions=True)
print(out.attentions[6].shape)torch.Size([1, 16, 10, 10])
One head at a time
Each head of each layer has its own shares, so read them one head at a time. Here " seal" in layer 7: head 16 looks at "enguin", and head 5 puts it all on "The". To see every head as lines, the way the video draws them, try BertViz in a notebook.
pieces = [tok.decode(i) for i in inputs["input_ids"][0]]
for head in [4, 15]:
row = out.attentions[6][0, head, 8]
top = row.argmax().item()
print(f"head {head + 1}: {pieces[top]!r} gets {row[top]:.2f}")head 5: 'The' gets 1.00 head 16: 'enguin' gets 0.54
The first token is a sink
A head with nothing to find still has to put its shares somewhere, and it puts them on the first token. People call that token an attention sink. Newer models add a gate after attention that takes most of it away, and Qwen3.5 has one.
import torch
on_first = torch.stack(out.attentions)[:, 0, :, 8, 0]
print(on_first.shape)
print((on_first > 0.5).sum().item(), "of", on_first.numel())torch.Size([28, 16]) 304 of 448
Run on Python 3.13, torch 2.15.0 and transformers 5.24.0, with Qwen3-0.6B-Base. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Word embeddings
A table gives each of 1,000 tokens a row of 384 numbers. Five token numbers pick out their rows. What does this print?
import torch
from torch import nn
table = nn.Embedding(1000, 384)
ids = torch.tensor([47, 512, 3, 3, 999])
print(table(ids).shape)2 of 3
"Seal" starts from the same row in "The penguin swam away from the seal." and in "The box was closed with a seal." Does it come out of attention with the same vector?
3 of 3
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?
The ideas in this lesson
- Attention
- Each token gives every token before it, and itself, a share, adding up to 1, and takes in a blend of them.
- A token's vector in context
- Attention gives the same token a different vector in each sentence, made from the tokens around it.
- Every token at once
- Every token does attention in the same step, each with its own row of shares; a big share is not a reason.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Attention
Here's a puzzle. "Seal" can be an animal. It can also keep a box shut.
A model starts both kinds of seal from the same numbers. So how does it tell them apart?
Keep your guess
Here are two sentences. "The penguin swam away from the seal."
And "The box was closed with a seal."
In the first one, which word does "seal" take the most from?
"The", just before it?
"Penguin"? Or itself? Hold on to your guess.
It looks back
A model reads text as tokens, small pieces of text. It starts each token from its own row of numbers, its vector. And that row is the same in every sentence. Every one. So the difference has to come from the other tokens. Which ones can "seal" see?
The tokens before it, and itself. A chatbot's model writes one token after another. So it's built to never look ahead.
A share for each token
Here's one of this model's attentions, the one that shows it best.
"Seal" gives each token it can see a share. And the shares add up to one. People also call the shares attention weights. Your guess? "Penguin", which this model cuts into two tokens, gets more than half.
The word just before "seal" gets almost nothing.
It can reach any word before it. The first word is as easy to reach as the last.
Scores, then shares
Where do the shares come from? First, each token gets a score, of any size. Then softmax turns the scores into shares that add up to one. How a score is made is a lesson of its own.
A blend
So what does "seal" do with its shares?
It takes each token's vector, times its share. Then it adds them all up, number by number. That's a blend. Which vector will the blend look most like?
Penguin's.
Its share was more than half.
Then "seal" adds the blend to its own vector.
Now "seal" carries some penguin. That's attention.
The same token, a different vector
With attention, each token takes in a blend of the tokens before it. Now take the box sentence. Will "seal" come out with the same vector as in the penguin sentence?
It gives "box" and "closed" the same share, more than a third each. So its blend carries box and closed. This model does attention again and again, in twenty-eight layers, one after another. The two seals start the same: their cosine similarity is one. After seven layers, it's about two thirds. The same row went in, and two different vectors came out.
Every token at once
Every token takes in a blend like this. So does the model go one token at a time?
No. When the model reads a text, every token does it in the same step, each with its own row of shares. Look at "closed". It takes more than half of its share from "box". What was closed? The box. No token waits for another.
A share is not a reason
So is the biggest share always what a token needs most?
This model does attention sixteen times side by side, in each of its twenty-eight layers. Each one is called a head.
Let's look at another one. Spot the problem.
"Seal" gives "The" almost all of its share.
And in about two thirds of all the heads, "seal" gives "The" more than half.
"The" tells it nothing.
But the shares have to add up to one. So a head with nothing to find still puts its share somewhere: on the first token, which every token can see. The head we watched first, number sixteen, is one of the few that look for meaning.
So read a share as where the blend came from, never as the model's reason.
In code
Now in real code. Load the model, and tell it to calculate attention the plain way. Then it can hand back its shares. There are twenty-eight sets, one for each layer. Each one holds sixteen heads, with a row of shares for each of the sentence's ten tokens. Take the row of "seal" in the head we watched first. Code counts from zero, so each number on screen is one less than you'd count. The last share is zero: the period comes after "seal". What will the row add up to?
One.
You can use this to see where any token looked, in any layer and any head.
Just remember that a share isn't a reason.
Three ideas
So each token gives the tokens before it shares that add up to one, and takes in their blend. The same word gets a different vector in every sentence. And every token does it at once.
Each token takes what it needs
With attention, each token takes what it needs from the others. Now try it on this lesson's page, and take the quiz. Find who did the swimming.
You use this lesson in Lab 2: Attention, written by hand, after Queries, keys, values and heads.
Facts last checked on .
