Sub topic 3
Cross-attention: how the decoder reads the source
This chapter explains the one layer that connects the two halves of an encoder-decoder model. It assumes you know self-attention (queries, keys, values, softmax over scores) and the encoder-decoder layout from the previous chapter. It also assumes basic PyTorch and the Hugging Face Transformers API.
Why the decoder needs a separate way to read the source
The encoder reads the whole source text and produces one vector per source token. The decoder writes the target text one token at a time. At each step it must decide which parts of the source matter right now.
A summariser needs to find the sentence it is paraphrasing. A translator needs to find the source word that corresponds to the target word it is about to write. Cross-attention gives the decoder this lookup. Without it, the decoder would only see its own previous output and have no access to the source.
Early sequence-to-sequence models compressed the entire source into a single fixed-size vector. Long inputs lost detail in that vector. Attention removed the bottleneck: the decoder keeps access to every encoder output and chooses among them at each step.
The mechanism
Cross-attention uses the same scaled dot-product formula as self-attention. The difference is where the queries, keys and values come from.
- Queries come from the decoder's current hidden states.
- Keys and values come from the encoder's final output.
For one head, the computation is:
- Project decoder states into queries:
Q = D · Wq. - Project encoder outputs into keys and values:
K = E · Wk,V = E · Wv. - Score every decoder position against every source position:
S = Q · Kᵀ / sqrt(d). - Apply softmax over the source axis, so each decoder position gets weights that sum to 1.
- Take the weighted sum of the values:
C = softmax(S) · V.
Each row of C is a summary of the source tailored to one decoder position. The decoder adds it back into its hidden state through a residual connection.
The shapes make the idea concrete. With T decoder positions and S source positions, the score matrix is T × S. Its rows are indexed by target tokens and its columns by source tokens. Self-attention in the encoder produces an S × S matrix. Masked self-attention in the decoder produces a T × T matrix.
A minimal implementation
This single-head version uses random tensors. It shows the shapes and the fact that every row of weights sums to 1.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
d = 8
src_len, tgt_len = 5, 3
encoder_out = torch.randn(src_len, d) # one vector per source token
decoder_state = torch.randn(tgt_len, d) # one vector per target position
Wq = torch.randn(d, d)
Wk = torch.randn(d, d)
Wv = torch.randn(d, d)
Q = decoder_state @ Wq # (tgt_len, d)
K = encoder_out @ Wk # (src_len, d)
V = encoder_out @ Wv # (src_len, d)
scores = Q @ K.T / d ** 0.5 # (tgt_len, src_len)
weights = F.softmax(scores, dim=-1) # softmax over source positions
context = weights @ V # (tgt_len, d)
print(weights.shape) # torch.Size([3, 5])
print(weights.sum(dim=-1)) # each row sums to 1
print(context.shape) # torch.Size([3, 8])Real models differ in three ways. They use several heads, each with its own projections, and concatenate the results. They apply a padding mask so that padded source positions get a score of negative infinity before the softmax. They stack the layer in every decoder block, and each layer has its own Wq, Wk and Wv.
Differences from the other attention layers
| Property | Encoder self-attention | Decoder masked self-attention | Cross-attention |
|---|---|---|---|
| Queries from | Encoder states | Decoder states | Decoder states |
| Keys and values from | Encoder states | Decoder states | Final encoder output |
| Score matrix shape | source × source | target × target | target × source |
| Causal mask | No | Yes | No |
| Padding mask | Source padding | Target padding | Source padding |
Cross-attention needs no causal mask. The whole source is known before generation starts, so every target position may look at every source position. The causal restriction applies only to the target side.
Every decoder layer attends to the same final encoder output. It does not attend to the encoder's intermediate layers. Different decoder layers can still learn different lookups, because their projection matrices differ.
Inspecting cross-attention weights
Hugging Face models return attention weights when you ask for them. The cross_attentions field holds one tensor per decoder layer, each shaped (batch, heads, target_len, source_len).
The next script runs a translation model on a source and target pair. It averages the heads of the last layer and prints, for each target token, the source token with the highest weight. It loads the model with attn_implementation="eager" because fused attention kernels do not return weights.
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-de"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name, attn_implementation="eager")
model.eval()
batch = tokenizer(
"The weather is nice today.",
text_target="Das Wetter ist heute schön.",
return_tensors="pt",
)
with torch.no_grad():
out = model(**batch, output_attentions=True)
print(len(out.cross_attentions), out.cross_attentions[0].shape)
last_layer = out.cross_attentions[-1][0].mean(dim=0) # (target_len, source_len)
src_tokens = tokenizer.convert_ids_to_tokens(batch["input_ids"][0])
tgt_tokens = tokenizer.convert_ids_to_tokens(batch["labels"][0])
for i, tgt in enumerate(tgt_tokens):
j = last_layer[i].argmax().item()
print(f"{tgt:>12} -> {src_tokens[j]:<12} weight {last_layer[i, j]:.2f}")Row i of the matrix belongs to the decoder step that predicts labels[i]. The decoder input is the labels shifted right by one position, so the model produces this alignment while it predicts each token.
You will often see the German Wetter attend to weather. Do not expect clean alignments everywhere. Averaging heads blurs the picture. Many heads attend to the end-of-sequence token or to punctuation, which acts as a place to put weight when nothing in the source is relevant.
What cross-attention does during generation
During training, all target positions are processed in parallel and the score matrix is computed in one pass. During generation, the decoder produces one token per step, so each step adds one new query row.
The keys and values depend only on the encoder output, which does not change during generation. Implementations compute them once and store them in the cache. Each new step then needs only a new query against the stored keys. The cost of cross-attention per step is proportional to the source length. Over a full output of T tokens it is proportional to T × S.
Two consequences follow.
- Memory for the cross-attention cache grows with source length and with the number of beams. Beam search with
num_beams=4stores four copies of the per-beam state. Long sources with many beams can run out of GPU memory. - The source length that the encoder accepts sets a hard limit. Anything beyond it never reaches the keys, so the decoder cannot attend to it. The later chapter on long inputs covers this.
Behaviour in summarisation and translation
The two tasks use the same layer but the weights look different.
In translation, attention often follows an approximate diagonal. The decoder moves through the source in roughly the same order as it writes the target. Departures from the diagonal appear where word order differs between languages. An example is a German verb that moves to the end of the clause, where the decoder jumps back to the English verb.
In summarisation, attention is spread and jumpy. The decoder may focus on one sentence for several tokens, then skip to a different paragraph. Many source tokens receive almost no weight, which corresponds to the content that the summary drops.
A related failure mode appears when cross-attention fails to anchor the output in the source. If the weights are diffuse or focused on special tokens while the decoder keeps writing fluent text, the language modelling ability of the decoder takes over. The output reads well but includes content that is not in the source. This is one mechanism behind hallucination, which a later chapter covers. A second mechanism is repetition, where the decoder attends to the same source span again and again. Some older systems added a coverage penalty to discourage this. Modern decoding settings such as no_repeat_ngram_size address the symptom on the output side instead.
Common errors
- Reading the matrix the wrong way round. Rows are target positions and columns are source positions. Transposing it gives a misleading plot.
- Forgetting
attn_implementation="eager". With fused kernels,output_attentions=Truemay returnNoneor print a warning, depending on the library version. - Ignoring padding. In a padded batch, the matrix includes padded columns. Their weights are zero after masking, but plots that skip the mask can show strange values at the end.
- Inspecting only one head or layer. Heads specialise, so a single head can show no alignment while another shows a clean one.
- Mixing up the shifted decoder input. The decoder input at position
iis the previous label, so the weights in rowiare computed before the model seeslabels[i].
Summary of the working model
- Cross-attention takes queries from the decoder and keys and values from the final encoder output.
- Its score matrix is target length by source length, with a padding mask on the source and no causal mask.
- Each decoder layer has its own cross-attention, and during generation the keys and values are computed once and cached.
- The weights can be read out for inspection, but they do not prove why a token was produced.
Exercise
A model translates a source of 20 tokens into a target of 25 tokens, using 8 heads and 6 decoder layers. What shape does out.cross_attentions[2] have for a batch of 1, and why does the source dimension not depend on the decoder's causal mask?
Show answer
The shape is (1, 8, 25, 20): batch, heads, target length, source length. The tuple has one entry per decoder layer, so index 2 is the third layer. The source dimension is unaffected by the causal mask because the whole source is known before decoding begins, so every target position may attend to every source position. The causal mask is applied only inside the decoder's own self-attention.
Exercise
In the minimal implementation, what would you change so that a padded source position, for example the last of 5 source tokens, receives zero attention weight?
Show answer
Before the softmax, set the score column for the padded position to negative infinity, for example scores[:, -1] = float("-inf"), or use scores.masked_fill(mask, float("-inf")) with a boolean mask over source positions. The softmax then gives that column a weight of exactly 0 and the remaining weights in each row still sum to 1.
Exercise
Why does beam search with a long source use more memory than greedy search with the same source, and which part of the model is responsible for the growth that depends on source length?
Show answer
Beam search keeps several candidate sequences alive at once, and each one needs its own cached state. The cross-attention cache holds keys and values for every source position, in every decoder layer, so its size grows with source length. Multiplying by the number of beams multiplies that cache, so a long source combined with a large num_beams can exhaust GPU memory.