Attention, explained
Read this sentence: “the bank of the river was full of mud”. Now this one: “the bank has closed my account”. The word bank is identical, letter for letter, yet none of us pictures a cash desk in the first sentence or a riverside in the second. Meaning does not live in the word alone: it lives in the words around it.
In the previous part we saw that an LLM does nothing more than guess the next token. To do that well it has to understand the context, and this is where the mechanism that has transformed language processing in recent years comes in: attention. In this article we look at what it computes, with an example you can explore hands-on and about fifteen lines of Python.
The problem: meaning depends on the other words
A classic embedding, like those of word2vec, gives each token a fixed vector. But bank has a single vector, which somehow has to hold both money and rivers. We need one more step: a way to update the vector of each word by blending it with information from the nearby words that matter.
Pronouns make the point even clearer. Take “the cat didn’t climb the table because it was too tired”. Who was tired? The cat. Change a single word: “…because it was too tall”. Now the one that is tall is the table. The structure of the sentence is the same: what decides the link is the meaning of an adjective several words further on.
Before Transformers, this job was done by recurrent networks, which read the sentence one word at a time and carry forward an internal state, a kind of running summary. They work, but everything has to pass through that summary: in long sentences distant information fades, and reading in sequence makes it hard to take full advantage of parallel computation. If you want to dig deeper, recurrent networks are the subject of chapter 8 of my book Deep Learning con Keras e Tensorflow (in Italian).
The idea: every word asks all the others a question
Attention was born in 2014 with the work of Bahdanau and colleagues on machine translation: while the model writes a word of the translation, it can “look at” the words of the original sentence that are most useful at that moment. In 2017 the paper Attention Is All You Need (Vaswani et al.) took the decisive step: it dropped recurrence altogether and built the Transformer on self-attention alone, the attention of a sentence towards itself.
The mechanism uses three vectors for each token, obtained by multiplying its embedding by three weight matrices, Wq, Wk and Wv:
- query (q): what I am looking for;
- key (k): what I offer, the label I present myself with;
- value (v): the information I pass on to whoever picks me.
Think of a library. The query is the question in your head (“I need something about rivers”), the keys are the labels on the books’ spines, the values are the books’ contents. You don’t take just one book: you leaf through several, spending more time on those whose label best matches your question.
In formulas, for every pair of tokens the calculation goes like this:
- the score is the dot product q·k: high when the question and the label “point” in the same direction;
- the score is divided by √d, the square root of the vectors’ dimension, because with long vectors dot products grow and would make the softmax too sharp;
- the softmax turns the scores of a row into positive weights that add up to 1;
- the output is the weighted sum of the values: each word receives a new vector, made mostly of the information from the words it looked at most.
In the river sentence, the query of bank matches well with the keys of river and mud; its new vector therefore shifts towards the meaning “riverside”. In the account sentence the same thing happens, but towards money.
More heads, more kinds of relation
A single attention looks for a single kind of similarity. That is why Transformers use multi-head attention: several attentions in parallel, each with its own Wq, Wk, Wv matrices. Studying trained models, researchers find heads that mostly look at the previous word, heads that link a verb to its subject, heads that tie a pronoun to the noun it refers to. Nobody programs them: they emerge from training. The heads’ outputs are then concatenated and remixed by another matrix.
No peeking at the future, and the cost is quadratic
A language model that guesses the next token must not cheat: while it processes word number 5 it must not see word 6. So a causal mask is used: before the softmax, the scores towards future tokens are set to minus infinity, so their weight becomes zero and the remaining weights are renormalised. In the attention matrix, the half above the diagonal goes dark.
Then there is a price. Each token is compared with all the others, so with n tokens you need n × n scores: double the length of the text and the attention work quadruples. This is one of the main reasons why a model’s context window is limited, and why a lot of research goes into more efficient forms of attention.
The demo
The demo below shows the mechanism on short sentences. Tap or hover over a word: the arcs show how much that word “looks at” each of the others, with the percentage written underneath. Below you will find the full matrix, the numbers for the selected row (score, division by √d, softmax) and the output vector. It is a toy model: vectors and matrices are written by hand to make the idea visible, whereas in a real Transformer they are learned.
What to try in the demo
- With head 2 (meaning), compare “bank” in the river sentence and in the account sentence: the words it looks at change, and so does its output vector.
- In the two cat sentences, select “tired” and then “tall”: the first links to “cat”, the second to “table”.
- Switch to head 1: the diagonal just below the main one lights up, because each word looks at the previous one.
- Turn on the causal mask: the upper triangle goes dark and the first word can only look at itself.
- Move the temperature: low values make the softmax sharp (almost everything on one word), high values make it flat.
- Type your own sentence: words the lexicon doesn’t know get a pseudo-random vector, marked with an asterisk.
In Python
Here is scaled dot-product attention in NumPy, with random embeddings for four tokens and an optional causal mask:
import numpy as np
rng = np.random.default_rng(0)
d = 8 # vector dimension
X = rng.normal(size=(4, d)) # random embeddings for 4 tokens
W_q, W_k, W_v = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))
def attention(X, causal=False):
Q, K, V = X @ W_q, X @ W_k, X @ W_v
scores = Q @ K.T / np.sqrt(d) # every query compared with every key
if causal: # no looking at future tokens
future = np.triu(np.ones(scores.shape, dtype=bool), k=1)
scores = np.where(future, -np.inf, scores)
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True) # row-wise softmax
return weights @ V, weights
output, weights = attention(X, causal=True)
print(np.round(weights, 2))
print(output.shape)
The program prints a 4 × 4 matrix of weights: each row adds up to 1, above the diagonal there are only zeros and the first row is entirely on the first token, the only one it can see. The last line prints (4, 8): a new vector for each token. Try causal=False to see the full matrix.
What we take away
Attention is, at heart, a weighted average whose weights are decided by the content: each word chooses who to be influenced by. To me, it is precisely this simplicity that makes it so powerful, because the same calculation, repeated with many heads and over many layers, is enough to capture syntax, references and meaning. In the next part, the Transformer and training, we will see how attention combines with the other pieces of the Transformer and how the model learns its matrices by reading huge amounts of text.