Lesson 10.6 · 6 of 7 · 7 min read · Reviewed 24 Nov 2026
Lab: read an attention map
By the end, you can
- Read an attention map: rows, columns, the causal triangle and the strongest links.
- Recognise common head patterns such as previous-token, first-token and coreference.
- Say what an attention map can and can't tell you about why a model answered as it did.
An attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation. map is the weight table from lesson 10.1 drawn as a grid of shaded cells. Interpretability tools such as BertViz draw them for real models, and papers are full of them. This lesson teaches you to read one; the lab has you build one from scratch in plain Python and answer questions from it.
How to read the grid
- Rows are queries. Row it shows how the tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. it spread its attention.
- Columns are keys. Column parser shows how much each token looked at parser.
- Each row sums to 1, because of the softmax. A bright cell means a large share of that row’s attention.
- In a decoder, the top-right triangle is blank. That’s the causal mask: no token reads a later one.
- One map is one head in one layer. A model with 32 layers and 32 heads has 1,024 of them per prompt.
A worked example
Sentence: “The engineer fixed the parser because it crashed”. Here is one illustrative head’s row for it:
| Key | The | engineer | fixed | the | parser | because | it |
|---|---|---|---|---|---|---|---|
| Weight | 0.08 | 0.12 | 0.04 | 0.03 | 0.61 | 0.05 | 0.07 |
Reading it: this head links it mostly to parser (0.61), and a little to engineer. It behaves like a coreference head, and in this sentence it agrees with a human reading: the parser crashed. Change crashed to was tired and a good coreference head should shift its weight towards engineer.
Notice the weights are spread, not all-or-nothing. A weight of 0.61 says “mostly”, not “only”.
Patterns you will see
| Pattern | What it looks like | Common reading |
|---|---|---|
| Previous token | A bright line just below the diagonal | Copying and continuing local phrases |
| Self | A bright main diagonal | Keeping the token’s own information |
| First token | A bright first column | A resting place for spare attention, often called an attention sink |
| Long jump | A single bright cell far to the left | Linking a pronoun, a closing bracket or a repeated name to its earlier partner |
| Uniform | Every allowed cell roughly equal | Averaging the context, often in early layers |
The first-token pattern surprises people. Softmax forces every row to give out exactly 1 unit of attention. When nothing in the context is relevant to a head, it needs somewhere harmless to put that weight, and many models learn to use the first position.
What a map does not tell you
Attention weights show where a head read from. They don’t show what it did with that information, how later layers combined it, or whether the output would change if that link were removed. Researchers have shown that quite different attention patterns can produce the same prediction. So:
- Use maps to form hypotheses (“this head tracks pronouns”).
- Test them with interventions: change the input, or remove the head, and see whether the output changes.
- Don’t present an attention map as the reason a model gave an answer, especially to users or auditors.
Common mistakes
- Reading columns as rows. Always ask: which token is the query here?
- Judging a model from one head. Different heads in the same layer often disagree.
- Treating a bright first column as meaning. It is usually a sink, not a signal.
Key points
- Each row of an attention map is one token's query; each column is a key it could look at; each row adds up to 1.
- In a decoder the top-right triangle is empty, because tokens can't attend to later tokens.
- Common patterns include a bright diagonal just below the middle (previous token), a bright first column (a resting place), and long jumps such as a pronoun to its noun.
- Attention weights show where information was read from, in one head of one layer; they are not a full explanation of the output.
Read an attention map
Build a causal attention map for one sentence, draw it as text and answer questions from it.
You will have: A text heat map of one illustrative head and four checked readings: top key for it, row sums, the empty triangle and the sink.
Steps
- Run the starter and read the shaded grid: rows are queries, columns are keys.
- Fill in the top key for it from its row.
- Check that every row sums to 1 and that the upper triangle is empty.
- Average the first column to measure the attention sink.
- Remove the it-to-parser bonus in raw_score and see how the row for it changes.
Done when
- The top key for it is parser.
- Both checks print True.
- You can say why the first column is bright even though The carries little meaning.
Open in the Playground No API key needed.
Starter code (Python)
import math
TOKENS = ["The", "engineer", "fixed", "the", "parser", "because", "it", "crashed"]
N = len(TOKENS)
# Raw scores for one illustrative head: a pull towards the first token, a little self-attention,
# and a strong link from "it" to "parser".
def raw_score(i, j):
s = 1.5 if j == 0 else 0.0
if j == i:
s += 1.0
if TOKENS[i] == "it" and TOKENS[j] == "parser":
s += 3.0
if TOKENS[i] == "fixed" and TOKENS[j] == "engineer":
s += 2.5
return s
def attention_map(causal=True):
rows = []
for i in range(N):
scores = [raw_score(i, j) if (j <= i or not causal) else float("-inf") for j in range(N)]
m = max(scores)
e = [math.exp(s - m) for s in scores]
rows.append([x / sum(e) for x in e])
return rows
def shade(w):
return " .:-=+*#%@"[min(9, int(w * 10))]
A = attention_map()
print(" " + " ".join(t[:3].ljust(3) for t in TOKENS))
for t, row in zip(TOKENS, A):
print(f"{t[:8]:>8} " + " ".join(f" {shade(w)} " for w in row))
it = TOKENS.index("it")
# TODO 1: find the column with the largest weight in the row for "it".
top = 0
print(f"top key for 'it': {TOKENS[top]} ({A[it][top]:.2f})")
# TODO 2: check every row sums to 1 (allow a tiny rounding error).
print("rows sum to 1:", None)
# TODO 3: check every cell above the diagonal (j > i) is exactly 0.
print("upper triangle empty:", None)
# TODO 4: average the first column over rows 1 to N-1.
first_col = 0.0
print(f"average weight on the first token: {first_col:.2f} (a likely attention sink)")
Show a solution
import math
TOKENS = ["The", "engineer", "fixed", "the", "parser", "because", "it", "crashed"]
N = len(TOKENS)
# Raw scores for one illustrative head: a pull towards the first token, a little self-attention,
# and a strong link from "it" to "parser".
def raw_score(i, j):
s = 1.5 if j == 0 else 0.0
if j == i:
s += 1.0
if TOKENS[i] == "it" and TOKENS[j] == "parser":
s += 3.0
if TOKENS[i] == "fixed" and TOKENS[j] == "engineer":
s += 2.5
return s
def attention_map(causal=True):
rows = []
for i in range(N):
scores = [raw_score(i, j) if (j <= i or not causal) else float("-inf") for j in range(N)]
m = max(scores)
e = [math.exp(s - m) for s in scores]
rows.append([x / sum(e) for x in e])
return rows
def shade(w):
return " .:-=+*#%@"[min(9, int(w * 10))]
A = attention_map()
print(" " + " ".join(t[:3].ljust(3) for t in TOKENS))
for t, row in zip(TOKENS, A):
print(f"{t[:8]:>8} " + " ".join(f" {shade(w)} " for w in row))
it = TOKENS.index("it")
top = max(range(N), key=lambda j: A[it][j])
print(f"top key for 'it': {TOKENS[top]} ({A[it][top]:.2f})")
print("rows sum to 1:", all(abs(sum(r) - 1) < 1e-9 for r in A))
print("upper triangle empty:", all(A[i][j] == 0 for i in range(N) for j in range(i + 1, N)))
first_col = sum(r[0] for r in A[1:]) / (N - 1)
print(f"average weight on the first token: {first_col:.2f} (a likely attention sink)")