What is the difference between self-attention and cross-attention?
Last updated
Both use the same scaled dot-product attention. The difference is where Q, K and V come from. In self-attention all three come from the same sequence. In cross-attention the queries come from one sequence and the keys and values come from another.
Self-attention:
Q = XW_Q, K = XW_K, V = XW_Vall come from the same inputX.Each token builds a context-aware representation by mixing in information from the other tokens of its own sequence.
Used in encoder layers (bidirectional) and decoder layers (with a causal mask).
Cross-attention:
Q = YW_Qcomes from the decoder or target stream.K = XW_K, V = XW_Vcome from the encoder output or another modality.Each target position asks: "which parts of the source are relevant to me?"
Examples: an encoder-decoder translation model attending to the source sentence, or text-to-image diffusion attending to text embeddings.
Shape consequence:
Self-attention scores are
n × n. Cross-attention scores aren_q × n_kv, so the two sequence lengths can differ.The output always has one row per query, so it follows the query sequence's length.
Masking: cross-attention usually needs no causal mask, because the whole source is visible. It typically uses only a padding mask on the keys.