Skip to content
LearnAI

2.5Self-attention step by step

The mechanism at the heart of every Transformer, computed by hand. Queries, keys, values, scaling, masking and softmax, with every number visible.

⏱ 16 minIntermediate

What does “it” refer to?

Read this sentence: The cat sat on the mat because it was tired. You know instantly that it is the cat, not the mat. Mats don’t get tired. Now change one word: The cat sat on the mat because it was warm. Suddenly it is probably the mat.

A language model faces this problem at every token. The embedding of it is the same in both sentences, but to predict what comes next, the model needs a version of it that knows what it refers to. The previous lesson showed why squeezing the past through an RNN’s hidden state makes this hard. Self-attentionSelf-attentionAttention in which the queries, keys and values all come from the same sequence. solves it directly: each token gets to look at the other tokens, decide which ones are relevant, and pull information from them into its own vector.

This lesson computes one attention layer completely by hand, on that exact sentence, with vectors small enough that you can read every number.

ANALOGY· A library with a very fuzzy catalog

You walk into a library with a question scribbled on a card: “something about an animal”. That card is your query. Every book has a label on its spine summarizing what it’s about: those are the keys. Inside each book is its actual content: the value.

A normal library returns the one book whose label matches exactly. This fuzzy library compares your card with every label, gives each book a relevance score, and hands you a blended summary: 60% from the best-matching book, 10% from the next, and a sliver from everything else. The relevance scores are the attention weights, and the blended summary is the output. In self-attention, every word in the sentence is simultaneously a reader with a question and a book on the shelf.

Three roles for every token

Each token starts as an embedding vector xix_i. Self-attention multiplies it by three learned matrices to get three new vectors. Together they’re called queries, keys and valuesQuery, key, value (Q/K/V)Three learned projections of each token. A query is compared with keys to get attention weights, which then mix the values.:

  • Query qi=xiWQq_i = x_i W_Q: what this token is looking for. For a pronoun, roughly “an earlier noun that could be my referent”.
  • Key ki=xiWKk_i = x_i W_K: what this token advertises about itself, so that queries can find it. For cat, roughly “I’m an animate noun”.
  • Value vi=xiWVv_i = x_i W_V: the information this token hands over if someone attends to it.

Why three separate vectors instead of just comparing embeddings directly? Because “what I’m looking for” and “what I am” are different things. A pronoun is not similar to a noun; it’s looking for one. Separate query and key projections let the model learn asymmetric relationships like that. And separating the value lets a token be found for one reason but pass on something else.

Then the recipe:

  1. Score. For each pair of tokens, take the dot productDot productMultiply two vectors element by element and add up the results. It is large when the vectors point in similar directions. qi⋅kjq_i \cdot k_j. A large score means token jj matches what token ii is looking for.
  2. Scale. Divide by dk\sqrt{d_k}, where dkd_k is the length of the key vectors (explained below).
  3. Mask. In a language model, set the scores for future tokens to −∞-\infty so nothing can peek ahead.
  4. Softmax. Turn each row of scores into positive weights that sum to 1, using the softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total.. These are the attention weightsAttention weightsThe softmax-normalized scores saying how much each token draws from every other token. Each row sums to 1..
  5. Mix. Each token’s output is the weighted average of all the value vectors, using its row of weights.

That’s the whole thing. Step through it below. The embeddings and the three weight matrices were designed by hand, with 4 dimensions each that have readable meanings (animate, thing, pronoun, action), so you can check every number. In a trained model, nobody chooses them: they are learned by gradient descent, and the dimensions don’t come with labels.

INTERACTIVESelf-attention, one matrix at a time
1/7 · embeddings X
Hover or tap a row to follow one token. Following: “it”
1. Start with one embedding per token

Each token arrives as a vector. In this toy, the 4 dimensions have readable meanings (animate, thing, pronoun, action); in a real model there are thousands and they are not human-labeled. “it” = (0.2, 0.2, 1, 0).

X (10 tokens × d=4 features)
animatethingpronounaction
The0.10.10.00.0
cat1.00.20.00.0
sat0.10.00.01.0
on0.00.30.00.1
the0.10.10.00.0
mat0.01.00.00.0
because0.00.00.10.3
it0.20.21.00.0
was0.00.00.20.8
tired0.30.00.00.9
Step through the seven stages of one attention head. Hover or tap any row to follow that token through the computation; the bold, outlined cell is where it attends most. Try following “it”, then “sat”, then switch the causal mask off.

Things to notice as you step through:

  1. Stage 2. The query for it has a big first component (5.00), because WQW_Q maps the pronoun feature to “looking for animate”. Only cat (and, weakly, tired and it itself) has a large key in that slot.
  2. Stage 3. The scores row for it has its peak at cat (5.22). mat scores 1.10: a thing, but not animate.
  3. Stage 6. After the softmax, it sends 58% of its attention to cat. Every row sums to 1.
  4. Stage 7. The output for it has absorbed cat’s value vector. Its “animate” component jumps from 0.20 to about 0.61. The next layer receives an it that carries cat-information.

Why divide by √d?

The dot product of two random vectors grows with their length. If each component of qq and kk has mean 0 and variance 1, then q⋅kq \cdot k is a sum of dkd_k such products and has variance dkd_k. With dk=128d_k = 128, a typical head size, scores routinely land in the ±20 range. Fed into a softmax, scores that spread out produce a nearly one-hot distribution: one weight close to 1 and the rest close to 0. The softmax is then saturated, its gradients are tiny, and learning stalls.

Dividing by dk\sqrt{d_k} brings the variance back to 1, whatever the head size. It is a small fix, but the original Transformer paper called it out explicitly, and it’s why the formula is called scaled dot-product attentionScaled dot-product attentionAttention(Q, K, V) = softmax(QKᵀ/√d_k)·V: compare queries with keys, normalize, and take a weighted average of values..

The causal mask: no peeking

GPT-style models are trained to predict each next token. During training, the model processes a whole passage at once, making a prediction at every position in parallel (see next-token prediction). If token 5 could attend to token 6, predicting token 6 would be trivial: just copy it. So we apply a causal maskCausal maskA mask that stops each token from attending to later tokens, so the model can't peek at the future during training.: before the softmax, every score where the key comes after the query is set to −∞-\infty. Since e−∞=0e^{-\infty} = 0, those weights become exactly zero. The result is a lower-triangular attention matrix: row 1 can only see token 1, row 10 can see everything.

Encoder models like BERT, which are not trained to generate left to right, skip the mask and let every token see the whole input. That’s the toggle in both demos.

The attention pattern as a picture

The matrix of attention weights is easiest to read as a heatmap: one row per token doing the looking (the query), one column per token being looked at (the key). Each row is a probability distribution.

INTERACTIVEAttention heatmap
ThecatsatonthematbecauseitwastiredThecatsatonthematbecauseit658656748wastired
Where “it” looks (row 8, query) — hover or tap rows of the heatmap
top key
“cat” 58%
visible keys
8
entropy
2.16 / 3.00 bits

Low τ sharpens each row toward a single key (low entropy); high τ flattens it toward a uniform average (entropy near the maximum). Turn the mask off and early tokens can suddenly see later ones: “The” now looks ahead.

Each row shows where one token looks; darker means more weight. Hover or tap a row to inspect it. Toggle the causal mask, and drag the temperature: low τ makes attention sharp and decisive, high τ blurs it into a plain average.

Things to try:

  1. Row it, τ = 1. One dominant column, cat. The entropy readout is well below its maximum.
  2. τ → 0.25. Every row sharpens. it now puts almost everything on cat. This is what unscaled attention with large dimensions does all the time, and it’s too decisive to learn well.
  3. τ → 4. Rows approach uniform averages, and the entropy approaches its maximum. Attention that looks everywhere equally carries almost no information about which token matters.
  4. Mask off. The upper triangle fills in. The at position 1, which could previously only see itself, now spreads its attention across the whole sentence, including words that come after it. A left-to-right language model must never have that information.

Where this sits inside a Transformer

Our demo has one head with d=4d = 4. Real models are the same computation at a larger size. GPT-2 small, for instance, has 12 layers, each with 12 attention heads, and each head works with 64-dimensional queries, keys and values carved out of the 768-dimensional token vectors. The heads run side by side, their outputs are concatenated and projected back to 768 dimensions, and the result is added to the token’s vector rather than replacing it. That addition (a residual connectionResidual connectionAdding a layer's input to its output (x + f(x)). This creates a 'residual stream' and makes very deep networks trainable.) means attention contributes information to each token instead of overwriting it, so it keeps knowing that it is a pronoun while also gaining cat-information.

After attention comes a small feed-forward network (an MLPMLP (feed-forward network)A multi-layer perceptron: linear layers with nonlinear activations between them. Each Transformer block contains one.) applied to each token separately. A useful slogan: attention moves information between tokens; the MLP processes information within a token. Stack dozens of these layers and the vector at each position becomes an increasingly rich, context-aware description of that token, until the final layer turns the last position’s vector into next-token logits. The Transformer walkthrough follows one token through the whole stack.

Two more properties worth knowing. First, attention by itself has no sense of order: shuffle the tokens and each one gets the same output, just shuffled, because a weighted sum doesn’t care where things are. Position must be injected separately, which the positional encoding lesson covers. Second, the score matrix is n×nn \times n for nn tokens. Double the context, and you quadruple the work and memory for this step. That quadratic cost shapes everything from context-window limits to the KV cache.

MATH CORNER · optionalAttention(Q, K, V) = softmax(QKᵀ/√dₖ)V, fully worked

Stack the token vectors as rows: X∈Rn×dX \in \mathbb{R}^{n \times d}. With learned WQ,WK∈Rd×dkW_Q, W_K \in \mathbb{R}^{d \times d_k} and WV∈Rd×dvW_V \in \mathbb{R}^{d \times d_v},

Q=XWQ,K=XWK,V=XWV,Q = XW_Q, \quad K = XW_K, \quad V = XW_V ,Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V,\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V ,

where the softmax is applied to each row and MM is the mask (Mij=−∞M_{ij} = -\infty if j>ij > i, else 0). Row ii of the output is yi=∑jαijvjy_i = \sum_j \alpha_{ij} v_j with αij=exp⁡(sij)∑j′exp⁡(sij′)\alpha_{ij} = \dfrac{\exp(s_{ij})}{\sum_{j'} \exp(s_{ij'})}.

Why dk\sqrt{d_k}: if the components of qq and kk are independent with mean 0 and variance 1, then Var⁡(q⋅k)=∑m=1dkVar⁡(qmkm)=dk\operatorname{Var}(q \cdot k) = \sum_{m=1}^{d_k} \operatorname{Var}(q_m k_m) = d_k, so q⋅k/dkq \cdot k / \sqrt{d_k} has variance 1.

A 3-token example with dk=2d_k = 2 (so dk≈1.414\sqrt{d_k} \approx 1.414). Tokens cat, sat, it, with queries, keys and values given directly:

tokenqqkkvv
cat(0, 2)(2, 0)(1, 0)
sat(2, 0)(0, 1)(0, 1)
it(2, 0)(1, 1)(0.5, 0.5)

Scores QK⊤QK^\top (row = query, column = key): cat row (0,2,2)(0, 2, 2); sat row (4,0,2)(4, 0, 2); it row (4,0,2)(4, 0, 2). For example, qit⋅kcat=2⋅2+0⋅0=4q_{\text{it}} \cdot k_{\text{cat}} = 2 \cdot 2 + 0 \cdot 0 = 4.

Scale by 1/1.4141/1.414, then mask the future:

querykey: catkey: satkey: it
cat0.000−∞−∞
sat2.8280.000−∞
it2.8280.0001.414

Softmax each row. For it: e2.828=16.91e^{2.828} = 16.91, e0=1e^{0} = 1, e1.414=4.11e^{1.414} = 4.11, which sum to 22.0222.02, giving weights (0.768, 0.045, 0.187)(0.768,\ 0.045,\ 0.187). The sat row gives (0.944, 0.056, 0)(0.944,\ 0.056,\ 0), and cat can only see itself: (1,0,0)(1, 0, 0).

Mix the values. For it:

yit=0.768 (1,0)+0.045 (0,1)+0.187 (0.5,0.5)=(0.861, 0.139).y_{\text{it}} = 0.768\,(1, 0) + 0.045\,(0, 1) + 0.187\,(0.5, 0.5) = (0.861,\ 0.139) .

The output for it is now mostly cat’s value. Notice also that sat attends 94% to cat: a verb finding its subject.

In code

Single-head causal self-attention from scratch, in about fifteen lines of PyTorch:

import math
import torch

def self_attention(x, W_q, W_k, W_v, causal=True):
    # x: (n, d) token vectors; W_*: (d, d_k) learned projections
    Q, K, V = x @ W_q, x @ W_k, x @ W_v
    scores = Q @ K.T / math.sqrt(K.shape[-1])          # (n, n)
    if causal:
        n = x.shape[0]
        future = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(future, float("-inf"))
    weights = scores.softmax(dim=-1)                    # each row sums to 1
    return weights @ V, weights                         # (n, d_v), (n, n)

n, d, d_k = 10, 16, 8
x = torch.randn(n, d)
W_q, W_k, W_v = (torch.randn(d, d_k) / math.sqrt(d) for _ in range(3))
out, A = self_attention(x, W_q, W_k, W_v)
print(out.shape, A.sum(dim=-1))                         # (10, 8), all ones

# The same thing, fused and memory-efficient:
out2 = torch.nn.functional.scaled_dot_product_attention(
    (x @ W_q)[None], (x @ W_k)[None], (x @ W_v)[None], is_causal=True)
COMMON MISCONCEPTIONS
  • “Attention weights tell you exactly why the model made a decision.” They show where one head in one layer read from, which is a useful clue. But outputs depend on values, many heads, many layers and the MLPs between them. High attention is not the same as high influence.
  • “Queries, keys and values are different kinds of input.” All three come from the same token vectors, through three different learned matrices. In self-attention, every token plays all three roles at once.
  • “The √d scaling is a minor detail.” Without it, scores grow with head size and the softmax saturates, so gradients vanish and training becomes unstable.
  • “The causal mask makes the model only look at the previous token.” It allows looking at all earlier tokens, and at itself. It only forbids looking at later ones.
  • “Attention knows word order.” On its own it is order-blind: a weighted sum doesn’t care about positions. Order comes from positional encodings.

Check your understanding

0/5 answered
  1. Q1.In self-attention, what does the dot product q_i · k_j measure?

  2. Q2.Why are attention scores divided by √d_k?

  3. Q3.With a causal mask, which tokens can token 4 attend to?

  4. Q4.A row of attention weights is (0.7, 0.2, 0.1) and the value vectors are (1, 0), (0, 1), (1, 1). What is the output?

  5. Q5.You double the context length from 4,000 to 8,000 tokens. Roughly how does the size of the attention score matrix change?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.