Walk me through how transformers work
Written by the mlprep team · Updated
Walk me through how transformers work. Start from the architecture — what's the core idea and why did it replace RNNs?
The transformer replaced RNNs by eliminating sequential computation entirely. RNNs process tokens one at a time — each hidden state depends on the previous one, which makes parallelization impossible and makes it hard to learn long-range dependencies. Transformers process all tokens simultaneously using attention.
The core idea: attention#
Instead of passing a hidden state down a chain, every token in the input attends directly to every other token. Attention computes a weighted sum of value vectors, where the weights come from how much each token's query matches another token's key.
The formula is:
Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V
Q, K, V are linear projections of the input embeddings. The dot product QKᵀ gives raw compatibility scores between every pair of tokens. Dividing by √d_k prevents the dot products from growing too large and pushing softmax into flat gradient regions. Then softmax normalizes these into weights, and the weighted sum of V gives each token a new representation that aggregates information from the whole sequence.
Multi-head attention#
Rather than running one attention pass, transformers run h attention heads in parallel — each with its own learned Q, K, V projections into a smaller subspace. The idea is that different heads learn to attend to different kinds of relationships (syntactic structure, coreference, positional proximity). Their outputs are concatenated and projected back.
The full architecture#
An encoder block stacks: multi-head self-attention → add & layer norm → feed-forward network → add & layer norm. The feed-forward network applies two linear layers with a non-linearity (typically GELU) independently to each token position. It's where most of the model capacity lives.
Decoders add a cross-attention layer that lets the decoder attend to encoder outputs. For language models (GPT family), there's no encoder at all — just a decoder with causal masking so each token can only attend to previous positions.
Residual connections around each sublayer let gradients flow directly from output to input, making very deep stacks trainable. Layer norm stabilizes the distribution of activations.
Why transformers won#
Training is fully parallelizable. Attention directly connects any two tokens regardless of distance, solving the long-range dependency problem. And the architecture scales extraordinarily well — throw more compute and data at it, and performance keeps improving.
You mentioned the attention formula — queries, keys, and values. Why that specific framing? And what does "scaling by √d_k" actually prevent?
The Q/K/V framing is a retrieval metaphor. Think of it like a soft dictionary lookup: your query says "what am I looking for," each key says "what do I store," and the value is the actual content retrieved. Attention finds all keys that match your query (via dot product similarity), weights them through softmax, and returns the blended values.
The scaling problem#
As embedding dimension d_k grows, the dot products QKᵀ grow in magnitude too. If you have two random vectors of dimension d_k with unit variance, their dot product has variance d_k. So for d_k = 512, the raw dot products can be in the range of ±20 or so.
When you pass large values into softmax, it saturates — the highest score gets weight ~1 and everything else gets weight ~0. You lose the soft blending entirely, attention collapses to hard selection, and more importantly the gradients of softmax become nearly zero. Training stalls because no learning signal flows back through the attention weights.
Dividing by √d_k keeps the dot products in a variance-1 regime regardless of dimension. The gradients stay healthy throughout training.
A concrete intuition#
Imagine d_k = 4: dot products on the order of ±2, softmax distributes attention across multiple tokens, gradients are meaningful.
Now d_k = 512 without scaling: dot products might be ±22, softmax picks one winner with near-certainty, gradients vanish. All heads collapse to attending to a single token. This is exactly what was observed empirically before the fix was standard.
One more: transformers need positional encoding. Why — and what are the tradeoffs between sinusoidal and learned embeddings?
Attention is permutation-invariant. If you shuffle the input tokens, the attention weights rearrange accordingly but the output is the same shuffle of outputs. There's no notion of "token 3 came before token 7." For most tasks — language, code, time series — order is everything, so you have to inject position information explicitly.
Sinusoidal encoding (original transformer)#
The original paper adds a fixed function of position to each token embedding before the first layer:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
Different dimensions encode position at different frequencies — lower dimensions capture coarse position, higher ones fine-grained. The key property: the encoding for position pos+k can be expressed as a linear function of the encoding for pos, which means relative positions are easy to learn from.
Advantage: zero extra parameters, works at inference on sequence lengths not seen during training (you can just compute the formula for position 10,000 even if you only trained to 512).
Learned embeddings (BERT, GPT)#
Just add a trainable vector for each position, learned end-to-end. Simpler to implement and usually performs at least as well.
Disadvantage: you can only generalize to sequence lengths seen during training. Position 513 has no learned embedding if you trained to 512.
Modern approaches#
Both sinusoidal and learned are absolute encodings — they say "this is position 37" not "this token is 5 positions from that token." RoPE (Rotary Position Embedding, used in LLaMA and most modern LLMs) encodes relative positions by rotating the Q and K vectors before the dot product. ALiBi adds a position-based bias directly to attention logits. Both handle longer sequences at inference better than the original approaches and have become the default.
Senior/staff considerations#
A senior answer should connect the architecture to scaling and serving constraints:
- Attention is expressive because every token can condition on every other token, but vanilla attention is O(n²) in sequence length for compute and memory. Long-context systems need FlashAttention, KV-cache management, sliding-window attention, chunking, retrieval, or sparse patterns.
- Decoder-only models dominate generative LLMs because causal next-token prediction scales cleanly with web-scale text and serving can reuse KV cache. Encoder-only models are still strong for classification and retrieval embeddings; encoder-decoder models remain useful for constrained sequence-to-sequence tasks.
- Pre-LN transformer blocks train deeper models more stably than the original Post-LN layout because gradients have a cleaner residual path.
- The feed-forward network often contains most parameters and compute, so MLP variants, activation choice, and mixture-of-experts matter as much as attention in large models.
- Positional methods are not implementation details. RoPE scaling, context extrapolation, and attention masks directly affect long-context quality.
Interview red flags#
- Explaining only Q/K/V without mentioning residuals, layer norm, MLP blocks, masking, and positional information.
- Saying transformers "understand order" without explaining that attention itself is permutation-equivariant.
- Ignoring O(n²) cost and KV-cache memory in production.
- Treating all transformers as encoder-decoder models; most modern LLMs are decoder-only.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Transformers replaced RNNs by computing attention across all token pairs simultaneously — no sequential bottleneck, no vanishing gradient over long distances. Self-attention is a learned soft lookup: queries find matching keys, retrieve blended values. Scaling by √d_k prevents softmax saturation. Positional encoding is necessary because attention itself is order-blind.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How does masked self-attention in a decoder differ from encoder self-attention, and why is the mask necessary?
- What are the computational complexity tradeoffs of attention, and how do approaches like flash attention or sparse attention address them?
- How would you explain to a product team why a transformer fine-tuned on domain data often beats a larger general model?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions