Self Attention
Self-attention enables every token in a sequence to aggregate contextual information from all other tokens in parallel. Each token projects into Query (Q), Key (K), and Value (V) vectors, and softmax-normalized scaled dot products between Q and K weight the V vectors into updated token representations.


Understanding Self-Attention Using a Classroom Meeting Analogy
Overview
Imagine a classroom having a meeting to discuss organizing class activities:
1. Each Student Plays Three Roles
- Speaker (Query): Expressing what information or perspective they are looking for.
- Listener (Key): Advertising what topic or expertise they represent so others know how relevant they are.
- Contributor (Value): Supplying the actual information and suggestions to share.
2. Attention Scoring Process
Suppose Tom is trying to update his plan:
- He broadcasts his question: “I think our class needs a fun activity.” (his Query).
- Other students match against his Query based on their expertise (their Keys):
- Lucy, the sports representative, has relevant experience organizing activities (high match).
- Mike, the academic representative, is somewhat relevant for competitions (medium match).
- John, who is dozing off, offers no relevant input (low match).
3. Information Integration
- Tom forms a weighted blend of everyone’s suggestions (Values) according to the normalized attention weights:
- Heavily incorporates Lucy’s specific sports ideas.
- Moderately incorporates Mike’s competition ideas.
- Virtually ignores John’s irrelevant input.
4. Parallel Processing
- Unlike sequential recurrence, every student updates at once—simultaneously acting as a Query (seeking context), a Key (advertising relevance), and a Value (contributing content).
5. Final Effect
- Each token obtains an updated representation enriched by context across the entire sequence.
Mathematical Formulation
Given an input sequence matrix of tokens, learned projection matrices and produce:
Scaled Dot-Product Self-Attention computes:
- Why divide by ? If entries of and have zero mean and unit variance, their dot product has variance . Dividing by keeps logits at unit variance so softmax does not saturate into near-zero gradients for large .
- Complexity: Computing the attention matrix takes time and memory in sequence length .