SDE & MLE Prep

Attention & Transformers

Q: Explain self-attention and the transformer block.

Each token builds a query, key and value; it attends to all tokens with weights softmax(QKᵀ / √d_k) and mixes their values: Attention(Q, K, V) = softmax(QKᵀ/√d_k + mask) V.

  • √d_k keeps dot products from growing with dimension (which would saturate softmax).
  • Multi-head: h parallel attentions in lower-dimensional subspaces, concatenated → different heads capture different relations.
  • Causal mask (decoder) blocks attention to future tokens.
  • Block: x + MHA(LN(x)) then x + FFN(LN(x)) (FFN ≈ 4× hidden, GELU/SwiGLU).
  • Cost: O(n²·d) time and O(n²) memory in sequence length → FlashAttention (IO-aware exact attention), sparse/linear attention, sliding windows.
  • Variants: encoder-only (BERT: bidirectional, classification/embedding), decoder-only (GPT: generation), encoder-decoder (T5, translation).
tokens -> embed + position -> [ LN -> multi-head attention -> + ] -> [ LN -> FFN -> + ] x N -> LN -> logits
                                 \_______ residual ________/          \___ residual __/