Multi-head attention runs several attention computations with different learned parameters. A single softmax-weighted sum can wash out individual token features; separate heads give the model multiple ways to select and combine information. section 15.3.1
Different relationships in a sentence
For a target word, one head might learn to attend to the subject of a source sentence, while another attends to punctuation. In self-attention, “station” in “The train left the station on time” could attend strongly to “train,” helping represent the word in context. section 15.3.1 section 15.3.2
Each head projects the query, key, and value, scores query–key matches, and uses softmax weights to combine values. The head outputs are concatenated and passed through an output projection. Different projections let heads learn different matches rather than relying on one weighted sum. section 15.3.1
Figure 15.7 Multi-headed attention allows each target word to attend to different parts of the source sequence in separate partitions of the eventual output vector.
See how separate heads attend to different parts of the source and contribute to the output vector. section 15.3.1
Self-attention with Keras
Given a sequence `source` and chosen dimensions, create and call a reusable layer: `attention = keras.layers.MultiHeadAttention(num_heads, hidden_dim // num_heads)` `output = attention(query=source, key=source, value=source)` Using the same sequence for query, key, and value lets each token attend to its own sequence. section 15.3.2
Choose inputs and masks for the job:
- For encoder self-attention, use the source sequence as query, key, and value; a source mask can exclude padding. section 15.3.2
- For decoder cross-attention, use the target sequence as query and the encoder output as key and value; mask source padding. section 15.3.3
- For decoder self-attention, use a causal mask so each target position can attend only to itself and earlier positions. Otherwise, it can see future tokens during prediction. section 15.3.3
Attention alone is not a complete Transformer block: add a nonlinear feed-forward component. Encoder and decoder blocks also use residual connections and layer normalization. section 15.3.2 section 15.3.3














