Self-Attention, Intuitively
Introduction
Read this sentence, the one Google used in 2017 to show what its new Transformer could do: "The animal didn't cross the street because it was too tired."
You know at once that "it" is the animal. Change "tired" to "wide" and "it" becomes the street. Notice where the answer comes from: a word that arrives after "it".
Self-attention is how a transformer lets each token pull in what it needs from the other tokens. It is the mixing step inside every block of The Transformer Architecture — The Big Picture, and the only step where tokens see each other at all: the feed-forward network after it is, in the 2017 paper's words, "applied to each position separately and identically".
You'll learn:
- why a token's new vector is a weighted blend of the vectors of the tokens it can see
- the query, key and value each token makes, and the three moves of one attention head
- what a model that reads left to right can and cannot see, with the real weights of a real model
- how to read an attention map, and why real heads look stranger than the textbook picture
- the whole mechanism in a short numpy file you can run
The Core Idea: A Weighted Blend
Each token enters a block as a vector of numbers (Embeddings: Meaning as Vectors is about those vectors). On its own, the vector for "it" says nothing about which noun it stands for.
Attention replaces each token's vector with a weighted blend of vectors from the tokens it may see, with more weight on the ones that matter to it. Every weight is between 0 and 1, and a token's weights add up to 1, so the blend is an average with uneven shares. In the real head followed below, "tired" takes 0.35 of its blend from "too", 0.24 from itself and 0.22 from "it", and smaller shares from the rest. Nothing is picked outright.
So the whole job comes down to one question, asked for every token at once: how much should I take from each token I can see? The rest of the page is how a transformer answers it.
Query, Key, Value: A Soft Database Lookup
The weights come from a lookup. The 2017 paper defines attention as "mapping a query and a set of key-value pairs to an output", and the textbook Dive into Deep Learning makes the comparison outright: "Compare this to databases." A database holds keys with their values, and an exact query finds one key and returns its value. Attention does the same softly: the query is compared with every key, and what comes back is a blend of all the values, weighted by how well each key matched. As the book says, "The same query can receive different answers, according to the contents of the database."
Each token makes three vectors from its own vector, each with its own matrix that the model learned in training. Jurafsky and Martin name the three roles in a model that reads left to right:
- Query: the token as "the current element being compared to the preceding inputs". What it looks for.
- Key: each token as "a preceding input that is being compared to the current element to determine a similarity weight". What it offers.
- Value: "a value of a preceding element that gets weighted and summed up to compute the output for the current element". What it hands over.
One attention head makes three moves for each token:
- Compare. The token's query meets every key it may see. Their dot product, divided by the square root of the vectors' size, is a score.
- Weigh. Softmax turns the row of scores into weights between 0 and 1 that add up to 1. Only the differences between scores matter: the highest score gets the most weight, whatever its sign.
- Blend. Each value is multiplied by its weight, and the results are added up. That sum is the token's new vector from this head.

The figure follows one real head of Whisper base.en's decoder (block 3, head 4) looking up from "tired". Every one of its scores is below zero, from minus 12.6 to minus 3.1, and softmax does not mind: "too" gets 0.35, "tired" itself 0.24, "it" 0.22 and "was" 0.14, every other word less than 0.01.
It Only Looks Backward (Causal Attention)
A language model writes one token at a time, each from the tokens before it (Language Models 101: Predicting the Next Token). In training it must never learn from a peek at the answer. The 2017 paper puts it plainly: "We need to prevent leftward information flow in the decoder to preserve the auto-regressive property."
The fix is a mask. Before softmax, the score for every later token is set to minus infinity, so its weight comes out exactly 0. In Jurafsky and Martin's words, those are the scores "which the softmax will turn to zero, thus eliminating any knowledge of words that follow in the sequence". A token sees itself and every token before it, and nothing after.
The mask is also why a whole sentence trains at once. Every position gets its own row with its own mask, so each one is a separate guess at the next token: "the use of the mask is what lets every position in the window serve as a training example".
Worked Example: What Can "it" See?
Go back to the sentence. Jurafsky and Martin read the same kind of sentence left to right, as a language model does, and stop at "it": "At this point we don't yet know which thing it is going to end up referring to!" At "it", the words "was too tired" have not come yet, so "it" cannot ask which noun was tired. The word that settles it is the later one, and it does so by looking back.
The famous picture of "it" lined up with "animal" came from a different kind of model. Google's post showed one head of a translator's encoder, "an encoder reading the input sentence and generating a representation of it", which reads the whole sentence before any French is written. There the translation of "it" "depends on the gender of the noun it refers to", and the encoder's lines from "it" go to "animal", to "street", and even to the closing full stop, which comes after "it".
Here is what a decoder does with the same sentence. Whisper base.en's decoder, the one The Transformer Architecture — The Big Picture ran from its released weights, wrote the sentence down word for word from a recording of it read aloud, and every one of its 48 heads was read out at every token. From "it", no head gives "animal" more than 0.09. Later, "tired" weighs "animal" above every other word before it in 8 of the 48 heads, though with no more than 0.06 in any of them. In this small model, no head draws the textbook line.
Two cautions keep that honest. This decoder only has to write down what it hears, and writing "it" down does not need to settle what "it" refers to. And text models do grow such heads: in BERT, an encoder that reads both ways, Clark and colleagues found that "certain attention heads correspond well to linguistic notions of syntax and coreference", one of them linking a word to the word it refers to with "65.1% accuracy".

Seeing It All at Once: The Attention Map
Following one token is one row. Stack every token's row and you have an attention map: a row for each token as it looks back, a column for each token it may look at, and a cell as dark as its weight. Every row adds up to 1, and the triangle above the diagonal holds nothing: that is the mask, drawn.
The figure shows four of the decoder's 48 heads on the same sentence, each with a habit you can see at a glance. One looks one word back (0.50 of a word's weight on the word before, on average); in it, the row of "it" puts 0.82 on "because". One parks nearly everything on the first token (0.99). One mostly looks at the token itself (0.70). One spreads its weight thin.
The parking habit is everywhere. In 32 of the 48 heads, the two marks the transcriber writes before any word take more than half of a word's weight on average. Xiao and colleagues found the same in large language models: "a surprisingly large amount of attention score is allocated to the initial tokens, irrespective of their relevance to the language modeling task". They named such tokens attention sinks. In this decoder the start mark's value is shorter than the words' values in 45 of the 48 heads, so weight parked on it adds little to the blend. Clark and colleagues saw the same habits in BERT: "attending to delimiter tokens, specific positional offsets, or broadly attending over the whole sentence".

The Whole Thing in a Few Lines
Here is one head with its mask, in numpy. The vectors and matrices are random; in a trained model the matrices are learned and the vectors come from the layers below.
import numpy as np
np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(7)
words = ["The", "animal", "was", "tired"]
x = rng.normal(size=(4, 8)) # one vector per word, made up here
# three matrices that a real model learns; made up here too
Wq, Wk, Wv = (rng.normal(size=(8, 8)) / 8**0.5 for _ in range(3))
def softmax(s):
e = np.exp(s - s.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def self_attention(x):
q, k, v = x @ Wq, x @ Wk, x @ Wv # each word's query, key and value
scores = q @ k.T / np.sqrt(k.shape[-1]) # every query against every key
later = np.triu(np.ones((len(x), len(x)), dtype=bool), k=1)
scores[later] = -np.inf # the mask: no word sees a word after it
weights = softmax(scores) # each row adds up to 1
return weights @ v, weights # the values, blended by the weights
new, weights = self_attention(x)
for word, row in zip(words, weights):
print(f"{word:>6}", row)
print("each row adds up to", weights.sum(axis=1))
print("new vectors:", new.shape)Its run, on Python 3.14.7 with numpy 2.4.4 and 2.4.3 alike:
The [1. 0. 0. 0.]
animal [0.49 0.51 0. 0. ]
was [0.22 0.21 0.57 0. ]
tired [0.2 0.14 0.44 0.22]
each row adds up to [1. 1. 1. 1.]
new vectors: (4, 8)The first row has only itself to see, so its weight is 1. Every row stops at the diagonal, the mask at work, and every row adds up to 1. The vectors are made up, so which word gets the most means nothing here.
The famous formula is the same three moves: softmax(Q K^T / sqrt(d)) V. The paper gives the reason for the square root: as the vectors grow, "the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients", where training barely moves the weights. Dividing by the square root of the size keeps the scores in a range softmax handles; for Whisper's heads of 64 numbers, it divides by 8.
See It: Look Up Through a Head
Make the three moves yourself, on the same real decoder and the same sentence. Pick any token by its dot, and any of the 6 blocks and 8 heads. Compare draws a line from the query to every token it may see, with a score bar beside each, while the tokens after it lie under the hatched mask; Weigh turns the scores into weights; Blend sends each value up into the new vector, as strong as its weight. The grid of all 48 heads shows, for your token, how much of its weight each head parks on the start marks.

Why This Is So Powerful
Two properties come straight from this design.
- Every token reaches every earlier token in one step. The 2017 paper's Table 1 gives the longest path between two positions as constant for self-attention, against one that grows with the sentence's length for a recurrent layer, which passes information along one word at a time.
- The rows are worked out together. In training, every row of the map comes out of the same few matrix products, so a whole sentence is one batch of work. When a model writes, it still adds one token at a time, and each new token is one new row.
And the weights come from the tokens themselves. The same head gives different weights to different sentences, because the scores are computed from the tokens' own queries and keys, not set in advance for each position.
Check Yourself
Six questions on the moves, the mask and what real heads do.
Check yourself: self-attention
1 / 6Multiple choice
Multiple choice
Multiple choice
Multiple choice
Multiple choice
Multiple choice
Mental-Model Corrections
- A soft blend, not a hard pick. Even the strongest weight in the figure's head is 0.35; the rest of the new vector comes from other tokens.
- Q, K and V are learned, not designed. Each is the token's vector times a matrix fixed in training.
- A map shows where a head looked, not why the model wrote a word. In the decoder above, most heads give most of a word's weight to the start marks, which say nothing about the sentence.
- One head, one pattern; a block has several. Whisper base.en's decoder has 8 heads in each block, each with its own matrices. The paper's reason: "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions."
- "Attention" is not human attention. It is a weighted average, its weights computed with learned matrices.
Key Takeaways
- Self-attention rebuilds each token's vector as a weighted blend of the values of the tokens it can see.
- One head makes three moves: compare the query with every key, weigh the scores with softmax, blend the values. The formula
softmax(Q K^T / sqrt(d)) Vis those three moves. - In a language model attention is causal: a mask zeroes every later token, so a token can only use the tokens before it, and a word that settles an earlier one has to look back to it.
- Real heads have plain habits: the start mark, the word before, themselves, everything a little.
- Every token reaches every earlier one in one step, and the rows are worked out together in training.
Next: Multi-Head Attention & Positional Encoding. Why a block runs many heads side by side, and how the model knows the order of the tokens at all: a blend is a weighted sum, and a sum does not care in what order its parts come.