Sub topic 3
Cross-attention: how the decoder reads the source
Prerequisites and the main idea
This chapter assumes that you understand basic Python, tensors, neural-network loss functions, and the Transformer idea of self-attention.
An encoder-decoder model receives a source sequence and produces a target sequence. In translation, the source might be an English sentence and the target might be German. In summarisation, the source is a document and the target is a shorter text.
The encoder reads the complete source sequence and creates a contextual representation for each source token. The decoder then generates the target one token at a time. Cross-attention is the connection that lets the decoder consult the encoder's representations while it generates each token.
What cross-attention computes
At decoding step \(t\), the decoder has a hidden state that represents the target tokens generated so far. This state supplies a query. The encoder outputs supply keys and values:
- The query represents what information the decoder currently needs.
- Each key represents one source position.
- Each value contains the information stored at that source position.
The decoder compares its query with every source key. After scaling and applying softmax, these comparisons become attention weights. The decoder uses the weights to create a weighted sum of the source values.
A simplified expression is:
cross_attention(query, keys, values) =
softmax(query × keysᵀ / √d) × valuesHere, \(d\) is the key-vector size. The result is a context vector that combines the most relevant source information for the current decoding step.
Unlike decoder self-attention, cross-attention does not usually hide earlier source positions. The encoder has already processed the whole source, so the decoder can attend to any source token. Decoder self-attention still uses a causal mask, which prevents the decoder from seeing target tokens that have not been generated yet.
A small tensor example
The following code shows the core calculation for one decoder query. It uses PyTorch directly rather than a complete language model.
import math
import torch
torch.manual_seed(7)
# One decoder query and four encoder positions.
query = torch.randn(1, 1, 8)
keys = torch.randn(1, 4, 8)
values = torch.randn(1, 4, 8)
scores = query @ keys.transpose(-2, -1) / math.sqrt(keys.size(-1))
weights = torch.softmax(scores, dim=-1)
context = weights @ values
print("attention weights:", weights.squeeze(0).squeeze(0))
print("context shape:", context.shape)The attention weights contain four values because the encoder produced four source positions. They sum to one. A larger weight means that the current decoder state found that source position more relevant.
A real Transformer repeats this operation across many attention heads and layers. Each head can learn a different relationship, such as word alignment, grammatical agreement, or a connection between a named entity and its description. The resulting context is combined with the decoder's other computations before the model predicts the next token.
Why cross-attention matters
For translation, cross-attention helps the decoder align output words with relevant source words. Alignment is usually soft rather than a fixed dictionary lookup. One target word can use information from several source positions, and word order can change between languages.
For summarisation, cross-attention helps the decoder select important facts from the document. However, attention is not a guarantee that the output is factual. The decoder can combine source information incorrectly or generate plausible details that are not present.
| Component | Reads | Purpose |
|---|---|---|
| Encoder self-attention | All source tokens | Builds contextual source representations |
| Decoder self-attention | Earlier target tokens | Models the generated prefix |
| Decoder cross-attention | Encoder outputs | Selects source information for the next target token |
Common errors
- Confusing cross-attention with decoder self-attention. Cross-attention connects target-side states to encoder outputs.
- Applying a causal mask to the source by mistake. The decoder normally needs access to the complete encoded source.
- Assuming one attention peak equals a word-for-word alignment. Multiple heads and layers may distribute information across several positions.
- Ignoring padding masks. Without a source padding mask, the decoder may attend to artificial padding tokens.
- Treating cross-attention as fact checking. The model can still hallucinate during generation.
Exercise
If a decoder is generating the third target token, which information can its cross-attention use: only the first two source tokens, or all encoded source tokens?
Show answer
It can use all encoded source tokens, subject to the source padding mask. The causal restriction applies to the target-side self-attention, not normally to cross-attention.