What is the difference between self-attention and cross-attention?

Last updated 22 November 2026

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_V all come from the same input X.

    • 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_Q comes from the decoder or target stream. K = XW_K, V = XW_V come 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 are n_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.

  • https://medium.com/@xiaxiami/self-attention-vs-cross-attention-from-fundamentals-to-applications-4b065285f3f8
  • https://medium.com/@virenm.meena/deep-learning-fundamentals-interview-questions-answers-bb61958547ca
  • https://www.interviewbit.com/varsity/blog/self-attention/
All Transformers interview questions