Attention
How does a word decide which other words to look at?
Lesson complete
If you like:
Read this sentence: “I sat on the bank of the river.” Here, a bank is the land along a river.
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain why a token needs to look at the others to make sense, and how attention decides whom to look at and how much.
- Compute by hand, with two-number vectors, a dot product, the attention weights with softmax, and the blend of values.
- Recognize what the formula softmax(QKᵀ/√d)V sums up, what several heads are for, and what all tokens at once gains and costs.
Key ideas
- A word can mean different things (“bank”), yet it enters the model with a single vector. To understand it you have to look at the others: that is what attention does.
- Each token produces a query (what it is looking for), a key (how it gets found), and a value (what it hands over). The dot product says how well a query and a key match.
- Softmax turns the scores into attention weights that add up to one hundred percent, and each token’s new vector is the blend of the values with those weights.
- It all sums up as softmax(QKᵀ/√d)·V. We divide by √d so that, with long vectors, softmax does not give all the weight to a single token.
- Several heads look at different things at once, and all tokens are computed at the same time: fast on a GPU, but the cost grows with the square of the text length.
What many people believe
Common belief An attention map shows why the model answered what it answered: what it “looked at” is its reason.
What is true It shows how one head, in one layer, spreads its weights. It is a clue about where information flows, but the answer depends on many heads and layers, and very different weights can give the same answer. Whether that counts as an explanation is still debated.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
The formula
For tokens, their queries and keys (with numbers) and their values (with ) are stacked into matrices and :
Row by row: the score of token on token is ; the weight is (each row adds up to 1) and the output is . This is the “scaled dot-product attention” of Vaswani et al. (2017), who describe attention as a function that maps a query and a set of key-value pairs to an output: a weighted sum of the values.
In the scene, the query of “bank” is and the key of “river” is : . The scores give , , , and ; the sum is , and the weights are , , , and . The scene does not divide by so the arithmetic can be followed in your head; with the division, the weights would be , , , and , and the new vector instead of : the same side, less pronounced. All the numbers in the example are written by hand (see data.ts).
Where Q, K, and V come from
If is the matrix of input vectors (embeddings; in a transformer, plus position), , , and . Those three matrices are the parameters that are learned; the weights are not: they are computed anew for each sentence. In self-attention, , , and all come from the same . In the attention of Bahdanau et al. (2014), built for translation, the queries came from the decoder and the keys and values from the encoder, and the score was a small network, , rather than a dot product; the weights were the same softmax and the result the same weighted sum . In the authors’ words, the decoder decides which parts of the source sentence to pay attention to.
Why
If the components of and are independent with mean 0 and variance 1, the product has mean 0 and variance (footnote 4 of Vaswani et al., 2017): its typical size is , eight when . Dividing by brings the variance back to 1. Without it, softmax saturates: if , then , which goes to 0 as one weight approaches 1 and the rest approach 0. That is the “slope that nearly vanishes” in the narration. With eight random keys and , the largest weight averages unscaled and scaled (100 draws; the scene’s draw gives and ).
Several heads
According to Vaswani et al. (2017), several heads let the model attend at once to information from different representation “subspaces”; with a single head, averaging inhibits this. In their base model, and , so eight heads cost about the same as one big one. BERT base has 12 layers of 12 heads (144) with 768 dimensions, that is, per head (Devlin et al., 2018).
The lesson’s real maps
They were computed with real-attention.py (in the lesson folder; it runs on a CPU): bert-base-uncased for English and bert-base-multilingual-cased for Spanish, both Apache-2.0 with a pinned revision. They are the weights of a single head after softmax, not averaged; the pieces of a word are added up. The “bank” head was chosen like this: among the heads in which the largest weight of “bank” falls on the word that decides its meaning in both sentences (river and money), the one with the largest sum of those two weights. Only 6 of 144 heads meet that condition in English (layer 3, head 11: 93% and 60%) and 4 of 144 in Spanish (layer 1, head 4: 44% and 65%). By contrast, the largest weight of “bank” falls on a mark ([CLS], [SEP], or the period) in 113 of 144 heads in English and 58 of 144 in Spanish. The other three are the heads with the largest average weight on the previous word, on the next word, and on the marks. Clark et al. (2019) describe these same kinds of heads in BERT: heads that attend to delimiter tokens, to a fixed positional offset, and broadly over the whole sentence.
Cost
The weight matrix is : the compute per layer grows as . A recurrent layer costs , but it needs steps one after another, and information between two positions travels a path of length ; in self-attention both are (Table 1 of Vaswani et al., 2017). That is why attention makes good use of a GPU, and why long contexts are expensive.
In code
import numpy as np
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def attention(Q, K, V, scale=True):
d = K.shape[-1]
scores = Q @ K.T # dot products: how well each query matches each key
if scale:
scores = scores / np.sqrt(d) # the piece the scene leaves for the end
weights = softmax(scores) # each row adds up to 1
return weights @ V, weights # weighted blend of the values
# "I sat on the bank of the river": the scene's numbers (d = 2)
K = np.array([[-1.6, 0], [-0.3, 1], [-0.8, -0.8], [-0.8, -0.8],
[0.5, -0.5], [-0.8, -0.8], [-0.8, -0.8], [1, 0.8]])
V = np.array([[0, 0], [0.5, 0], [0, 0], [0, 0],
[0.5, 0.5], [0, 0], [0, 0], [1, 0]]) # (riverbank, money)
q = np.array([[1.0, 1.0]]) # the query of "bank"
out, w = attention(q, K, V, scale=False)
print(np.round(w, 2), np.round(out, 2))
out, w = attention(q, K, V) # with the division by √2
print(np.round(w, 2), np.round(out, 2))
# [[0.02 0.2 0.02 0.02 0.1 0.02 0.02 0.6 ]] [[0.75 0.05]]
# [[0.04 0.21 0.04 0.04 0.13 0.04 0.04 0.46]] [[0.63 0.06]]
And the check of : the standard deviation of grows as ; after dividing, it stays at 1.
rng = np.random.default_rng(0)
for d in (1, 2, 64, 512):
q = rng.standard_normal((20000, d))
k = rng.standard_normal((20000, d))
s = (q * k).sum(axis=1) # 20,000 dot products q·k
print(d, round(s.std(), 1), round((s / np.sqrt(d)).std(), 2))
# 1 1.0 1.0
# 2 1.4 1.0
# 64 8.0 1.0
# 512 22.6 1.0
What comes next
What attention alone does not do: it does not know word order (shuffle the words and each token spreads the same weights over the same tokens), and when writing text each token may only look back ( is placed on the scores that look at the future, before the softmax). With a position encoding, that mask, a network per token, residual connections, and normalization, blocks are stacked: the transformer, in lesson 22.
Decision lens
What this idea means if your job is to decide, not to code.
- Every token is compared with all the others: the cost of attention grows with the square of the context. Doubling the text costs about four times as many comparisons; it is one of the reasons long contexts are expensive (lessons 26 and 30).
- An attention map is not an explanation. If a vendor shows “what the model looked at” as the justification for an answer, also ask for tests with your own cases and quality measures (lessons 33 and 34).
- Everything in the context can influence everything else: the architecture does not tell your instruction apart from a stranger’s document on its own. Hence the risk of prompt injection: separate and validate what comes in (lesson 35).
- More context does not guarantee more understanding: with more tokens, attention spreads across more candidates. Test with your own long documents and do not assume the model uses everything equally (lesson 30).
Terms in this lesson
- Token A piece of text (a word, a word fragment, a symbol, or a basic code) taken from the vocabulary. It is the unit the model reads and generates, and the unit you are billed for.
- Embedding A vector of numbers, learned from data, that represents something (a word, a sentence, an image) so that similar things end up close. Each word has a row in an embedding table.
- Vector An ordered list of numbers. In machine learning, each example reaches the model as a vector.
- Cosine similarity The cosine of the angle between two vectors: 1 if they point the same way, 0 if they are perpendicular, −1 if they oppose. It ignores length and measures direction only.
- Softmax A function that turns any scores into positive probabilities that add up to one: it applies the exponential to each score and divides by the sum.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Layer A group of neurons that receive the same inputs and compute at the same time. A network is a chain of layers: input, one or more hidden ones, and output.
- Gradient The list of the slopes of the error, one for each weight. Seen as an arrow, it points to where the error rises fastest.
- Recurrent neural network (RNN) A network that processes a sequence step by step with the same cell: at each step it receives the current input and the previous hidden state, and produces a new state.
- GPU Graphics processing unit: a chip with hundreds or thousands of simple cores, built to draw graphics and very efficient at multiplying matrices in parallel, the central operation of training.
- Attention A mechanism by which each token decides how much to look at the others: it compares its query with everyone’s keys, turns the scores into weights with softmax, and builds its new vector as the blend of the values with those weights.
- Query, key, and value (Q, K, V) The three vectors each token produces: the query says what it is looking for, the key how it gets found, and the value what it hands over. They come from multiplying its vector by three learned weight matrices.
- Self-attention Attention in which queries, keys, and values come from the same sequence: each token looks at the other tokens of its own text, and at itself.
- Multi-head attention Several attentions in parallel, each one (a head) with its own matrices for Q, K, and V and its own map. Their results are joined and combined with a final matrix.
Full transcript
Sources
- Bahdanau, D., Cho, K., Bengio, Y. (2014). Neural Machine Translation by Jointly Learning to Align and Translate
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., Polosukhin, I. (2017). Attention Is All You Need
- Devlin, J., Chang, M.-W., Lee, K., Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
- Google; Hugging Face (2018). bert-base-uncased (ficha del modelo; Apache-2.0)
- Google; Hugging Face (2018). bert-base-multilingual-cased (ficha del modelo; Apache-2.0)
- Clark, K., Khandelwal, U., Levy, O., Manning, C. D. (2019). What Does BERT Look At? An Analysis of BERT’s Attention
- Jain, S., Wallace, B. C. (2019). Attention is not Explanation
- Wiegreffe, S., Pinter, Y. (2019). Attention is not not Explanation
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub