Advanced level · Module 5: Attention Mechanisms in NLP · Lesson 3 of 3
Self-Attention, Queries, Keys and Values
Learners compute scaled dot-product self-attention by hand and in PyTorch, the core operation of transformers.
In this lesson you will
- Compute scaled dot-product attention
- Explain queries, keys, values and multiple heads
Key concepts
self-attentionquery, key, valuesoftmax(QKᵀ/√d)Vmulti-head attentionnn.MultiheadAttention
The lesson
In self-attention, every token attends to every other token in the same sequence. Each token's vector is projected into a query, a key and a value. The output is softmax(QKᵀ / √d) V, where d is the key dimension; dividing by √d keeps the scores in a range where softmax works well.
Self-attention lets 'it' in 'The office closed the portal because it was overloaded' attend directly to 'portal', regardless of distance, and all positions are computed in parallel, unlike an RNN.
Multi-head attention runs several attention operations with different projections and concatenates them, so different heads can capture different relations. PyTorch provides nn.MultiheadAttention.
Step by step
- Compute self-attention by hand for three tokens with two-dimensional vectors.
- Implement the formula in PyTorch and check it against your hand calculation.
- Run nn.MultiheadAttention on the same input and inspect the shapes.
- Explain why self-attention handles long-range links better than RNNs.
Practice activity
Implement scaled dot-product self-attention and verify it against a hand calculation.
Expected result: Matching hand and code results, with a clear explanation of each component.
Check your understanding
-
Why divide by √d in attention?
Show answer
To keep scores in a range where softmax gives useful, not extreme, weights.
-
What advantage does self-attention have over RNNs?
Show answer
Direct connections between any positions and parallel computation.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.