DL0026 Self-Attention vs Cross-Attention

What distinguishes self-attention from cross-attention in transformer models?

Answer

The distinction is where Q, K, and V come from. In self-attention, all three are projections of the same sequence, so every token weighs every other token within its own sequence, modeling internal dependencies. In cross-attention, the queries come from one sequence (e.g., the decoder state) while the keys and values come from a different sequence (e.g., the encoder output), letting one representation selectively read from another. Both use the identical scaled dot-product computation.

(1) Input Scope: Self-attention: Q, K, V from one sequence; cross-attention: Q from the target sequence, K/V from the source sequence.
(2) Architectural Role: Self-attention appears in encoder and decoder blocks; cross-attention is the bridge that injects encoder context into each decoder step.
(3) Score Matrix Shape: Self-attention produces an n \times n map; cross-attention produces n_{dec} \times n_{enc}, rectangular when lengths differ.

Side-by-side attention heatmaps: self-attention among the tokens The cat sat on the mat, and cross-attention from decoder queries to the encoder sequence The animal rested on a rug.

Figure 1: Same mechanism, different sources: self-attention relates tokens within one sentence; cross-attention aligns decoder tokens to a separate encoder sequence.

Mathematical Formulation:
\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V
Q = X_{q} W^Q, \quad K = X_{kv} W^K, \quad V = X_{kv} W^V

Where:

  • X_q is the query-source sequence; X_{kv} is the key/value-source sequence; self-attention is the special case X_q = X_{kv}.
  • W^Q, W^K, W^V are learnable projection matrices; d_k is the key dimension used for scaling.

Side-by-Side Comparison:

AspectSelf-AttentionCross-Attention
Q sourceSame sequenceTarget sequence (e.g., decoder)
K, V sourceSame sequenceDifferent sequence (e.g., encoder output)
ModelsIntra-sequence dependenciesInter-sequence alignment
Score matrixn \times n (square)n_{dec} \times n_{enc} (rectangular)
Typical locationEncoder & decoder blocksDecoder blocks (bridging to encoder)

Bottom line: self-attention answers “which of my own tokens matter to me?”; cross-attention answers “which tokens of the other sequence should I read now?”


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *