Self-Attention Mechanism
Self-Attention is the soul of Transformer. It answers the question: when processing a word, how does the model know which other words in the sentence it should focus on?
An Intuitive Example
Consider the sentence "Xiaoming gave the apple to Xiaohong because he was hungry". Does "he" refer to Xiaoming or Xiaohong? A human sees at a glance that it is Xiaoming. Self-attention is what lets the model make the same judgment, by computing the strength of association between "he" and each word in the sentence.
The Three Roles of Q, K, V
Each word is converted into three vectors:
- Query: what I am looking for
- Key: what I am, and who can match me
- Value: the information I actually carry
The computation: take the dot product of Q with every K to measure similarity, normalize it into weights, then take the weighted sum over all V. The result is "a new representation that fuses contextual information".
Formula
Attention(Q,K,V) = softmax(QK^T / sqrt(d_k)) * V
Dividing by sqrt(d_k) prevents the dot products from growing too large and causing the softmax gradients to vanish.
Multi-Head Attention
A single attention head can capture only one kind of relationship. The multi-head mechanism runs several sets of Q/K/V in parallel so the model can understand from multiple angles at once: some heads focus on syntactic structure, some on coreference, and some on semantic similarity.
Computational Cost
The complexity of self-attention is O(n^2) (n is the sequence length). That means doubling the text length quadruples the computation. This is the core bottleneck of long-context processing today, and the target of optimization techniques such as FlashAttention and sparse attention.