Queries from one sequence, keys and values from another
The formula is identical to self-attention. The only thing that changes is where the three matrices come from.
- : the sequence doing the asking.
- : the sequence being read.
In self-attention all three come from the same tensor, so a sequence relates to itself. Here the query sequence interrogates a different one.
That single substitution is what connects two modalities or two languages, and it is the mechanism behind every encoder-decoder model.
The shapes, which is where the asymmetry shows
The attention matrix is rectangular, one row per output position and one column per input position.
The two sequences need not be the same length, the same modality, or the same vocabulary. They only have to share a model width.
The cost is the product of the two lengths rather than the square of one, which matters when a short query reads a long document.
One decoder block, in order
- Self-attention over the tokens generated so far, causally masked.
- Add and normalise.
- Cross-attention, with queries from that result and keys and values from the encoder output.
- Add and normalise.
- Feed-forward, then add and normalise again.
The encoder output is computed once for the whole generation, so its keys and values are cached and reused at every decoding step.
That cache is a different object from the KV cache of self-attention, and it never grows, because the source sequence does not change while the output is produced.
No mask, and why that is correct
Self-attention in a decoder is masked, because a token must not see its own future.
Cross-attention is not, because the entire source is available before generation begins and there is nothing to hide.
Those weights are also the closest thing a transformer has to an alignment.
In translation they line up source and target words, and they are readable in a way self-attention weights usually are not.
Where it appears now
Encoder-decoder models such as T5 and the original transformer use it in every decoder block, which is its classic home.
Multimodal models use it to let text queries read image patches, which is how a vision-language model conditions on what it was shown.
Text-conditioned diffusion is the same trick in reverse, with the image as the query sequence and the prompt as the source, which is exactly where the prompt enters the denoising network.