One attention head can only look for one thing. Give "chased" two heads, and one finds who did the chasing while the other finds who was chased.
AI · beginner · 8 min · 15 steps · free
What you'll learn
Explain why models use several attention heads
Run the same attention steps with different queries
Compare where each head focuses
multi_head.py
import math
# "The cat chased the mouse." The word "chased" asks two questions at once, one per attention head.
words = ["the", "cat", "the", "mouse"]
keys = [[0.0, 0.0], [2.0, 0.5], [0.0, 0.0], [0.5, 2.0]] # [is a doer, is a receiver]
queries = [[1.0, 0.0], [0.0, 1.0]] # head 0: who chased? head 1: chased whom?
for head, query in enumerate(queries):
scores = [query[0] * k[0] + query[1] * k[1] for k in keys]
powered = [math.exp(s) for s in scores]
weights = [round(p / sum(powered), 2) for p in powered]
print("head", head, weights)
Step by step
This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
The other words in "The cat chased the mouse", seen from the word "chased".
Each word's key, with two numbers: [is a doer, is a receiver]. "cat" is a doer, "mouse" a receiver, "the" neither.
Two queries, one per head. Head 0 asks "who chased?", head 1 asks "chased whom?".
Head 0 first.
Score each word: the query [1, 0] picks out the "doer" number. cat scores 2.
Softmax, step 1.
Head 0's weights: cat 0.67. This head has found who did the chasing.
It prints head 0 [0.09, 0.67, 0.09, 0.15].
Head 1: same words, same keys, a different query.
Now mouse scores 2 and cat 0.5.
powered now points to a different list: [1, 1.64872, 1, 7.38906].
Head 1's weights: mouse 0.67. Same sentence, a completely different focus.
It prints head 1 [0.09, 0.15, 0.09, 0.67].
Two heads, two answers: "chased" now knows both who chased (cat) and whom (mouse). A real model joins every head's mixed values side by side and passes them on. Large models have dozens of heads in every layer.
Common mistakes
Assuming every head has a neat human meaning: many learn patterns that are hard to name
Best practices
Read each head's weights separately; together they give a richer picture
Key takeaways
Each head runs attention with its own queries, keys and values.
Different heads can focus on different words for different reasons.
The heads' results are joined together and passed on.
More heads let the model track many kinds of links at once.
Check yourself
Two heads look at the same sentence. Will they always focus on the same word?
Answer: No: each has its own query, so each can look for something different. Here head 0 focused on "cat" and head 1 on "mouse".
What happens to the heads' results?
Answer: They are joined together and passed on. Every head contributes; the model learns how to use them all.