Self-attention and cross-attention are two fundamental mechanisms in transformer architectures, each serving distinct roles in processing sequences. This article clarifies their differences and applications.
Self-Attention allows each token in a sequence to attend to every other token within the same sequence. It is the backbone of transformer encoders and decoders, enabling the model to capture contextual relationships. For example, in language models like BERT, self-attention helps understand how words like "bank" relate to their surroundings (e.g., "river bank" vs. "bank account").
Cross-Attention involves attending to a different sequence. In the transformer decoder, cross-attention layers allow the decoder to focus on relevant parts of the encoder's output. This is crucial for tasks like translation, where the decoder must align with the input sentence.
In summary: self-attention builds intra-sequence relationships, while cross-attention builds inter-sequence connections. Combined, they power models like GPT and T5.