Self-Attention
Compute contextual token representations through scaled dot-product attention between Q and K matrices with causal masking.
Self-attention lets each word 'ask a question' to every other word in the sentence: 'How relevant are you to me?'. The answer determines how much each word influences the others. For example, in 'The cat sat on the mat because it was tired', when computing the meaning of 'sat', attention focuses heavily on 'cat' (the actor) and 'mat' (the location), dynamically connecting context.
This is the exact mechanism that powered the ChatGPT revolution. In autoregressive decoders (like GPT), causal masking prevents the model from looking ahead at future tokens during training, training it to reliably predict the next token one step at a time.
Scaled Dot-Product Attention Formula
Attention Weight Matrix (A_ij)
Rows: Query tokens (attending from) | Columns: Key tokens (attending to)
- Attention pipeline: Q * K^T -> scale by sqrt(d_k) -> causal mask -> softmax -> multiply by V.
- Causal masking forces decoders (GPT) to look backward only; removing it creates bidirectional encoders (BERT).
- Scaling by sqrt(d_k) = 4 prevents gradient vanishing caused by softmax saturation on large dot products.
- Softmax normalizes attention weights so each query distributes exactly 100% of its representation budget.
Toggle the causal mask on and off. Notice how the upper triangle flips from 0% (masked future) to active bidirectional attention weights.