Deep LearningAdvanced22 min read5 questions

Transformers & Attention: The Full Derivation

The most-asked architecture question in AI interviews. Derive scaled dot-product attention, explain the √d, and know why grouped-query attention exists.

Covers: Self-attention math, multi-head attention, positional encodings, KV cache, FlashAttention, MHA vs GQA vs MLA

If you interview for anything touching LLMs, you will be asked to explain attention. The bar is not 'can you recite the formula' — it is 'can you explain each term, justify the scaling factor, and reason about the memory and compute consequences at inference time'.

Filter
0/5 mastered
AdvancedattentiontransformersderivationAsked at OpenAI, Anthropic

30-second answer

Attention(Q,K,V) = softmax(QKᵀ/√d_k)V. Each query is compared to every key by dot product to produce relevance scores; softmax turns them into weights; the output is a weighted average of values. The √d_k divisor exists because the dot product of two independent d_k-dimensional unit-variance vectors has variance d_k — without normalisation the logits grow with dimension, softmax saturates, and gradients vanish.

Advancedmulti-headgqamqaAsked at OpenAI, Anthropic

30-second answer

One head produces a single averaged attention distribution, so it can only attend one way at a time. Splitting d_model into h heads lets each learn a different relation — syntactic dependency, coreference, positional locality — in parallel, at identical total FLOPs. MQA shares one K/V pair across all query heads and GQA shares one per group; both exist to shrink the KV cache, which is the dominant memory cost in long-context serving.

Advancedpositional-encodingropealibiAsked at Meta AI, Mistral

30-second answer

Self-attention is permutation-equivariant — shuffle the input tokens and the outputs shuffle identically, so word order carries no information without positional signal. Sinusoidal encodings are fixed and extrapolate weakly; learned embeddings are flexible but hard-capped at the trained length; ALiBi adds a distance-proportional bias to attention scores and extrapolates well; RoPE rotates Q and K by position-dependent angles so attention naturally depends on relative position, and is the modern default because it extrapolates and can be interpolated to extend context.

ExpertflashattentiongpumemoryAsked at NVIDIA, Together AI

30-second answer

Standard attention writes the n×n score matrix to HBM and reads it back several times — it is memory-bandwidth-bound, not compute-bound. FlashAttention tiles Q, K and V into blocks that fit in on-chip SRAM and uses the online-softmax trick to compute the exact result without ever materialising the full matrix. Same maths, O(n) memory instead of O(n²), and 2–4× faster because HBM traffic drops by an order of magnitude.

AdvancedtransformersarchitectureparametersAsked at OpenAI, Anthropic

30-second answer

Each block is: x + Attention(Norm(x)), then x + FFN(Norm(x)). Attention contributes 4d² parameters (Q, K, V, O) and the FFN contributes 8d² with SwiGLU (or 8d² with a 4d ReLU MLP). So ~12d² per layer, giving N ≈ 12·L·d² total plus embeddings. Forward FLOPs are about 2N per token and a full training step is about 6N per token (forward + backward).

Showing 5 of 5 questions for transformers-and-attention-explained.

Check your understanding

5 questions · no sign-up, nothing stored

0/5 answered
Question 1

1.Attention divides by √d_k because:

Question 2

2.Grouped-query attention (GQA) primarily exists to:

Question 3

3.RoPE's defining property is that:

Question 4

4.FlashAttention achieves its speedup by:

Question 5

5.A rough estimate of the FLOPs to train a model with N parameters on T tokens is:

Hands-on challenge

Build it — this is what you talk about in a deep-dive round.

Implement a GPT-style transformer from scratch

Write a small decoder-only transformer with modern components and train it on a toy corpus.

Requirements

  • RMSNorm, RoPE, grouped-query attention with a working KV cache, and a SwiGLU FFN.
  • Verify your attention matches `F.scaled_dot_product_attention` to 1e-5.
  • Implement generation with the KV cache and demonstrate the speedup versus recomputing each step.
  • Write a parameter counter and FLOP estimator; check them against your actual model.

Stretch goals

  • Implement the tiled online-softmax attention from question 4 and confirm it is exact.
  • Add YaRN or NTK-aware RoPE scaling and evaluate needle-in-a-haystack accuracy beyond the trained length.