Self-attention and multi-head attention

Self-attention trained live in your browser: every Q, K, V, scaled score, causal mask, softmax and weighted sum, multi-head split and concat, and the patterns each head learns.

Updated

  • Queries, keys and values
  • Scaled dot-product attention
  • The causal mask
  • Multiple heads, split and concatenated
  • Position-based vs content-based attention
q1k1q2k2q3k3q4k4q5k5q6k6q7k7q8k8q9k9softmax(QKᵀ/√dₖ)·VQ · Kᵀ÷ √dₖsoftmax
Preparing the lab…

Intuition

A soft table lookup

To write 8 digits backwards, output position 1 needs the last input, position 2 the second-to-last, and so on: everything each position needs is somewhere else. Attention is a "soft" table lookup: the query is compared with every key, the more alike the larger the weight, and the result is the weighted average of the values. When all the weight lands on one position, it becomes an exact lookup.

The three small labs below really train the same model in your browser (one attention layer, 2 heads, width 16). Each picture is the attention matrix for the first evaluation sample: rows are query positions, columns the positions looked at, and darker means more weight. Below, x is the input and ŷ the model's output at each position (green right, red wrong).

Random weightsPreparing…
40 training stepsPreparing…
100 training stepsPreparing…

At first every position looks at all positions about equally, and per-position accuracy is 10.2% (guessing gives 10%). At 40 steps per-position accuracy is 77.3%, but only 7.4% of sequences are entirely right. After 100 steps the attention is a clear anti-diagonal — position tt looks at position 7−t7-t — and everything is right.

Math

Queries, keys and values

The input is TT position vectors (token embedding plus position embedding), each DD-dimensional, stacked into a matrix XX. Three learned linear maps give

Q=XWQ+bQ,K=XWK+bK,V=XWV+bVQ = XW_Q + b_Q,\qquad K = XW_K + b_K,\qquad V = XW_V + b_V

The score of position tt for position ss is qt⋅ks/dkq_t\cdot k_s/\sqrt{d_k}; a softmax over each row gives the weights atsa_{ts}, and the output is ot=∑sats vso_t = \sum_s a_{ts}\, v_s.

Why divide by dk\sqrt{d_k}: if the components of qq and kk have variance 1, their dot product has variance dkd_k. Without scaling, scores grow with the dimension, the softmax becomes almost one-hot, and the gradients become tiny and hard to train.

Multiple heads and the causal mask

Split the DD dimensions into HH parts; each head computes attention in its own dk=D/Hd_k = D/H dimensions, and the outputs are concatenated and multiplied by WOW_O. Different heads can attend to different positions or different features at the same time.

Causal mask: when generating text, position tt must not peek ahead, so scores with s>ts > t are set to −∞-\infty before the softmax and their weights are 0. The upper-right triangle of the attention map is therefore empty.

Where position comes from: attention by itself only looks at content; shuffle the input order and each position's result simply moves with it. Position information therefore has to be added to the input; this page uses learned position embeddings.

Three tasks, three patterns

Previous (causal)Preparing…
Running maximum (causal)Preparing…
Reverse, 4 headsPreparing…

Average weight that the head best at looking in the right place puts on "where it should look", over 64 evaluation samples:

TaskRuleWhere to lookRandom weightsTrained
Reverseyt=x7−ty_t = x_{7-t}Mirror position0.1260.986 (100 steps)
Previousyt=xt−1y_t = x_{t-1}Previous position—0.974 (100 steps)
Running maximumyt=max⁡(x0..xt)y_t = \max(x_0..x_t)Where the maximum is—0.911 (200 steps)

The first two tasks look at a fixed relative position, so the attention map is a diagonal line; the running maximum looks by content, and every sample's map is different. With 4 heads on the reverse task the best head reaches 0.992 and the other three lie between 0.669 and 0.869: the task needs only one head, and the others merely "help".

How fast it trains

Reverse task (per position / whole sequence right):

Steps020406080
Per position10.2%23.8%77.3%99.9%100%
Whole sequence007.4%99.2%100%

Lowering the learning rate from 0.01 to 0.001 gives only 54.6% at 200 steps; it takes 400 steps to get everything right. With sequences of length 12 it is still fully right at 100 steps.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: attention learns where to look

5 steps · each one: set up and run → look → answer

  1. 1. Getting started

    The default reverse task, 20 training steps. Open "Heads".

    Why is the attention map almost uniform?
  2. 2. The anti-diagonal

    Train to 60 steps.

    The attention map has become a line from top right to bottom left. Why that shape?
  3. 3. Looking at the previous one

    Switch the task to "Previous".

    Why is the upper-right triangle empty?
  4. 4. Looking by content

    Switch to "Running maximum".

    Why is this attention map not a fixed diagonal line?
  5. 5. Four heads

    Back to reverse with 4 heads; open "Heads".

    Have all four heads become anti-diagonals?

Try these settings

Exercises

Exercises

Exercise 1: learning too slowly

At learning rate 0.001, 200 steps give only 54.6%. Change the settings to get at least 99% of whole sequences right within 100 steps.

Hint

Set the learning rate back to 0.01: everything is right after 80 steps.

  • Whole sequence ≥ 99.0%
  • at most 100 steps

Exercise 2: running maximum

Looking by content is a little harder than looking at a fixed position. Within 200 steps, get at least 99% of whole sequences right on the running-maximum task.

Hint

Learning rate 0.01: fully right at 200 steps.

  • Whole sequence ≥ 99.0%
  • at most 200 steps

Quiz

Why are attention scores divided by √dₖ?
What does the causal mask do?
Without position embeddings, could self-attention do the “reverse” task?

Further reading

Frequently asked questions

What is self-attention?

Each position in a sequence compares its query with every position's key, turns the similarities into weights with softmax, and takes the weighted sum of the values. "Self" means the queries, keys and values all come from the same sequence.

What are queries, keys and values?

All three come from the input vectors through different linear maps. The query says "what I am looking for", the key "how I can be found", and the value "what I provide once found". Separate maps let "matching" and "what to take" be learned as different things.

What is the benefit of multi-head attention?

Several smaller attentions run in parallel, each free to focus on different positions or features, and their outputs are concatenated. The total cost is about the same as one large head. On this page's reverse task only one of 4 heads actually does the reversing: multiple heads give the model room, but not every head has to be useful.

Can attention weights be used as an explanation of the model?

With care. The weights show where a layer took information from, but how the values taken affect the output after later transformations needs separate analysis, and in multi-layer models information gets mixed layer after layer. Only in a model like this page's, with one layer and a clear task, do the weights line up with the rule.

How much computation does self-attention take?

A sequence of length T needs T × T scores, so computation and memory grow as T², the main bottleneck for long texts; FlashAttention, sparse attention and linear attention all address it.

Further reading