Skip to main content
02

What is self-attention, and why transformers?

MediumTransformersAttention

What is self-attention, and why did transformers replace RNNs?

TL;DR

Self-attention lets every token look at every other token in the sequence and decide how much each one matters for its own meaning. Each token is projected into a query (what I'm looking for), a key (what I contain) and a value (what I pass on). Attention weights come from comparing queries with keys (a scaled dot product followed by softmax), and each token's new representation is the weighted sum of the values. In "the animal didn't cross the street because it was tired", attention lets "it" focus on "animal". Transformers replaced RNNs because attention processes all tokens in parallel (fast training on GPUs) and connects distant tokens directly, instead of passing information step by step.

Key points

  • Formula: Attention(Q, K, V) = softmax(QKᵀ / √d) · V. Dividing by √d keeps the softmax from saturating.
  • Multi-head attention: several attention heads run in parallel, each learning different relationships (syntax, coreference, position).
  • Causal masking: in decoder-only LLMs a token can only attend to earlier tokens, which is what makes next-token prediction work.
  • Positional information (such as RoPE) is added, because attention by itself ignores word order.
  • Cost: attention is O(n²) in sequence length, which is why long contexts are expensive. Optimizations include FlashAttention and the KV cache (reusing past keys and values during generation).
  • RNNs process sequentially, can't parallelize training, and struggle with long-range dependencies (vanishing gradients).

Example

text
"The cat sat on the mat because it was warm"
Attention from "it":  mat 0.61 · cat 0.22 · sat 0.05 · ...
→ "it" is represented mostly using "mat"

Common follow-ups

  • What's the KV cache? During generation, keys and values for earlier tokens don't change, so they're stored and reused. That saves compute but uses a lot of GPU memory on long contexts.
  • Encoder vs decoder? Encoders (BERT) attend in both directions and suit classification and embeddings. Decoders (GPT-style) are causal and suit generation.

What interviewers look for

Tip

An intuitive explanation (query, key, value), the formula, multi-head and causal masking, and the O(n²) cost.

  • Red flag: only reciting the formula with no intuition for what attention does.

Was this helpful?

Related questions